diff --git a/src/lib/collection.spec.ts b/src/lib/collection.spec.ts index 9522653..f72eeb8 100644 --- a/src/lib/collection.spec.ts +++ b/src/lib/collection.spec.ts @@ -215,6 +215,13 @@ describe('Collection', () => { expect(broken.next()).toBeUndefined(); }); + it('returns accessor with link when next rel exists', () => { + const accessor = paged.next(); + + expect(accessor).toBeDefined(); + expect(accessor?.self).toBe('/api/test?start=44&limit2'); + }); + it('returns undefined when canRead() is false', () => { const broken = new Collection(TestResource, { _client: spectator.httpClient, @@ -236,12 +243,56 @@ describe('Collection', () => { expect(broken.next()).toBeUndefined(); }); + }); - it('returns accessor with link when next rel exists', () => { - const accessor = paged.next(); + describe('#previous()', () => { + it('returns undefined when prev rel does not exist', () => { + expect(collection.previous()).toBeUndefined(); + }); + + it('returns undefined when prev rel does not have href', () => { + const broken = new Collection(TestResource, { + _client: spectator.httpClient, + _links: { + self: { href: '/api/test' }, + prev: {} + }, + _embedded: { + array: [] + }, + start: 0 + }); + + expect(broken.previous()).toBeUndefined(); + }); + + it('returns accessor with link when prev rel exists', () => { + const accessor = paged.previous(); expect(accessor).toBeDefined(); - expect(accessor?.self).toBe('/api/test?start=44&limit2'); + expect(accessor?.self).toBe('/api/test?start=40&limit2'); + }); + + it('returns undefined when canRead() is false', () => { + const broken = new Collection(TestResource, { + _client: spectator.httpClient, + _links: { + self: { href: '/api/test' }, + prev: { + href: '/api/test?start=40&limit2', + methods: ['DELETE'] + } + }, + _embedded: { + array: [ + { version: '2.0.0' }, + { version: '3.0.0' } + ] + }, + start: 42 + }); + + expect(broken.previous()).toBeUndefined(); }); }); diff --git a/src/lib/collection.ts b/src/lib/collection.ts index 4119e6c..93f9eb9 100644 --- a/src/lib/collection.ts +++ b/src/lib/collection.ts @@ -5,6 +5,8 @@ import { Accessor } from './accessor'; const next = 'next'; +const prev = 'prev'; + /** * This class represents an in-memory collection of resources. */ @@ -42,12 +44,28 @@ export class Collection extends Resource { this.values = []; } + /** + * Follow `next` link if it exists and can be read. + * + * @returns the accessor for the link or `undefined` + */ next(): Accessor | undefined { const accessor = this.follow(next); return !!accessor && accessor.canRead ? accessor : undefined; } + /** + * Follow `prev` link if it exists and can be read. + * + * @returns the accessor for the link or `undefined` + */ + previous(): Accessor | undefined { + const accessor = this.follow(prev); + + return !!accessor && accessor.canRead ? accessor : undefined; + } + /** * Refresh the resource collection. In other words, read * the resource collection identified by `self` link.