Skip to content
This repository has been archived by the owner on Oct 7, 2021. It is now read-only.

Commit

Permalink
feature(fetch array) : api can now fetch an array of object
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas DEBLOCK committed Mar 24, 2017
1 parent 02180aa commit 99f80a9
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,12 @@ await client.contactInfos.fetch();

console.log(client.contactInfos.phone) // show ...;
```

Function fetchArray can be use for get list of item :
``` ts
// ...
let persons = await client.fetchArray('/persons', Person);

// persons contains list of Person. It's an Array
console.log(persons[0].name); // show ...
```
18 changes: 17 additions & 1 deletion src/hal-rest-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,23 @@ export class HalRestClient {
}

fetchResource(resourceURI : string) : Promise<HalResource> {
return this.fetch(resourceURI, HalResource);
return this.fetch(resourceURI, HalResource);
}

fetchArray<T extends IHalResource>(resourceURI : string, c : IHalResourceConstructor<T>) : Promise<Array<T>> {
// TODO use HalArray instead of this shit
return this.fetchResource(resourceURI).then((halResource) => {
var array = [];
var source = halResource.prop(Object.keys(halResource.props)[0]);
for (let item of source) {
var resource = createResource(item.uri, c);
resource.props = item.props;
resource.links = item.links;
resource.isLoaded = item.isLoaded;
array.push(resource);
}
return array;
});
}

fetch<T extends IHalResource>(resourceURI : string, c : IHalResourceConstructor<T>, resource ?: T): Promise<T> {
Expand Down
15 changes: 15 additions & 0 deletions src/test/test-resource-class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ function initTests() {
testNock
.get('/person/2/contactInfos')
.reply(200, contactInfos);
testNock
.get('/persons')
.reply(200, {
"_links" : {"self" : {"href" : "http://test.fr/person"}},
"_embedded" : { "persons" : [JSON.parse(JSON.stringify(person1))] }
});
}

test('can get single string prop', async function(t) {
Expand All @@ -118,6 +124,15 @@ test('can get single string prop', async function(t) {
t.equals(person.name, "Toto");
});

test('can fetch Array of Person', async function(t) {
initTests();
let client = createClient('http://test.fr/');
let persons = await client.fetchArray('/persons', Person);
t.equals(persons.length, 1);
t.ok(persons[0] instanceof Person, "items is a person");
t.equals(persons[0].name, "Project 1");
})

test('bad use of @HalProperty show error', async function(t) {
try {
class Test extends HalResource {
Expand Down

0 comments on commit 99f80a9

Please sign in to comment.