Created
December 4, 2015 14:40
-
-
Save vbauerster/85386cfc0396a7b56bee 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 {HttpClient} from 'aurelia-fetch-client' | |
import {Authentication} from './authentication'; | |
import {BaseConfig} from './baseConfig' | |
import {inject} from 'aurelia-framework'; | |
import {Storage} from './storage'; | |
@inject(HttpClient, Authentication, Storage, BaseConfig) | |
export class FetchConfig { | |
constructor(httpClient, authService, storage, config){ | |
this.httpClient = httpClient; | |
this.auth = authService; | |
this.storage = storage; | |
this.config = config.current; | |
} | |
configure(){ | |
var auth = this.auth; | |
var config = this.config; | |
var storage = this.storage; | |
var isConfigured = this.httpClient.isConfigured; | |
this.httpClient.configure(httpConfig => { | |
let defaults = { | |
headers: { | |
'Accept': 'application/json' | |
} | |
}; | |
let baseUrl = ''; | |
if (isConfigured) { | |
if (Object.keys(this.httpClient.defaults).length > 0) { | |
// respect user settings | |
Object.assign(defaults, this.httpClient.defaults); | |
} | |
if (this.httpClient.baseUrl) { | |
config.baseUrl = ''; | |
baseUrl = this.httpClient.baseUrl; | |
} | |
} | |
httpConfig | |
.withBaseUrl(baseUrl) | |
.withDefaults(defaults) | |
.withInterceptor({ | |
request(request) { | |
if (auth.isAuthenticated() && config.httpInterceptor) { | |
var tokenName = config.tokenPrefix ? `${config.tokenPrefix}_${config.tokenName}` : config.tokenName; | |
var token = storage.get(tokenName); | |
if (config.authHeader && config.authToken) { | |
token = `${config.authToken} ${token}`; | |
} | |
request.headers.append(config.authHeader, token); | |
} | |
return request; | |
} | |
}); | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment