open-consul/ui-v2/app/adapters/application.js
John Cowen d598a98cbf
ui: Fix token duplication bug (#7552)
We need to detect whether an object is an ember-data snapshot or just a
plain object, and we where restricted from using `instanceof` due to
ember-data's `Snapshot` class being private.

We'd chosen to go with `constructor.name` instead, which seemed to work,
but when the javascript gets minifed the name of the contructor is also
minified and therefore is not what you are expecting.

This commit reverts to our original idea of checking for the existence
and type of the `.attributes` function, which is the function we require
within the conditional, and therefore is more reliable (if the function
doesn't exist it will error out during development aswell as production)
2020-04-01 09:55:20 +01:00

63 lines
2.1 KiB
JavaScript

import Adapter from './http';
import { inject as service } from '@ember/service';
// TODO: This should be changed to use env
import config from 'consul-ui/config/environment';
export const DATACENTER_QUERY_PARAM = 'dc';
export const NSPACE_QUERY_PARAM = 'ns';
export default Adapter.extend({
repo: service('settings'),
client: service('client/http'),
formatNspace: function(nspace) {
if (config.CONSUL_NSPACES_ENABLED) {
return nspace !== '' ? { [NSPACE_QUERY_PARAM]: nspace } : undefined;
}
},
formatDatacenter: function(dc) {
return {
[DATACENTER_QUERY_PARAM]: dc,
};
},
// TODO: kinda protected for the moment
// decide where this should go either read/write from http
// should somehow use this or vice versa
request: function(req, resp, obj, modelName) {
const client = this.client;
const store = this.store;
const adapter = this;
let unserialized, serialized;
const serializer = store.serializerFor(modelName);
// workable way to decide whether this is a snapshot
// essentially 'is attributable'.
// Snapshot is private so we can't do instanceof here
// and using obj.constructor.name gets changed/minified
// during compilation so you can't rely on it
// checking for `attributes` being a function is more
// reliable as that is the thing we need to call
if (typeof obj.attributes === 'function') {
unserialized = obj.attributes();
serialized = serializer.serialize(obj, {});
} else {
unserialized = obj;
serialized = unserialized;
}
return client
.request(function(request) {
return req(adapter, request, serialized, unserialized);
})
.catch(function(e) {
return adapter.error(e);
})
.then(function(respond) {
// TODO: When HTTPAdapter:responder changes, this will also need to change
return resp(serializer, respond, serialized, unserialized);
});
// TODO: Potentially add specific serializer errors here
// .catch(function(e) {
// return Promise.reject(e);
// });
},
});