Skip to content

Commit 6ac8016

Browse files
committed
Extract baseUrl + api root into static method
This will allow consumers to inject additional functionality like being able to live-switch the host or namespace at request time.
1 parent 4b7b21d commit 6ac8016

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/model.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ export default class Model {
132132

133133
static url(id?: string | number) : string {
134134
let endpoint = this.endpoint || `/${this.jsonapiType}`;
135-
let base = `${this.baseUrl}${this.apiNamespace}${endpoint}`;
135+
let base = `${this.fullBasePath()}${endpoint}`;
136136

137137
if (id) {
138138
base = `${base}/${id}`;
@@ -141,6 +141,10 @@ export default class Model {
141141
return base;
142142
}
143143

144+
static fullBasePath() : string {
145+
return `${this.baseUrl}${this.apiNamespace}`;
146+
}
147+
144148
static fromJsonapi(resource: japiResource, payload: japiDoc) : any {
145149
return deserialize(resource, payload);
146150
}

test/unit/model-test.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,33 @@ describe('Model', function() {
7676
});
7777
});
7878

79+
describe('.url', function() {
80+
context('Default base URL generation method', function() {
81+
it('should append the baseUrl, apiNamespace, and jsonapi type', function(){
82+
class DefaultBaseUrl extends ApplicationRecord {
83+
static baseUrl : string = 'http://base.com'
84+
static apiNamespace : string = '/namespace/v1'
85+
static jsonapiType : string = 'testtype'
86+
}
87+
88+
expect(DefaultBaseUrl.url('testId')).to.eq('http://base.com/namespace/v1/testtype/testId')
89+
})
90+
})
91+
92+
context('Base URL path generation is overridden', function() {
93+
it('should use the result of the override function', function(){
94+
class OverriddenBaseUrl extends ApplicationRecord {
95+
static jsonapiType : string = 'testtype'
96+
static fullBasePath() : string {
97+
return 'http://overridden.base'
98+
}
99+
}
100+
101+
expect(OverriddenBaseUrl.url('testId')).to.eq('http://overridden.base/testtype/testId')
102+
})
103+
})
104+
})
105+
79106
describe('#getJWT', function() {
80107
beforeEach(function() {
81108
ApplicationRecord.jwt = 'g3tm3';

0 commit comments

Comments
 (0)