@worker-tools/json-fetch
Version:
A drop-in replacements for fetch, Request, and Response with first class support for JSON objects.
64 lines • 2.4 kB
JavaScript
/**
* Tests is the argument is a Fetch API `BodyInit`.
* Assumed to be `JSONValue` otherwise.
*/
function isBodyInit(b) {
return (b == null ||
typeof b === 'string' ||
(typeof Blob !== 'undefined' && b instanceof Blob) ||
(typeof ArrayBuffer !== 'undefined' && (b instanceof ArrayBuffer || ArrayBuffer.isView(b))) ||
(typeof FormData !== 'undefined' && b instanceof FormData) ||
(typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) ||
(typeof ReadableStream !== 'undefined' && b instanceof ReadableStream));
}
export class JSONRequest extends Request {
constructor(input, init, replacer, space) {
const { headers: _headers, body: _body, ..._init } = init || {};
let isBI;
const body = (isBI = isBodyInit(_body))
? _body
: JSON.stringify(_body, replacer, space);
const headers = new Headers(_headers);
if (!headers.has('Content-Type') && !isBI)
headers.set('Content-Type', JSONRequest.contentType);
if (!headers.has('Accept'))
headers.set('Accept', JSONRequest.accept);
super(input instanceof URL ? input.href : input, { headers, body, ..._init });
}
}
Object.defineProperty(JSONRequest, "contentType", {
enumerable: true,
configurable: true,
writable: true,
value: 'application/json;charset=UTF-8'
});
Object.defineProperty(JSONRequest, "accept", {
enumerable: true,
configurable: true,
writable: true,
value: 'application/json, text/plain, */*'
});
export class JSONResponse extends Response {
constructor(body, init, replacer, space) {
const { headers: _headers, ..._init } = init || {};
let isBI;
const _body = (isBI = isBodyInit(body))
? body
: JSON.stringify(body, replacer, space);
const headers = new Headers(_headers);
if (!headers.has('Content-Type') && !isBI)
headers.set('Content-Type', JSONResponse.contentType);
super(_body, { headers, ..._init });
}
}
Object.defineProperty(JSONResponse, "contentType", {
enumerable: true,
configurable: true,
writable: true,
value: 'application/json;charset=UTF-8'
});
export function jsonFetch(...args) {
return fetch(new JSONRequest(...args));
}
export * from './search-params-url.js';
//# sourceMappingURL=index.js.map