UNPKG

2.5 kBPlain TextView Raw
1// deno-lint-ignore-file no-cond-assign
2// deno-lint-ignore no-explicit-any
3export type JSONBodyInit = BodyInit | any;
4export type JSONRequestInit = { body?: JSONBodyInit | null } & Omit<RequestInit, 'body'>;
5
6/**
7 * Tests is the argument is a Fetch API `BodyInit`.
8 * Assumed to be `JSONValue` otherwise.
9 */
10function isBodyInit(b?: JSONBodyInit): b is BodyInit {
11 return (
12 b == null ||
13 typeof b === 'string' ||
14 (typeof Blob !== 'undefined' && b instanceof Blob) ||
15 (typeof ArrayBuffer !== 'undefined' && (b instanceof ArrayBuffer || ArrayBuffer.isView(b))) ||
16 (typeof FormData !== 'undefined' && b instanceof FormData) ||
17 (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) ||
18 (typeof ReadableStream !== 'undefined' && b instanceof ReadableStream)
19 );
20}
21
22export class JSONRequest extends Request {
23 static contentType = 'application/json;charset=UTF-8';
24 static accept = 'application/json, text/plain, */*';
25
26 constructor(
27 input: RequestInfo | URL,
28 init?: JSONRequestInit,
29 replacer?: Parameters<typeof JSON.stringify>[1],
30 space?: Parameters<typeof JSON.stringify>[2],
31 ) {
32 const { headers: _headers, body: _body, ..._init } = init || {};
33
34 let isBI: boolean
35 const body = (isBI = isBodyInit(_body))
36 ? _body
37 : JSON.stringify(_body, replacer, space);
38
39 const headers = new Headers(_headers);
40 if (!headers.has('Content-Type') && !isBI)
41 headers.set('Content-Type', JSONRequest.contentType);
42 if (!headers.has('Accept'))
43 headers.set('Accept', JSONRequest.accept);
44
45 super(input instanceof URL ? input.href : input, { headers, body, ..._init });
46 }
47}
48
49export class JSONResponse extends Response {
50 static contentType = 'application/json;charset=UTF-8';
51
52 constructor(
53 body?: JSONBodyInit | null,
54 init?: ResponseInit,
55 replacer?: Parameters<typeof JSON.stringify>[1],
56 space?: Parameters<typeof JSON.stringify>[2],
57 ) {
58 const { headers: _headers, ..._init } = init || {};
59
60 let isBI: boolean
61 const _body = (isBI = isBodyInit(body))
62 ? body
63 : JSON.stringify(body, replacer, space);
64
65 const headers = new Headers(_headers);
66 if (!headers.has('Content-Type') && !isBI)
67 headers.set('Content-Type', JSONResponse.contentType);
68
69 super(_body, { headers, ..._init });
70 }
71}
72
73export function jsonFetch(...args: ConstructorParameters<typeof JSONRequest>) {
74 return fetch(new JSONRequest(...args));
75}
76
77export * from './search-params-url.js'