From c3cee0978c1b5de0cf4b2eed82919a390878b80b Mon Sep 17 00:00:00 2001 From: Hans Pagel Date: Mon, 11 Dec 2023 16:51:11 +0100 Subject: [PATCH] feat: add cookies --- .../snippetz-plugin-undici/src/undici.test.ts | 24 +++++++++++++++++++ packages/snippetz-plugin-undici/src/undici.ts | 12 +++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/packages/snippetz-plugin-undici/src/undici.test.ts b/packages/snippetz-plugin-undici/src/undici.test.ts index e23d382..8b9703e 100644 --- a/packages/snippetz-plugin-undici/src/undici.test.ts +++ b/packages/snippetz-plugin-undici/src/undici.test.ts @@ -110,6 +110,30 @@ const {statusCode, headers, body} = await request("https://example.com?foo=bar&b "Content-Type": "application/json" } }); +`) + }) + + it('has the path', () => { + const source = undici({ + url: 'https://example.com', + cookies: [ + { + name: 'foo', + value: 'bar', + }, + { + name: 'bar', + value: 'foo', + }, + ], + }) + + expect(print(source)).toBe(`import {request} from "undici"; +const {statusCode, headers, body} = await request("https://example.com", { + "headers": { + "Set-Cookie": "foo=bar; bar=foo" + } +}); `) }) }) diff --git a/packages/snippetz-plugin-undici/src/undici.ts b/packages/snippetz-plugin-undici/src/undici.ts index 9742d29..5faccce 100644 --- a/packages/snippetz-plugin-undici/src/undici.ts +++ b/packages/snippetz-plugin-undici/src/undici.ts @@ -27,7 +27,6 @@ export function undici(request: Partial) { } // Query - const searchParams = new URLSearchParams( normalizedRequest.queryString ? arrayToObject(normalizedRequest.queryString) @@ -44,6 +43,17 @@ export function undici(request: Partial) { }) } + // Cookies + if (normalizedRequest.cookies) { + options.headers = options.headers || {} + + normalizedRequest.cookies.forEach((cookie) => { + options.headers!['Set-Cookie'] = options.headers!['Set-Cookie'] + ? `${options.headers!['Set-Cookie']}; ${cookie.name}=${cookie.value}` + : `${cookie.name}=${cookie.value}` + }) + } + // Remove undefined keys Object.keys(options).forEach((key) => { if (options[key] === undefined) {