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

Commit

Permalink
feat: add JSON support
Browse files Browse the repository at this point in the history
  • Loading branch information
hanspagel committed Dec 11, 2023
1 parent b802ef4 commit 2424735
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
29 changes: 29 additions & 0 deletions packages/snippetz/src/undici.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,35 @@ const {statusCode, headers, trailers, body} = await request("https://example.com
"Content-Type": "application/json"
}
});
`)
})

it('has JSON body', () => {
const source = undici({
url: 'https://example.com',
headers: [
{
name: 'Content-Type',
value: 'application/json',
},
],
postData: {
mimeType: 'application/json',
text: JSON.stringify({
hello: 'world',
}),
},
})

expect(print(source)).toBe(`import {request} from "undici";
const {statusCode, headers, trailers, body} = await request("https://example.com", {
"headers": {
"Content-Type": "application/json"
},
"body": {
"hello": "world"
}
});
`)
})
})
11 changes: 11 additions & 0 deletions packages/snippetz/src/undici.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ export function undici(request: Partial<Request>) {
}
})

// Add body
if (normalizedRequest.postData) {
// Plain text
options.body = normalizedRequest.postData.text

// JSON
if (normalizedRequest.postData.mimeType === 'application/json') {
options.body = JSON.parse(options.body)
}
}

// Transform to JSON
const jsonOptions = Object.keys(options).length
? `, ${JSON.stringify(options, null, 2)}`
Expand Down

0 comments on commit 2424735

Please sign in to comment.