Add $prepare function to HalLink interface for templated URLs

Templated urls are of the form, e.g., `/api/v3/.../{user_id}`.
The HalLink had a flag that the given URL is templated, but no interface
to expand that link given a mapping for the templated parts.

This is required for the refactoring of the watchers tab.
pull/5053/head
Oliver Günther 8 years ago
parent 76881f1853
commit d69bc4a2b2
No known key found for this signature in database
GPG Key ID: 88872239EB414F99
  1. 58
      frontend/app/components/api/api-v3/hal-link/hal-link.service.test.ts
  2. 26
      frontend/app/components/api/api-v3/hal-link/hal-link.service.ts

@ -229,5 +229,63 @@ describe('HalLink service', () => {
runChecks();
});
});
describe('when $preparing the link', () => {
var func;
beforeEach(() => {
link.href = '/foo/bar/{user_id}';
link.title = 'title';
link.method = 'post';
link.templated = true;
});
describe('when the link is NOT templated', () => {
beforeEach(() => {
link.templated = false;
});
it('should raise an exception', () => {
expect(function() {
link.$prepare({});
}).to.throw;
});
});
describe('when the link is templated', () => {
beforeEach(() => {
func = link.$prepare({ user_id: '1234' });
});
it('should return a function that fetches the data', () => {
func();
$httpBackend.expectPOST('/foo/bar/1234').respond(200, {});
$httpBackend.flush();
});
it('should pass the params to $fetch', () => {
var $fetch = sinon.spy(func.$link, '$fetch');
func('hello');
expect($fetch.calledWith('hello')).to.be.true;
});
it('should have the untemplated href property', () => {
expect(func.href).to.equal('/foo/bar/1234');
});
it('should have the title property of the link', () => {
expect(func.title).to.equal(link.title);
});
it('should have the method property of the link', () => {
expect(func.method).to.equal(link.method);
});
it('should not be templated', () => {
expect(func.templated).to.equal(false);
});
});
});
});
});

@ -76,6 +76,31 @@ export class HalLink implements HalLinkInterface {
return halRequest.request(this.method, this.href, data, headers);
}
/**
* Prepare the templated link and return a CallableHalLink with the templated parameters set
*
* @returns {CallableHalLink}
*/
public $prepare(templateValues:{[templateKey:string]: string}) {
if (!this.templated) {
throw 'The link ' + this.href + ' is not templated.';
}
let href = _.clone(this.href);
_.each(templateValues, (value, key) => {
let regexp = new RegExp('{' + key + '}');
href = href.replace(regexp, value);
});
return HalLink.callable({
href: href,
title: this.title,
method: this.method,
templated: false,
payload: this.payload
});
}
/**
* Return a function that fetches the resource.
*
@ -95,6 +120,7 @@ export class HalLink implements HalLinkInterface {
return linkFunc;
}
}
function halLinkService(...args) {

Loading…
Cancel
Save