Skip to content

Commit

Permalink
feat: add support for stringifyJson
Browse files Browse the repository at this point in the history
  • Loading branch information
Reverier-Xu committed Apr 21, 2024
1 parent 7760a81 commit 210a9b7
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 1 deletion.
2 changes: 1 addition & 1 deletion source/core/Ky.ts
Expand Up @@ -203,7 +203,7 @@ export class Ky {
}

if (this._options.json !== undefined) {
this._options.body = JSON.stringify(this._options.json);
this._options.body = this._options.stringifyJson ? this._options.stringifyJson(this._options.json) : JSON.stringify(this._options.json);
this.request.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
this.request = new globalThis.Request(this.request, {body: this._options.body});
}
Expand Down
1 change: 1 addition & 0 deletions source/core/constants.ts
Expand Up @@ -50,6 +50,7 @@ export const stop = Symbol('stop');
export const kyOptionKeys: KyOptionsRegistry = {
json: true,
parseJson: true,
stringifyJson: true,
searchParams: true,
prefixUrl: true,
retry: true,
Expand Down
26 changes: 26 additions & 0 deletions source/types/options.ts
Expand Up @@ -58,6 +58,32 @@ export type KyOptions = {
*/
parseJson?: (text: string) => unknown;

/**
User-defined JSON-stringifying function.
Use-cases:
1. Stringify JSON with the custom `replacer` function.
@default JSON.stringify()
@example
```
import ky from 'ky';
import { DateTime } from 'luxon';
const json = await ky('https://example.com', {
stringifyJson: data => JSON.stringify(data, (_, value) => {
if (value instanceof DateTime) {
return value.toSeconds();
}
return value;
})
}).json();
```
*/
stringifyJson?: (data: unknown) => string;

/**
Search parameters to include in the request URL. Setting this will override all existing search parameters in the input URL.
Expand Down
21 changes: 21 additions & 0 deletions test/main.ts
Expand Up @@ -733,3 +733,24 @@ test('parseJson option with promise.json() shortcut', async t => {

await server.close();
});

test('stringifyJson option with request.json()', async t => {
const server = await createHttpTestServer({bodyParser: false});
server.post('/', async (request, response) => {
const body = await parseRawBody(request);
t.is(body, '{"data":{"hello":"world"},"extra":"extraValue"}');
response.end();
});

const json = {hello: 'world'};

await ky.post(server.url, {
stringifyJson: data => JSON.stringify({
data,
extra: 'extraValue',
}),
json,
});

await server.close();
});

0 comments on commit 210a9b7

Please sign in to comment.