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 option to include response headers in the result #744

Merged
merged 3 commits into from Oct 10, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
34 changes: 32 additions & 2 deletions src/Auth0RestClient.js
Expand Up @@ -27,7 +27,7 @@ class Auth0RestClient {

this.wrappedProvider = function (method, args) {
if (!this.provider) {
return this.restClient[method](...args);
return this._request(method, args);
}

let callback;
Expand All @@ -39,7 +39,7 @@ class Auth0RestClient {
.getAccessToken()
.then((access_token) => {
this.restClient.options.headers['Authorization'] = `Bearer ${access_token}`;
return this.restClient[method](...args);
return this._request(method, args);
})
.catch((err) => {
if (callback) {
Expand All @@ -50,6 +50,36 @@ class Auth0RestClient {
};
}

_request(method, args) {
if (!this.options.includeResponseHeaders) {
return this.restClient[method](...args);
}

let callback;
// Handle the case where the promise variant is called without any args
// client.get() -> client.get({}, callback)
if (!args || !args.length) {
args = [{}];
}
// Handle the case where an undefined placeholder is defined for callback
// client.get(params, undefined) -> client.get(params, callback)
if (typeof args[args.length - 1] === 'undefined') {
args.pop();
}
if (typeof args[args.length - 1] === 'function') {
callback = args.pop();
}
return new Promise((resolve, reject) => {
this.restClient[method](...args, (err, data, headers) => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here we are always using the restClient (rest-facade)'s callback method because this is the only one that returns both the body of the response and the headers

const payload = { data, headers };
if (err) {
(callback && callback(err)) || reject(err);
}
(callback && callback(null, payload)) || resolve(payload);
});
});
}

getAll(...args) {
return this.wrappedProvider('getAll', args);
}
Expand Down
1 change: 1 addition & 0 deletions src/management/BaseManager.js
Expand Up @@ -25,6 +25,7 @@ class BaseManager {
errorFormatter: { message: 'message', name: 'error' },
headers: options.headers,
query: { repeatParams: false },
includeResponseHeaders: options.includeResponseHeaders,
};

const usersAuth0RestClient = new Auth0RestClient(
Expand Down
2 changes: 2 additions & 0 deletions src/management/index.js
Expand Up @@ -90,6 +90,7 @@ class ManagementClient {
* @param {boolean} [options.retry.enabled=true] Enabled or Disable Retry Policy functionality.
* @param {number} [options.retry.maxRetries=10] Retry failed requests X times.
* @param {object} [options.headers] Additional headers that will be added to the outgoing requests.
* @param {object} [options.includeResponseHeaders] Include the response headers in the payload in the format `{ data, headers }`
Widcket marked this conversation as resolved.
Show resolved Hide resolved
*/
constructor(options) {
if (!options || typeof options !== 'object') {
Expand Down Expand Up @@ -147,6 +148,7 @@ class ManagementClient {
}

managerOptions.retry = options.retry;
managerOptions.includeResponseHeaders = options.includeResponseHeaders;

/**
* Simple abstraction for performing CRUD operations on the
Expand Down
32 changes: 32 additions & 0 deletions test/auth0-rest-client.tests.js
Expand Up @@ -228,4 +228,36 @@ describe('Auth0RestClient', () => {
done();
});
});

it('should include response headers in promise response', async function () {
nock(API_URL).get('/some-resource').reply(200, { data: 'value' });

const options = {
includeResponseHeaders: true,
headers: {},
};

const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock);
const { data, headers } = await client.getAll();
expect(data).to.deep.equal({ data: 'value' });
expect(headers).to.deep.equal({ 'content-type': 'application/json' });
nock.cleanAll();
});

it('should include response headers in callback response', function (done) {
nock(API_URL).get('/some-resource').reply(200, { data: 'value' });

const options = {
includeResponseHeaders: true,
headers: {},
};

const client = new Auth0RestClient(`${API_URL}/some-resource`, options, this.providerMock);
client.getAll((err, { data, headers }) => {
expect(data).to.deep.equal({ data: 'value' });
expect(headers).to.deep.equal({ 'content-type': 'application/json' });
nock.cleanAll();
done();
});
});
});
24 changes: 24 additions & 0 deletions test/management/management-client.tests.js
Expand Up @@ -940,5 +940,29 @@ describe('ManagementClient', () => {
expect(this.client.users.assignRoles.called).ok;
this.client.users.assignRoles.reset();
});

it('should include response headers in response', async function () {
const config = Object.assign({}, withTokenConfig, { includeResponseHeaders: true });
this.client = new ManagementClient(config);

nock('https://auth0-node-sdk.auth0.com').get(`/api/v2/users`).reply(200, { data: 'value' });

const { data, headers } = await this.client.users.getAll();
expect(data).to.deep.equal({ data: 'value' });
expect(headers).to.deep.equal({ 'content-type': 'application/json' });
nock.cleanAll();
});

it('should include response headers in response for shorthand method', async function () {
const config = Object.assign({}, withTokenConfig, { includeResponseHeaders: true });
this.client = new ManagementClient(config);

nock('https://auth0-node-sdk.auth0.com').get(`/api/v2/users`).reply(200, { data: 'value' });

const { data, headers } = await this.client.getUsers();
expect(data).to.deep.equal({ data: 'value' });
expect(headers).to.deep.equal({ 'content-type': 'application/json' });
nock.cleanAll();
});
});
});