github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/ui/app/adapters/application.js (about) 1 import { inject as service } from '@ember/service'; 2 import { computed, get } from '@ember/object'; 3 import RESTAdapter from 'ember-data/adapters/rest'; 4 import codesForError from '../utils/codes-for-error'; 5 import removeRecord from '../utils/remove-record'; 6 import { default as NoLeaderError, NO_LEADER } from '../utils/no-leader-error'; 7 8 export const namespace = 'v1'; 9 10 export default RESTAdapter.extend({ 11 namespace, 12 13 system: service(), 14 token: service(), 15 16 headers: computed('token.secret', function() { 17 const token = this.get('token.secret'); 18 if (token) { 19 return { 20 'X-Nomad-Token': token, 21 }; 22 } 23 }), 24 25 handleResponse(status, headers, payload) { 26 if (status === 500 && payload === NO_LEADER) { 27 return new NoLeaderError(); 28 } 29 return this._super(...arguments); 30 }, 31 32 findAll() { 33 return this._super(...arguments).catch(error => { 34 const errorCodes = codesForError(error); 35 36 const isNotImplemented = errorCodes.includes('501'); 37 38 if (isNotImplemented) { 39 return []; 40 } 41 42 // Rethrow to be handled downstream 43 throw error; 44 }); 45 }, 46 47 ajaxOptions(url, type, options = {}) { 48 options.data || (options.data = {}); 49 if (this.get('system.shouldIncludeRegion')) { 50 const region = this.get('system.activeRegion'); 51 if (region) { 52 options.data.region = region; 53 } 54 } 55 return this._super(url, type, options); 56 }, 57 58 // In order to remove stale records from the store, findHasMany has to unload 59 // all records related to the request in question. 60 findHasMany(store, snapshot, link, relationship) { 61 return this._super(...arguments).then(payload => { 62 const relationshipType = relationship.type; 63 const inverse = snapshot.record.inverseFor(relationship.key); 64 if (inverse) { 65 store 66 .peekAll(relationshipType) 67 .filter(record => record.get(`${inverse.name}.id`) === snapshot.id) 68 .forEach(record => { 69 removeRecord(store, record); 70 }); 71 } 72 return payload; 73 }); 74 }, 75 76 // Single record requests deviate from REST practice by using 77 // the singular form of the resource name. 78 // 79 // REST: /some-resources/:id 80 // Nomad: /some-resource/:id 81 // 82 // This is the original implementation of _buildURL 83 // without the pluralization of modelName 84 urlForFindRecord: urlForRecord, 85 urlForUpdateRecord: urlForRecord, 86 }); 87 88 function urlForRecord(id, modelName) { 89 let path; 90 let url = []; 91 let host = get(this, 'host'); 92 let prefix = this.urlPrefix(); 93 94 if (modelName) { 95 path = modelName.camelize(); 96 if (path) { 97 url.push(path); 98 } 99 } 100 101 if (id) { 102 url.push(encodeURIComponent(id)); 103 } 104 105 if (prefix) { 106 url.unshift(prefix); 107 } 108 109 url = url.join('/'); 110 if (!host && url && url.charAt(0) !== '/') { 111 url = '/' + url; 112 } 113 114 return url; 115 }