Skip to content
This repository has been archived by the owner on Aug 28, 2024. It is now read-only.

Commit

Permalink
feat: add cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
hanspagel committed Dec 11, 2023
1 parent d2bda04 commit c3cee09
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
24 changes: 24 additions & 0 deletions packages/snippetz-plugin-undici/src/undici.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
});
`)
})
})
12 changes: 11 additions & 1 deletion packages/snippetz-plugin-undici/src/undici.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ export function undici(request: Partial<Request>) {
}

// Query

const searchParams = new URLSearchParams(
normalizedRequest.queryString
? arrayToObject(normalizedRequest.queryString)
Expand All @@ -44,6 +43,17 @@ export function undici(request: Partial<Request>) {
})
}

// 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) {
Expand Down

0 comments on commit c3cee09

Please sign in to comment.