Skip to content

Commit

Permalink
sends accept: application/json header when in json mode
Browse files Browse the repository at this point in the history
  • Loading branch information
jamierbower committed Oct 11, 2023
1 parent d27fbcf commit fa79732
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
8 changes: 5 additions & 3 deletions lib/transport/node-fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,17 @@ class FetchTransport extends Transport {
}
}

if (this.jsonMode(ctx)) req.addHeader('Accept', 'application/json');

if (req.hasHeaders()) opts.headers = req.getHeaders();

return opts;
}

parseAsJson(ctx, contentType) {
jsonMode(ctx) {
if (ctx.opts?.json !== undefined) return ctx.opts.json;

return this.defaults?.json || contentType?.includes('json');
return this.defaults?.json;
}

async toResponse(ctx, from) {
Expand All @@ -76,7 +78,7 @@ class FetchTransport extends Transport {
if (text) {
to.body = text;
const contentType = to.headers['content-type'];
if (this.parseAsJson(ctx, contentType)) {
if (this.jsonMode(ctx, contentType) || contentType?.includes('json')) {
try {
to.body = JSON.parse(to.body);
} catch {} // If body is not parseable, leave as text
Expand Down
28 changes: 27 additions & 1 deletion test/transport/node-fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ describe('Request HTTP transport', () => {
.catch(assert.ifError);
});

it('allows disabling of timing request', () => {
it('allows disabling of timing request', () => {
nock.cleanAll();
api.get('/').reply(200, responseBody);

Expand Down Expand Up @@ -288,6 +288,32 @@ describe('Request HTTP transport', () => {
});
});

it('if json default option is passed in as true, send an accept: application/json header', () => {
nock.cleanAll();
nock(host, {
reqheaders: {
accept: 'application/json'
}
})
.get(path)
.reply(200, responseBody, header);

const ctx = createContext(url);
const options = {
defaults: {
json: true
}
};

const fetchTransport = new FetchTransport(options);
return fetchTransport
.execute(ctx)
.catch(assert.ifError)
.then((ctx) => {
assert.equal(ctx.res.statusCode, 200);
});
});

it('if there is no json default option passed in, but the content type header includes application/json, then parse body as json', () => {
nock.cleanAll();
api.get(path).reply(200, JSONResponseBody, jsonHeader);
Expand Down

0 comments on commit fa79732

Please sign in to comment.