import { JsonApi, Spec } from '../src/index'; import { SchemaError } from '../src/schemaChecker'; /* tslint:disable:no-unused-expression,await-promise,no-unsafe-any,completed-docs */ type Responder = (url: URL) => Spec.JsonApiDocument; /** Answers by pathname and records the requested URLs */ class RecordingContext implements JsonApi.Context { readonly requested: URL[] = []; constructor(private readonly responders: { [path: string]: Responder }) {} async getDocument(url: URL): Promise { this.requested.push(new URL(url.href)); const responder = this.responders[url.pathname]; if (!responder) { return Promise.reject(`The path "${url.pathname}" was not found`); } return Promise.resolve(responder(url)); } } const base = 'http://example.com'; function comment(id: string): Spec.ResourceObject { return { type: 'comments', id, attributes: { text: `comment ${id}` } }; } /** A collection of comments 1..6 in pages of two, the page number is `page[number]` */ function pagedComments(url: URL): Spec.JsonApiDocument { const number = Number(url.searchParams.get('page[number]') || '1'); const ids = [1, 2].map((offset) => String((number - 1) * 2 + offset)); const pageLink = (n: number) => `${base}/comments?page[number]=${n}`; return { data: ids.map(comment), links: { first: pageLink(1), last: pageLink(3), prev: number > 1 ? pageLink(number - 1) : null, next: number < 3 ? pageLink(number + 1) : null, }, }; } function article(commentsRelationship: Spec.RelationshipObject): Spec.JsonApiDocument { return { data: { type: 'articles', id: '1', relationships: { comments: commentsRelationship } } }; } async function articleResource( commentsRelationship: Spec.RelationshipObject, comments: Responder = pagedComments, sparseFields?: JsonApi.SparseFields, ) { const context = new RecordingContext({ '/articles/1': () => article(commentsRelationship), '/comments': comments }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/articles/1`), context, sparseFields); return { context, resource: doc.resource!, relationship: doc.resource!.relationships['comments'] }; } const ids = (resources: JsonApi.Resource[]) => resources.map((r) => r.id); describe('QueryParams', () => { it('builds the standard JSON:API members', () => { const params = new JsonApi.QueryParams() .include(['author']) .fields('articles', ['title', 'body']) .sort(['-created', 'title']) .filter('author.name', 'Dan') .page('size', 10) .custom('debug', true); expect(params.entries()).toEqual([ ['include', 'author'], ['fields[articles]', 'title,body'], ['sort', '-created,title'], ['filter[author.name]', 'Dan'], ['page[size]', '10'], ['debug', 'true'], ]); }); it('builds nested filter keys from a path', () => { const params = new JsonApi.QueryParams().filter(['simple', 'primary', 'id__in'], '1,2').filter(['author'], 5); expect(params.entries()).toEqual([ ['filter[simple][primary][id__in]', '1,2'], ['filter[author]', '5'], ]); expect(params.entries()).toEqual( new JsonApi.QueryParams().filter('simple][primary][id__in', '1,2').filter('author', 5).entries(), ); }); it.each([[[]], [['simple', '']], [['simple]', 'name']], [['simple', '[name']], [['simple', 1]]])( 'rejects the filter path %j', (path) => { const params = new JsonApi.QueryParams(); expect(() => params.filter(path, 'x')).toThrow(TypeError); expect(params.isEmpty).toBe(true); }, ); it('merges lists without duplicates or replaces them', () => { const params = new JsonApi.QueryParams().sort(['a', 'b']).sort(['b', 'c']).include(['x']); expect(params.entries()).toEqual([ ['sort', 'a,b,c'], ['include', 'x'], ]); params.sort(['d'], true).include([''], true).fields('t', [], true); expect(params.entries()).toEqual([ ['sort', 'd'], ['include', ''], ]); }); it('copies and merges without changing the original', () => { const params = new JsonApi.QueryParams([['a', 1]]); const merged = params.merge(new JsonApi.QueryParams().filter('b', 'x')); const copy = params.copy().page('size', 2); expect(params.entries()).toEqual([['a', '1']]); expect(merged.entries()).toEqual([ ['a', '1'], ['filter[b]', 'x'], ]); expect(copy.entries()).toEqual([ ['a', '1'], ['page[size]', '2'], ]); expect(new JsonApi.QueryParams().isEmpty).toBe(true); }); it('appends to a copy of a URL', () => { const url = new URL(`${base}/articles?x=1`); const result = new JsonApi.QueryParams().sort(['title']).applyTo(url); expect(url.href).toBe(`${base}/articles?x=1`); expect(result.searchParams.get('x')).toBe('1'); expect(result.searchParams.get('sort')).toBe('title'); }); }); describe('Document.fromURL', () => { it('sends sparse fields and query parameters without changing the given URL', async () => { const context = new RecordingContext({ '/comments': pagedComments }); const url = new URL(`${base}/comments`); const params = new JsonApi.QueryParams().sort(['-created']).filter('author', '5').page('number', 2); const doc = await JsonApi.Document.fromURL(url, context, { comments: ['text'] }, params); expect(url.href).toBe(`${base}/comments`); const requested = context.requested[0]; expect(requested.searchParams.get('fields[comments]')).toBe('text'); expect(requested.searchParams.get('sort')).toBe('-created'); expect(requested.searchParams.get('filter[author]')).toBe('5'); expect(requested.searchParams.get('page[number]')).toBe('2'); expect(doc.url!.href).toBe(requested.href); expect(ids(doc.resources)).toEqual(['3', '4']); }); }); describe('A paged document', () => { it('provides its links without null values', async () => { const context = new RecordingContext({ '/comments': pagedComments }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/comments`), context); expect(Object.keys(doc.links).sort()).toEqual(['first', 'last', 'next']); expect(await doc.prevPage()).toBeUndefined(); }); it('resolves relative links against the document URL', async () => { const context = new RecordingContext({ '/comments': (url) => url.searchParams.get('page[number]') === '2' ? { data: [comment('2')] } : { data: [comment('1')], links: { next: '/comments?page[number]=2' } }, }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/comments`), context); const next = await doc.nextPage(); expect(next!.url!.href).toBe(`${base}/comments?page[number]=2`); expect(ids(next!.resources)).toEqual(['2']); }); it('navigates between pages', async () => { const context = new RecordingContext({ '/comments': pagedComments }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/comments`), context, { comments: ['text'] }); const second = await doc.nextPage(); expect(ids(second!.resources)).toEqual(['3', '4']); expect(second!.sparseFields).toEqual({ comments: ['text'] }); expect(ids((await second!.prevPage())!.resources)).toEqual(['1', '2']); expect(ids((await second!.lastPage())!.resources)).toEqual(['5', '6']); expect(ids((await second!.firstPage())!.resources)).toEqual(['1', '2']); expect(await doc.nextPage()).toBe(second); }); it('collects all pages and resources', async () => { const context = new RecordingContext({ '/comments': pagedComments }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/comments`), context); expect((await doc.allPages()).length).toBe(3); expect(ids(await doc.allResources())).toEqual(['1', '2', '3', '4', '5', '6']); expect(context.requested.length).toBe(3); }); }); describe('Large pages', () => { const pageSize = 150000; it('collects a document page above the function argument limit', async () => { const context = new RecordingContext({ '/last': () => ({ data: [comment('last')] }) }); const doc = new JsonApi.Document( { data: Array.from({ length: pageSize }, (_, index) => comment(String(index))), links: { next: `${base}/last` }, }, context, ); const resources = await doc.allResources(); expect(resources).toHaveLength(pageSize + 1); expect(resources[0].id).toBe('0'); expect(resources[pageSize - 1].id).toBe(String(pageSize - 1)); expect(resources[pageSize].id).toBe('last'); expect(context.requested.map((url) => url.href)).toEqual([`${base}/last`]); }); it('collects a large later page of a related document', async () => { const { context, relationship } = await articleResource( { links: { related: `${base}/comments` } }, (url) => url.searchParams.has('page[number]') ? { data: Array.from({ length: pageSize }, (_, index) => comment(String(index))) } : { data: [comment('first')], links: { next: `${base}/comments?page[number]=2` } }, ); const resources = await relationship.resources(); expect(resources).toHaveLength(pageSize + 1); expect(resources[0].id).toBe('first'); expect(resources[1].id).toBe('0'); expect(resources[pageSize].id).toBe(String(pageSize - 1)); expect(context.requested.map((url) => url.href)).toEqual([ `${base}/articles/1`, `${base}/comments`, `${base}/comments?page[number]=2`, ]); }); }); describe('A to-many relationship with a paged related document', () => { const related = { links: { related: `${base}/comments` } }; it('follows the next links by default', async () => { const { context, relationship } = await articleResource(related); expect(ids(await relationship.resources())).toEqual(['1', '2', '3', '4', '5', '6']); expect(context.requested.length).toBe(4); }); it('follows the next links through the relatedResources accessor', async () => { const { resource } = await articleResource(related); expect(ids(await resource.relatedResources['comments'])).toEqual(['1', '2', '3', '4', '5', '6']); }); it('returns only the requested page with followPaging: false', async () => { const { relationship } = await articleResource(related); expect(ids(await relationship.resources({ followPaging: false }))).toEqual(['1', '2']); expect(ids(await relationship.resources({ followPaging: false, page: { number: 3 } }))).toEqual(['5', '6']); }); it('rejects a paged response with allowPaging: false', async () => { const { relationship } = await articleResource(related); await expect(relationship.resources({ allowPaging: false })).rejects.toThrowError(JsonApi.PagingNotAllowedError); await expect(relationship.resourcesFromRelatedLink({ allowPaging: false })).rejects.toThrowError( JsonApi.PagingNotAllowedError, ); await expect(relationship.resources({ allowPaging: false, page: { number: 3 } })).resolves.toHaveLength(2); }); it('rejects contradicting paging options', async () => { const { relationship } = await articleResource(related); await expect(relationship.resources({ allowPaging: false, followPaging: true })).rejects.toThrowError(TypeError); }); it('memoizes only requests without options', async () => { const { context, relationship } = await articleResource(related); const first = await relationship.relatedDocument(); expect(await relationship.relatedDocument()).toBe(first); await relationship.relatedDocument({ sort: ['text'] }); await relationship.relatedDocument({ sort: ['text'] }); expect(context.requested.length).toBe(4); expect(await relationship.resources()).toBe(await relationship.resources()); }); }); describe('Requesting a related document with options', () => { it('sends sort and page, replacing the paging of the link and keeping its other parameters', async () => { const { context, relationship } = await articleResource({ links: { related: `${base}/comments?filter[author]=5&sort=id&page[cursor]=abc&page[size]=2` }, }); await relationship.relatedDocument({ sort: ['-created'], page: { number: 2 } }); const requested = context.requested[1]; expect(requested.searchParams.get('filter[author]')).toBe('5'); expect(requested.searchParams.getAll('sort')).toEqual(['-created']); expect(requested.searchParams.get('page[number]')).toBe('2'); expect(requested.searchParams.has('page[cursor]')).toBe(false); expect(requested.searchParams.has('page[size]')).toBe(false); }); it('merges the paging of the link with replacePage: false', async () => { const { context, relationship } = await articleResource({ links: { related: `${base}/comments?page[cursor]=abc&page[size]=2` }, }); await relationship.relatedDocument({ page: { size: 10 }, replacePage: false }); const requested = context.requested[1]; expect(requested.searchParams.get('page[cursor]')).toBe('abc'); expect(requested.searchParams.getAll('page[size]')).toEqual(['10']); }); it('replaces the sparse fields of the referring document per type', async () => { const { context, relationship } = await articleResource( { links: { related: `${base}/comments?fields[comments]=id` } }, pagedComments, { comments: ['text'], people: ['name'] }, ); const doc = await relationship.relatedDocument({ sparseFields: { comments: ['author'] } }); const requested = context.requested[1]; expect(requested.searchParams.getAll('fields[comments]')).toEqual(['author']); expect(requested.searchParams.get('fields[people]')).toBe('name'); expect(doc!.sparseFields).toEqual({ comments: ['author'], people: ['name'] }); }); it('validates sort and page', async () => { const { relationship } = await articleResource({ links: { related: `${base}/comments` } }); await expect(relationship.relatedDocument({ sort: [''] })).rejects.toThrowError(TypeError); await expect(relationship.relatedDocument({ page: { size: null } })).rejects.toThrowError(TypeError); }); }); describe('A to-many relationship with resource linkage', () => { const linkage = { data: [{ type: 'comments', id: '9' }], links: { related: `${base}/comments` } }; it('prefers the linkage without options', async () => { const { context, relationship } = await articleResource(linkage); expect(ids(await relationship.resources())).toEqual(['9']); expect(context.requested.length).toBe(1); }); it('uses included linkage without resolving unused relative links or null paging links', async () => { const context = new RecordingContext({}); const doc = new JsonApi.Document( { ...article({ data: [{ type: 'comments', id: '9' }], links: { related: 'comments', self: { href: 'relationships/comments' }, next: null, prev: null }, }), included: [comment('9')], }, context, ); const resources = await doc.resource!.relationships['comments'].resources(); expect(ids(resources)).toEqual(['9']); expect(resources[0].attributes!['text']).toBe('comment 9'); expect(context.requested).toHaveLength(0); }); it('uses the related link for sort and page', async () => { const { context, relationship } = await articleResource(linkage); expect(ids(await relationship.resources({ sort: ['text'], followPaging: false }))).toEqual(['1', '2']); expect(context.requested[1].searchParams.get('sort')).toBe('text'); }); it('needs a related link for sort and page', async () => { const { relationship } = await articleResource({ data: [{ type: 'comments', id: '9' }] }); await expect(relationship.resources({ sort: ['text'] })).rejects.toThrowError(SchemaError); }); it('does not use paged linkage', async () => { const { relationship } = await articleResource({ data: [{ type: 'comments', id: '1' }], links: { related: `${base}/comments`, next: `${base}/articles/1/relationships/comments?page[number]=2` }, }); expect(ids(await relationship.resources())).toEqual(['1', '2', '3', '4', '5', '6']); }); }); describe('Relative links', () => { it('resolve against the full document URL', async () => { const context = new RecordingContext({ '/api/comments': (url) => url.searchParams.get('page[number]') === '3' ? { data: [comment('3')] } : url.searchParams.get('page[number]') === '2' ? { data: [comment('2')], links: { next: { href: 'comments?page[number]=3' } } } : { data: [comment('1')], links: { next: '?page[number]=2' } }, }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/api/comments`), context); const second = await doc.nextPage(); expect(second!.url!.href).toBe(`${base}/api/comments?page[number]=2`); const third = await second!.nextPage(); expect(third!.url!.href).toBe(`${base}/api/comments?page[number]=3`); }); /** Redirects `/api/comments` to `/api/comments/` like `fetch` does, and reports the URL it was received from */ class RedirectingContext extends RecordingContext implements JsonApi.Context { async getDocumentWithURL(url: URL): Promise { const received = url.pathname === '/api/comments' ? new URL(`${base}/api/comments/`) : url; return { rawData: await this.getDocument(received), url: received }; } } it('resolve against the URL the context reports, e.g. after redirects', async () => { const context = new RedirectingContext({ '/api/comments/': () => ({ data: [{ ...comment('1'), relationships: { author: { links: { related: 'authors/1' } } } }], links: { next: 'page2' }, }), '/api/comments/page2': () => ({ data: [comment('2')] }), }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/api/comments`), context); expect(doc.url!.href).toBe(`${base}/api/comments`); expect(doc.effectiveURL!.href).toBe(`${base}/api/comments/`); expect(doc.resources[0].relationships['author'].links!['related'].url.href).toBe(`${base}/api/comments/authors/1`); expect(ids(await doc.allResources())).toEqual(['1', '2']); expect(context.requested.map((url) => url.href)).toEqual([`${base}/api/comments/`, `${base}/api/comments/page2`]); }); it('resolve against the requested URL without a reported URL', async () => { const withoutURL: JsonApi.Context = { getDocument: () => Promise.reject('getDocumentWithURL must be used'), getDocumentWithURL: async () => ({ rawData: { data: [], links: { next: '?page[number]=2' } } }), }; const doc = await JsonApi.Document.fromURL(new URL(`${base}/api/comments`), withoutURL); expect(doc.effectiveURL!.href).toBe(`${base}/api/comments`); expect(doc.links['next'].url.href).toBe(`${base}/api/comments?page[number]=2`); const plain = new JsonApi.Document({ data: [] }, withoutURL, new URL(`${base}/x`)); expect(plain.effectiveURL!.href).toBe(`${base}/x`); }); }); describe('Sparse field options with resource linkage', () => { function context(commentAttributes: Spec.AttributesObject, links?: Spec.LinksObject) { return new RecordingContext({ '/articles/1': () => ({ data: { type: 'articles', id: '1', relationships: { comments: { data: [{ type: 'comments', id: '1' }], ...(links ? { links } : {}) } }, }, included: [ { type: 'comments', id: '1', attributes: commentAttributes, relationships: { author: { links: { related: `${base}/people/9` } } }, }, ], }), '/comments': () => ({ data: [ { type: 'comments', id: '1', attributes: { text: 'fetched', created: 'today' }, relationships: { author: { links: { related: `${base}/people/9` } } }, }, ], }), '/people/9': () => ({ data: { type: 'people', id: '9', attributes: { email: 'a@b.c' } } }), }); } it('apply to documents fetched from resources resolved by linkage', async () => { const ctx = context({ text: 'included' }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/articles/1`), ctx, { people: ['name'] }); const comments = await doc.resource!.relationships['comments'].resources({ sparseFields: { people: ['email'] } }); expect(comments[0].attributes!['text']).toBe('included'); await comments[0].relatedResource['author']; expect(ctx.requested[ctx.requested.length - 1].searchParams.get('fields[people]')).toBe('email'); }); it('use the related link if the included resources lack requested fields', async () => { const ctx = context({ text: 'included' }, { related: `${base}/comments` }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/articles/1`), ctx); const comments = await doc.resource!.relationships['comments'].resources({ sparseFields: { comments: ['created'] }, }); expect(comments[0].attributes!['text']).toBe('fetched'); expect(ctx.requested[1].searchParams.get('fields[comments]')).toBe('created'); }); it('need a related link if the included resources lack requested fields', async () => { const ctx = context({ text: 'included' }); const doc = await JsonApi.Document.fromURL(new URL(`${base}/articles/1`), ctx); const relationship = doc.resource!.relationships['comments']; await expect(relationship.resources({ sparseFields: { comments: ['created'] } })).rejects.toThrowError(SchemaError); }); });