diff --git a/README.md b/README.md index eacca77..4f599b6 100644 --- a/README.md +++ b/README.md @@ -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 ... +``` diff --git a/src/hal-rest-client.ts b/src/hal-rest-client.ts index 6c18e8b..ba291c8 100644 --- a/src/hal-rest-client.ts +++ b/src/hal-rest-client.ts @@ -30,7 +30,23 @@ export class HalRestClient { } fetchResource(resourceURI : string) : Promise { - return this.fetch(resourceURI, HalResource); + return this.fetch(resourceURI, HalResource); + } + + fetchArray(resourceURI : string, c : IHalResourceConstructor) : Promise> { + // 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(resourceURI : string, c : IHalResourceConstructor, resource ?: T): Promise { diff --git a/src/test/test-resource-class.ts b/src/test/test-resource-class.ts index c289e32..bdc4127 100644 --- a/src/test/test-resource-class.ts +++ b/src/test/test-resource-class.ts @@ -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) { @@ -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 {