Custom Fetch
Creates a function with the same API as WHATWG's fetch
,
but with your own custom behaviour. Ideal for testing or
for modifying an HTTP request before sending.
import CustomFetch from 'custom-fetch';
import * as NodeFetch from 'node-fecth';
const { Request, Response } = NodeFetch;
const fetch = new CustomFetch(async (request, signal) => {
switch(request.url) {
case 'http://horses.example/':
return 'Welcome to horses.example';
case 'http://flowers.example/foxglove.json':
return new Response(
JSON.stringify({
name: 'Foxglove',
scientificName: 'Digitalis purpurea',
gbifId: 5414995
}),
{
headers: {
'Content-Type': 'application/json'
}
}
)
default:
request = new Request(request, { headers: { 'X-Favourite-Color': 'blue' } })
return NodeFetch.fetch(request, { signal });
},
{ Request, Response }
);
export default fetch('http://horses.example/');
Dependencies
None
custom-fetch
module.exports ⏏
Custom Fetch constructor
Kind: Exported class
new module.exports(fetchHandler, fetchConstructors)
Param | Type | Description |
---|
fetchHandler | fetchHandler | Callback for handling fetch request. |
fetchConstructors | object | Object containing constructors for creating fetch Request and Response classes |
fetchConstructors.Request | Request | Constructor for a fetch Request object |
fetchConstructors.Response | Response | Constructor for a fetch Response object |
module.exports~Request : function
Kind: inner class of module.exports
new Request(url, options)
Param | Type |
---|
url | string |
options | object |
module.exports~Response : function
Kind: inner class of module.exports
new Response(body, options)
Param | Type |
---|
body | string |
options | object |
module.exports~fetchHandler ⇒ Response
| string
Kind: inner typedef of module.exports
Param | Type |
---|
request | Request |
signal | Signal |