From 992f55ce8e0a406fa967aaacd630ab4c878ee8f2 Mon Sep 17 00:00:00 2001 From: Mikkel ALMONTE--RINGAUD Date: Sat, 17 Aug 2024 09:16:20 +0200 Subject: [PATCH] feat: add set cookies to request --- src/index.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/index.ts b/src/index.ts index 81b9016..90fc6b8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -21,19 +21,28 @@ export const getCookiesFromResponse = (response: Response): string[] => { export const getHeaderFromResponse = (response: Response, item: string): string | null => { const headers = response.headers; - return isHeader(headers) + return isHeaderInstance(headers) ? headers.get(item) : (headers as Record)[item]; }; -const isHeader = (headers: Response["headers"]): headers is Headers => { +const isHeaderInstance = (headers: Response["headers"]): headers is Headers => { return typeof headers.get === "function"; } +export const setCookiesArrayToRequest = (request: Request, cookies: string[]): void => { + setHeaderToRequest(request, "Cookie", cookies.join("; ")) +} + +export const setCookiesObjectToRequest = (request: Request, cookies: Record): void => { + const array = Object.entries(cookies).map(([key, value])=>`${key}=${value}`) + setCookiesArrayToRequest(request, array) +} + export const setHeaderToRequest = (request: Request, key: string, value: string): void => { - if (!request.headers) request.headers = {}; + request.headers ||= {}; - if (isHeader(request.headers)) { + if (isHeaderInstance(request.headers)) { request.headers.set(key, value); } else {