Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 13 additions & 23 deletions src/services/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,34 +97,23 @@ function formDataToBuffer(form) {
});
}

// One response header. fetch and axios headers have get(); an axios response rebuilt by an
// application interceptor can carry a plain object instead. headers must be an object.
const headerOf = (headers, name) => (typeof headers.get === 'function' ? headers.get(name) : headers[name]);

// CKO response headers of a fetch or an axios response.
function getResponseHeaders(response) {
const requestId = response.headers.get(REQUEST_ID_HEADER) || response.headers.get('request-id');
const version = response.headers.get(API_VERSION_HEADER) || response.headers.get('version');
const etag = response.headers.get(ETAG_HEADER);
const { headers } = response;
const requestId = requestIdOf(headers);
const version = headerOf(headers, API_VERSION_HEADER) || headerOf(headers, 'version');
const etag = headerOf(headers, ETAG_HEADER);
return {
'cko-request-id': requestId || '',
'cko-version': version || '',
'etag': etag || '',
};
}

function getResponseAxiosHeaders(response) {
// Return CKO response headers when available

if (REQUEST_ID_HEADER in response.headers) {
const requestId = response.headers[REQUEST_ID_HEADER] || response.headers['request-id'];
const version = response.headers[API_VERSION_HEADER] || response.headers.version;
const etag = response.headers[ETAG_HEADER];
return {
'cko-request-id': requestId ? requestId[0] : '',
'cko-version': version ? version[0] : '',
'etag': etag ? etag[0] : '',
};
}

return {};
}

function buildAxiosResponse(config, response) {
if (config.csv) {
return {
Expand All @@ -135,7 +124,7 @@ function buildAxiosResponse(config, response) {
return {
status: response.status,
json: response.data,
headers: getResponseAxiosHeaders(response),
headers: getResponseHeaders(response),
};
}

Expand Down Expand Up @@ -209,8 +198,9 @@ const AXIOS_SUCCESS_ONLY_POLICY = {
// Body of the errors of the response policy: the status, and the request id when the API sent one.
const statusOnlyBody = (status, requestId) => (requestId ? { status, request_id: requestId } : { status });

// The request id of a 3xx response: both clients give its headers with get().
const requestIdOf = (headers) => headers?.get?.(REQUEST_ID_HEADER) || headers?.get?.('request-id') || undefined;
// The request id of a response, if it has headers (see headerOf).
const requestIdOf = (headers) =>
(headers && (headerOf(headers, REQUEST_ID_HEADER) || headerOf(headers, 'request-id'))) || undefined;

// A 3xx response: an ApiError with the status only.
const redirectStatusError = (status, requestId) => new ApiError(status, statusOnlyBody(status, requestId));
Expand Down
133 changes: 133 additions & 0 deletions test/http/responseHeaders.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import axios from 'axios';
import { expect } from 'chai';
import http from 'http';
import { ApiError } from '../../src/services/errors.js';
import { get } from '../../src/services/http.js';

// The response headers the SDK returns, read from a real local server so each
// HTTP client parses them as it does in production.
describe('HTTP response headers', () => {
let server;
let baseUrl;
let responseHeaders;
let responseStatus = 200;

before((done) => {
server = http.createServer((req, res) => {
req.resume();
req.on('end', () => {
res.writeHead(responseStatus, { 'Content-Type': 'application/json', ...responseHeaders });
res.end('{}');
});
});
server.listen(0, '127.0.0.1', () => {
baseUrl = `http://127.0.0.1:${server.address().port}`;
done();
});
});

after((done) => {
server.close(done);
});

const config = { headers: {} };
const call = (client) => get(client, `${baseUrl}/x`, config, 'Bearer sk_test');

for (const client of ['fetch', 'axios']) {
describe(`with the ${client} client`, () => {
it('returns the request id, version and etag whole', async () => {
responseHeaders = {
'cko-request-id': 'req_0123456789abcdef',
'cko-version': '1.0.0',
etag: 'W/"a1b2c3"',
};

const response = await call(client);

expect(response.headers).to.deep.equal({
'cko-request-id': 'req_0123456789abcdef',
'cko-version': '1.0.0',
etag: 'W/"a1b2c3"',
});
});

it('falls back to the request-id and version headers', async () => {
responseHeaders = { 'request-id': 'req_fallback', version: '2.0.0' };

const response = await call(client);

expect(response.headers).to.deep.equal({
'cko-request-id': 'req_fallback',
'cko-version': '2.0.0',
etag: '',
});
});

it('returns the etag when there is no request id', async () => {
responseHeaders = { etag: '"only-etag"' };

const response = await call(client);

expect(response.headers).to.deep.equal({
'cko-request-id': '',
'cko-version': '',
etag: '"only-etag"',
});
});

it('returns empty values when no CKO headers are sent', async () => {
responseHeaders = {};

const response = await call(client);

expect(response.headers).to.deep.equal({
'cko-request-id': '',
'cko-version': '',
etag: '',
});
});
});
}

it('reads the headers when an axios interceptor turns them into a plain object', async () => {
const interceptor = axios.interceptors.response.use((response) => ({
...response,
headers: { ...response.headers },
}));
responseHeaders = { 'cko-request-id': 'req_0123456789abcdef', etag: 'W/"a1b2c3"' };

try {
const response = await call('axios');

expect(response.headers).to.deep.equal({
'cko-request-id': 'req_0123456789abcdef',
'cko-version': '',
etag: 'W/"a1b2c3"',
});
} finally {
axios.interceptors.response.eject(interceptor);
}
});

it('keeps the request id of a 3xx when an axios interceptor turns the headers into a plain object', async () => {
const interceptor = axios.interceptors.response.use(undefined, (error) => {
if (error.response) {
error.response = { ...error.response, headers: { ...error.response.headers } };
}
return Promise.reject(error);
});
responseStatus = 307;
responseHeaders = { Location: `${baseUrl}/moved`, 'cko-request-id': 'req_0123456789abcdef' };

try {
await call('axios');
expect.fail('the request should fail');
} catch (error) {
expect(error).to.be.instanceOf(ApiError);
expect(error.body).to.deep.equal({ status: 307, request_id: 'req_0123456789abcdef' });
} finally {
responseStatus = 200;
axios.interceptors.response.eject(interceptor);
}
});
});