Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add preprocessor
  • Loading branch information
septs committed Jan 5, 2021
commit b9a28df4a991117cfce049dd26f4cb569be2ecf2
12 changes: 11 additions & 1 deletion lib/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { JSONSchema4, JSONSchema4Type, JSONSchema6, JSONSchema6Type } from "json-schema";
import { RequestInit } from "node-fetch";
import { Request, RequestInit } from "node-fetch";

export = $RefParser;

Expand Down Expand Up @@ -240,6 +240,16 @@ declare namespace $RefParser {
* Provide `RequestInit` on HTTP Resolver
*/
requestInit?: RequestInit;

/**
* pre process `Request` object on HTTP Resolver
*
* e.g:
* 1. modify request method
* 2. re-mapping url
* etc
*/
preprocessor?(request: Request): Request;
}

/**
Expand Down
23 changes: 21 additions & 2 deletions lib/resolvers/http.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
"use strict";

const fetch = require("node-fetch").default;
const Request = require("node-fetch").Request;
const { ono } = require("@jsdevtools/ono");
const url = require("../util/url");
const { ResolverError } = require("../util/errors");

module.exports = {
module.exports = { /**
* The order that this resolver will run, in relation to other resolvers.
*
* @type {number}
*/
order: 200,

/**
* fetch RequestInit defintion
*
Expand All @@ -17,6 +24,16 @@ module.exports = {
timeout: 5000
},

/**
* HTTP Request preprocessor
*
* @param {Request} request
* @returns {Request}
*/
preprocessor (request) {
return request;
},

/**
* Determines whether this resolver can read a given file reference.
* Resolvers that return true will be tried in order, until one successfully resolves the file.
Expand Down Expand Up @@ -47,7 +64,9 @@ module.exports = {
u.protocol = url.parse(location.href).protocol;
}

return fetch(url.format(u), this.requestInit)
const request = new Request(url.format(u), this.requestInit);

return fetch(this.preprocessor(request))
.then((response) => response.buffer())
.catch((err) => new ResolverError(ono(err, `Error downloading ${u.href}`), u.href));
}
Expand Down