From d8014e3babb91e2e0ca17273136b8efe7f5ee8ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20B=C3=B8ving?= Date: Wed, 27 Sep 2023 14:59:53 +0200 Subject: [PATCH] Determine the content type based on the passed body in `requestPlain` --- src/preamble.ts | 48 +++++++----------------------------------------- 1 file changed, 7 insertions(+), 41 deletions(-) diff --git a/src/preamble.ts b/src/preamble.ts index ee4a9ec..50dac83 100644 --- a/src/preamble.ts +++ b/src/preamble.ts @@ -26,7 +26,12 @@ export const requestPlain = ( method: method.toUpperCase(), body: typeof body != "undefined" ? JSON.stringify(body) : void 0, signal: controller.signal, - headers: options?.headers, + headers: { + ...options?.headers, + ...(typeof body != "undefined" + ? { "Content-Type": "application/json" } + : {}), + }, }).then(async (res) => { inFlight = false; if (res.ok) { @@ -58,45 +63,6 @@ export const requestJson = ( data: Promise; cancel: (reason?: string) => void; } => { - const { data, cancel } = requestPlain(method, url, body, { - ...options, - headers: { - "Content-Type": "application/json", - }, - }); + const { data, cancel } = requestPlain(method, url, body, options); return { data: data.then((text) => JSON.parse(text) as T), cancel }; }; - -export type SSEStream = ( - event: - | { type: "message"; data: T } - | { - type: "error"; - event: Event; - } -) => void; - -const sse = ( - _method: Method, - url: string, - options?: ApiOptions -): { - cancel: () => void; - listen: (stream: SSEStream) => void; -} => { - const source = new EventSource(`${getApiBase(options)}${url}`); - - let stream: SSEStream | null = null; - - source.onmessage = (event) => { - const data = event.data; - stream?.({ type: "message", data }); - }; - source.onerror = (event) => { - stream?.({ type: "error", event }); - }; - return { - cancel: () => source.close(), - listen: (newStream) => (stream = newStream), - }; -};