Add the region qp to all requests made through the token service

This commit is contained in:
Michael Lange 2018-08-08 16:10:22 -07:00
parent d61fd9ef48
commit 0cfeba49d7
2 changed files with 27 additions and 3 deletions

View file

@ -28,7 +28,7 @@ export default Service.extend({
const token = this.get('token'); const token = this.get('token');
return PromiseArray.create({ return PromiseArray.create({
promise: token.authorizedRequest(`/${namespace}/regions`).then(res => res.json()), promise: token.authorizedRawRequest(`/${namespace}/regions`).then(res => res.json()),
}); });
}), }),

View file

@ -1,9 +1,12 @@
import Service from '@ember/service'; import Service, { inject as service } from '@ember/service';
import { computed } from '@ember/object'; import { computed } from '@ember/object';
import { assign } from '@ember/polyfills'; import { assign } from '@ember/polyfills';
import queryString from 'query-string';
import fetch from 'nomad-ui/utils/fetch'; import fetch from 'nomad-ui/utils/fetch';
export default Service.extend({ export default Service.extend({
system: service(),
secret: computed({ secret: computed({
get() { get() {
return window.sessionStorage.nomadTokenSecret; return window.sessionStorage.nomadTokenSecret;
@ -19,7 +22,12 @@ export default Service.extend({
}, },
}), }),
authorizedRequest(url, options = { credentials: 'include' }) { // All non Ember Data requests should go through authorizedRequest.
// However, the request that gets regions falls into that category.
// This authorizedRawRequest is necessary in order to fetch data
// with the guarantee of a token but without the automatic region
// param since the region cannot be known at this point.
authorizedRawRequest(url, options = { credentials: 'include' }) {
const headers = {}; const headers = {};
const token = this.get('secret'); const token = this.get('secret');
@ -29,4 +37,20 @@ export default Service.extend({
return fetch(url, assign(options, { headers })); return fetch(url, assign(options, { headers }));
}, },
authorizedRequest(url, options) {
const region = this.get('system.activeRegion');
if (region) {
url = addParams(url, { region });
}
return this.authorizedRawRequest(url, options);
},
}); });
function addParams(url, params) {
const paramsStr = queryString.stringify(params);
const delimiter = url.includes('?') ? '&' : '?';
return `${url}${delimiter}${paramsStr}`;
}