Last active
August 29, 2019 13:12
-
-
Save villander/5fd82cfd5b804150f4011e9d877ff6b1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AjaxService from 'ember-ajax/services/ajax'; | |
import { inject as service } from '@ember/service'; | |
import { readOnly } from '@ember/object/computed'; | |
import { computed } from '@ember/object'; | |
import { | |
convertToJsonApiErrors, | |
normalizeJsonApiErrors | |
} from 'web-app/utils/normalize-errors'; | |
import { decamelizeObject } from 'web-app/utils/object-manipulation'; | |
export default AjaxService.extend({ | |
session: service(), | |
currentUser: service(), | |
endpoints: service(), | |
gatewayHost: readOnly('endpoints.gatewayApi'), | |
vcardHost: readOnly('endpoints.vcardApi'), | |
authenticatorHost: readOnly('endpoints.authenticatorApi'), | |
crmHost: readOnly('endpoints.crmApi'), | |
/** | |
* trustedHosts | |
* | |
* @override | |
*/ | |
trustedHosts: computed('authenticatorHost', 'crmHost', 'gatewayHost', 'vcardHost', { | |
get() { | |
return [ | |
this.authenticatorHost.replace(/https?:\/\//, ''), | |
this.gatewayHost.replace(/https?:\/\//, ''), | |
this.vcardHost.replace(/https?:\/\//, ''), | |
this.crmHost.replace(/https?:\/\//, '') | |
]; | |
} | |
}).readOnly(), | |
/** | |
* headers | |
* | |
* @override | |
*/ | |
get headers() { | |
const headers = {}; | |
const { token } = this.session.data.authenticated; | |
if (token) { | |
headers.Authorization = `Bearer ${token}`; | |
} | |
return headers; | |
}, | |
/** | |
* POST | |
* | |
* @override | |
*/ | |
post(module, endpoint, params, hasJson = false) { | |
const url = this.get(`${module}Host`) + endpoint; | |
if (hasJson) { | |
return this._super(url, { contentType: 'application/json; charset=utf-8', data: params }).catch((error) => this._handleErrors(error)); | |
} | |
return this._super(url, { data: decamelizeObject(params) }).catch((error) => this._handleErrors(error)); | |
}, | |
/** | |
* PUT | |
* | |
* @override | |
*/ | |
put(module, endpoint, params) { | |
const url = this.get(`${module}Host`) + endpoint; | |
return this._super(url, { data: decamelizeObject(params) }).catch((error) => this._handleErrors(error)); | |
}, | |
_handleErrors(error) { | |
const errors = convertToJsonApiErrors(error.payload.error); | |
error.normalizedErrors = normalizeJsonApiErrors(errors); | |
throw error; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment