UNPKG

@worker-tools/json-stream

Version:

Utilities for working with streaming JSON in Worker Runtimes such as Cloudflare Workers, Deno Deploy and Service Workers.

50 lines 1.95 kB
// deno-lint-ignore-file no-explicit-any import { StreamResponse, StreamRequest } from "@worker-tools/stream-response"; import { asyncIterToStream } from 'whatwg-stream-to-async-iter'; import { JSONStringifyReadable, isAsyncIterable } from './json-stringify.js'; const toBody = (x) => x instanceof ReadableStream ? x : isAsyncIterable(x) ? asyncIterToStream(x) : new JSONStringifyReadable(x); export class JSONStreamRequest extends StreamRequest { constructor(input, init) { const { headers: _headers, body: _body, ...rest } = init || {}; const body = toBody(_body); const headers = new Headers(_headers); if (!headers.has('Content-Type') && _body != null) headers.set('Content-Type', JSONStreamRequest.contentType); if (!headers.has('Accept')) headers.set('Accept', JSONStreamRequest.accept); super(input instanceof URL ? input.href : input, { headers, body, ...rest }); } } Object.defineProperty(JSONStreamRequest, "contentType", { enumerable: true, configurable: true, writable: true, value: 'application/json;charset=UTF-8' }); Object.defineProperty(JSONStreamRequest, "accept", { enumerable: true, configurable: true, writable: true, value: 'application/json, text/plain, */*' }); export class JSONStreamResponse extends StreamResponse { constructor(body, init) { const { headers: _headers, ...rest } = init || {}; const _body = toBody(body); const headers = new Headers(_headers); if (!headers.has('Content-Type') && body != null) headers.set('Content-Type', JSONStreamResponse.contentType); super(_body, { headers, ...rest }); } } Object.defineProperty(JSONStreamResponse, "contentType", { enumerable: true, configurable: true, writable: true, value: 'application/json;charset=UTF-8' }); //# sourceMappingURL=json-fetch.js.map