Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add options to customize parsing/stringifying JSON #1298

Merged
merged 23 commits into from
Jun 5, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 0 additions & 19 deletions documentation/migration-guides.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,25 +97,6 @@ const gotInstance = got.extend({
gotInstance(url, options);
```

- No `jsonReplacer` option, but you can use hooks for that too:

```js
const gotInstance = got.extend({
hooks: {
init: [
options => {
if (options.jsonReplacer && options.json) {
options.body = JSON.stringify(options.json, options.jsonReplacer);
delete options.json;
}
}
]
}
});

gotInstance(url, options);
```

Hooks are powerful, aren't they? [Read more](../readme.md#hooks) to see what else you achieve using hooks.

#### More about streams
Expand Down
18 changes: 18 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,24 @@ const parsed = await got('https://example.com', {
}).json();
```

###### stringifyJson

Type: `(object: any) => string`\
Default: `(object: any) => JSON.stringify(object)`

Function used to stringify JSON requests body.

Example:

```js
const got = require('got');

await got.post('https://example.com', {
stringifyJson: object => JSON.stringify(object),
json: {some: 'payload'}
});
```

###### resolveBodyOnly

Type: `boolean`\
Expand Down
6 changes: 5 additions & 1 deletion source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ type CacheableRequestFunction = (

type CheckServerIdentityFunction = (hostname: string, certificate: DetailedPeerCertificate) => Error | void;
export type ParseJsonFunction = (text: string) => unknown;
export type StringifyJsonFunction = (object: any) => string;
Giotino marked this conversation as resolved.
Show resolved Hide resolved

interface RealRequestOptions extends https.RequestOptions {
checkServerIdentity: CheckServerIdentityFunction;
Expand Down Expand Up @@ -154,6 +155,7 @@ export interface Options extends URLOptions {
methodRewriting?: boolean;
dnsLookupIpVersion?: DnsLookupIpVersion;
parseJson?: ParseJsonFunction;
stringifyJson?: StringifyJsonFunction;

// From `http.RequestOptions`
localAddress?: string;
Expand Down Expand Up @@ -206,6 +208,7 @@ export interface NormalizedOptions extends Options {
username: string;
password: string;
parseJson: ParseJsonFunction;
stringifyJson: StringifyJsonFunction;
[kRequest]: HttpRequestFunction;
[kIsNormalizedAlready]?: boolean;
}
Expand All @@ -230,6 +233,7 @@ export interface Defaults {
https?: HTTPSOptions;
methodRewriting: boolean;
parseJson: ParseJsonFunction;
stringifyJson: StringifyJsonFunction;

// Optional
agent?: Agents | false;
Expand Down Expand Up @@ -1000,7 +1004,7 @@ export default class Request extends Duplex implements RequestEvents<Request> {
headers['content-type'] = 'application/json';
}

this[kBody] = JSON.stringify(options.json);
this[kBody] = options.stringifyJson(options.json);
}

const uploadBodySize = await getBodySize(this[kBody], options.headers);
Expand Down
3 changes: 2 additions & 1 deletion source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ const defaults: InstanceDefaults = {
requestLimit: 10000,
stackAllItems: true
},
parseJson: (text: string) => JSON.parse(text)
parseJson: (text: string) => JSON.parse(text),
stringifyJson: (object: any) => JSON.stringify(object)
},
handlers: [defaultHandler],
mutableDefaults: false
Expand Down
16 changes: 16 additions & 0 deletions test/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ const echoIp: Handler = (request, response) => {
response.end(address === '::ffff:127.0.0.1' ? '127.0.0.1' : address);
};

const echoBody: Handler = async (request, response) => {
response.end(await getStream(request));
};

test('simple request', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.end('ok');
Expand Down Expand Up @@ -351,3 +355,15 @@ test.serial('deprecated `family` option', withServer, async (t, server, got) =>
})();
});
});

test('JSON request custom stringifier', withServer, async (t, server, got) => {
server.post('/', echoBody);

const payload = {a: 'b'};
const customStringify = (object: any) => JSON.stringify({...object, c: 'd'});

t.deepEqual((await got.post({
stringifyJson: customStringify,
json: payload
})).body, customStringify(payload));
});