json-rest-api 1.0.27 → 1.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/docs/API.md +2 -0
  2. package/docs/GUIDE/GUIDE_2_7_Pagination_And_Ordering.md +11 -2
  3. package/docs/GUIDE/GUIDE_3_Field_Transformations.md +3 -3
  4. package/docs/GUIDE/GUIDE_Y_Appendices.md +57 -29
  5. package/index.js +1 -0
  6. package/lib/rest-api-errors.js +35 -0
  7. package/package.json +2 -2
  8. package/plugins/core/connectors/lib/transport-http-helpers.js +12 -1
  9. package/plugins/core/file-handling-plugin.js +3 -0
  10. package/plugins/core/lib/anyapi/schema-utils.js +2 -1
  11. package/plugins/core/lib/anyapi/utils/descriptor-helpers.js +4 -2
  12. package/plugins/core/lib/dbTablesOperations.js +20 -10
  13. package/plugins/core/lib/querying/knex-pagination-helpers.js +29 -13
  14. package/plugins/core/lib/querying/knex-relationship-includes.js +18 -7
  15. package/plugins/core/lib/querying/query-field-sort-helpers.js +93 -15
  16. package/plugins/core/lib/querying/sort-helpers.js +8 -1
  17. package/plugins/core/lib/querying-writing/database-value-normalizers.js +297 -143
  18. package/plugins/core/lib/querying-writing/knex-field-helpers.js +15 -1
  19. package/plugins/core/lib/querying-writing/request-contracts.js +16 -6
  20. package/plugins/core/lib/storage/canonical-storage-mapping.js +11 -1
  21. package/plugins/core/lib/storage/storage-adapter.js +19 -3
  22. package/plugins/core/lib/storage/storage-mapping.js +7 -1
  23. package/plugins/core/rest-api-anyapi-knex-plugin.js +36 -60
  24. package/plugins/core/rest-api-knex-plugin.js +28 -20
  25. package/plugins/core/rest-api-plugin-methods/common.js +15 -0
  26. package/plugins/core/rest-api-plugin-methods/enrich-attributes.js +3 -0
  27. package/plugins/core/rest-api-plugin-methods/get.js +8 -1
  28. package/plugins/core/rest-api-plugin-methods/query.js +8 -1
  29. package/tests/anyapi-cursor-pagination.test.js +1 -3
  30. package/tests/computed-fields.test.js +21 -0
  31. package/tests/db-table-operations.test.js +13 -1
  32. package/tests/file-handling.test.js +37 -0
  33. package/tests/fixtures/api-configs.js +140 -3
  34. package/tests/pagination-boundaries.test.js +154 -0
  35. package/tests/pagination-contract.test.js +122 -0
  36. package/tests/pagination-cursor-multifield.test.js +5 -3
  37. package/tests/relationship-include-storage-adapter.test.js +56 -0
  38. package/tests/storage-mapping.test.js +112 -10
  39. package/tests/temporal-boundaries.test.js +208 -0
@@ -58,6 +58,63 @@ async function withTenantContext (tenantId, fn) {
58
58
  }
59
59
  }
60
60
 
61
+ export async function createTemporalBoundaryApi (knex) {
62
+ const api = new Api({ name: 'temporal-boundaries', log: { level: 'error' } })
63
+ await api.use(RestApiPlugin, {
64
+ simplifiedApi: false,
65
+ simplifiedTransport: false,
66
+ returnRecordApi: { post: 'full', put: 'full', patch: 'full' },
67
+ queryDefaultLimit: 2,
68
+ queryMaxLimit: 3
69
+ })
70
+ await api.use(QueryProjectionsPlugin)
71
+ await useStoragePlugin(api, knex)
72
+ const producedAt = {
73
+ type: 'dateTime', temporalPrecision: 0, computed: true,
74
+ compute: () => new Date('2026-09-08T01:02:03.456Z')
75
+ }
76
+ await api.addResource('people', {
77
+ schema: { id: { type: 'id' }, name: { type: 'string' }, producedAt },
78
+ relationships: { events: { type: 'hasMany', target: 'events', foreignKey: 'personId' } },
79
+ tableName: 'temporal_people'
80
+ })
81
+ await api.resources.people.createKnexTable()
82
+ mapTable('temporal_people', 'people')
83
+ await api.addResource('events', {
84
+ sortableFields: ['id', 'name', 'occurredAt', 'day', 'atTime', 'observedAtMs'],
85
+ schema: {
86
+ id: { type: 'id' },
87
+ name: { type: 'string', required: true },
88
+ occurredAt: { type: 'dateTime', temporalPrecision: 6, nullable: true, search: true },
89
+ day: { type: 'date', nullable: true, search: true },
90
+ atTime: { type: 'time', temporalPrecision: 3, nullable: true, search: true },
91
+ observedAtMs: { type: 'epochMilliseconds', nullable: true, search: true },
92
+ observedAtSeconds: { type: 'epochSeconds', nullable: true, search: true },
93
+ serializedAt: {
94
+ type: 'dateTime', temporalPrecision: 6, nullable: true, search: true,
95
+ storage: { serialize: value => value == null ? null : value.replace('T', ' ').replace(/Z$/, '') }
96
+ },
97
+ personId: { type: 'id', belongsTo: 'people', as: 'person', nullable: true },
98
+ subjectId: { type: 'number', nullable: true },
99
+ subjectType: { type: 'string', nullable: true },
100
+ producedAt
101
+ },
102
+ queryFields: {
103
+ projectedAt: {
104
+ type: 'dateTime', temporalPrecision: 3, sortable: true,
105
+ select: ({ knex, column }) => knex.raw('??', [column('occurredAt')])
106
+ }
107
+ },
108
+ relationships: {
109
+ subject: { belongsToPolymorphic: { types: ['people'], typeField: 'subjectType', idField: 'subjectId' } }
110
+ },
111
+ tableName: 'temporal_events'
112
+ })
113
+ await api.resources.events.createKnexTable()
114
+ mapTable('temporal_events', 'events')
115
+ return api
116
+ }
117
+
61
118
  /**
62
119
  * Creates a basic API configuration with Countries, Publishers, Authors, Books
63
120
  */
@@ -334,6 +391,68 @@ export async function createCamelCaseBelongsToApi (knex, pluginOptions = {}) {
334
391
  return api
335
392
  }
336
393
 
394
+ export async function createRelationshipIncludeStorageAdapterApi (knex) {
395
+ const api = new Api({
396
+ name: 'relationship-include-storage-adapter-test',
397
+ log: { level: process.env.LOG_LEVEL || 'info' }
398
+ })
399
+
400
+ await api.use(RestApiPlugin, {
401
+ simplifiedApi: false,
402
+ simplifiedTransport: false
403
+ })
404
+ await api.use(RestApiKnexPlugin, { knex })
405
+
406
+ await knex.schema.createTable('uninitialized_pets', table => {
407
+ table.increments('id').primary()
408
+ table.string('first_name').notNullable()
409
+ table.string('last_name').notNullable()
410
+ })
411
+ await knex.schema.createTable('uninitialized_bookings', table => {
412
+ table.increments('id').primary()
413
+ table.string('reference').notNullable()
414
+ table.integer('pet_id').notNullable()
415
+ })
416
+
417
+ await api.addResource('pets', {
418
+ schema: {
419
+ id: { type: 'id' },
420
+ firstName: { type: 'string', required: true },
421
+ lastName: { type: 'string', required: true }
422
+ },
423
+ tableName: 'uninitialized_pets'
424
+ })
425
+
426
+ await api.addResource('bookings', {
427
+ schema: {
428
+ id: { type: 'id' },
429
+ reference: { type: 'string', required: true },
430
+ petId: {
431
+ type: 'id',
432
+ required: true,
433
+ belongsTo: 'pets',
434
+ as: 'pet'
435
+ }
436
+ },
437
+ tableName: 'uninitialized_bookings'
438
+ })
439
+
440
+ return api
441
+ }
442
+
443
+ export async function seedRelationshipIncludeStorageAdapterApi (knex) {
444
+ await knex('uninitialized_pets').insert({
445
+ id: 7,
446
+ first_name: 'Coco',
447
+ last_name: 'Spaniel'
448
+ })
449
+ await knex('uninitialized_bookings').insert({
450
+ id: 41,
451
+ reference: 'BOOK-41',
452
+ pet_id: 7
453
+ })
454
+ }
455
+
337
456
  /**
338
457
  * Creates a small API focused on resource ID normalization behavior.
339
458
  */
@@ -641,7 +760,7 @@ export async function createExtendedApi (knex) {
641
760
  title: { type: 'string', max: 200 },
642
761
  content: { type: 'string', required: true, max: 5000 },
643
762
  reviewer_name: { type: 'string', required: true, max: 100 },
644
- review_date: { type: 'dateTime', default: 'now()' },
763
+ review_date: { type: 'dateTime', temporalPrecision: 3, defaultTo: () => new Date().toISOString() },
645
764
  helpful_count: { type: 'number', default: 0 },
646
765
  reviewable_type: { type: 'string', required: true },
647
766
  reviewable_id: { type: 'number', required: true }
@@ -976,6 +1095,18 @@ export async function createComputedFieldsApi (knex, pluginOptions = {}) {
976
1095
  compute: ({ attributes }) => {
977
1096
  return Number((attributes.price - attributes.cost).toFixed(2))
978
1097
  }
1098
+ },
1099
+ calculated_at: {
1100
+ type: 'dateTime',
1101
+ temporalPrecision: 0,
1102
+ computed: true,
1103
+ compute: () => new Date('2026-08-25T23:45:01.987Z')
1104
+ },
1105
+ calculated_time: {
1106
+ type: 'time',
1107
+ temporalPrecision: 3,
1108
+ computed: true,
1109
+ compute: () => new Date('2026-08-25T23:45:01.987Z')
979
1110
  }
980
1111
  },
981
1112
  relationships: {
@@ -1016,6 +1147,12 @@ export async function createComputedFieldsApi (knex, pluginOptions = {}) {
1016
1147
  const helpfulnessScore = (attributes.helpful_votes / attributes.total_votes) * 100
1017
1148
  return helpfulnessScore > 70 && attributes.spam_score < 0.5
1018
1149
  }
1150
+ },
1151
+ calculated_at: {
1152
+ type: 'dateTime',
1153
+ temporalPrecision: 0,
1154
+ computed: true,
1155
+ compute: () => new Date('2026-08-25T23:46:02.654Z')
1019
1156
  }
1020
1157
  },
1021
1158
  tableName: 'test_reviews'
@@ -2090,7 +2227,7 @@ export async function createCustomIdPropertyApi (knex, pluginOptions = {}) {
2090
2227
  title: { type: 'string', max: 200 },
2091
2228
  content: { type: 'string', required: true, max: 5000 },
2092
2229
  reviewer_name: { type: 'string', required: true, max: 100 },
2093
- review_date: { type: 'dateTime', default: 'now()' },
2230
+ review_date: { type: 'dateTime', temporalPrecision: 3, defaultTo: () => new Date().toISOString() },
2094
2231
  reviewable_type: { type: 'string', required: true, search: true },
2095
2232
  reviewable_id: { type: 'number', required: true },
2096
2233
  // Define the polymorphic field in schema
@@ -2164,7 +2301,7 @@ export async function createCursorPaginationApi (knex) {
2164
2301
  price: { type: 'number', required: true },
2165
2302
  sku: { type: 'string', required: true, max: 50, unique: true },
2166
2303
  status: { type: 'string', max: 50, default: 'active' },
2167
- createdAt: { type: 'dateTime', default: 'now()' }
2304
+ createdAt: { type: 'dateTime', temporalPrecision: 3, defaultTo: () => new Date().toISOString() }
2168
2305
  },
2169
2306
  tableName: 'cursor_products'
2170
2307
  })
@@ -0,0 +1,154 @@
1
+ import { after, before, beforeEach, describe, it } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import knexLib from 'knex'
4
+ import { createTemporalBoundaryApi } from './fixtures/api-configs.js'
5
+ import { cleanTables, createJsonApiDocument } from './helpers/test-utils.js'
6
+ import { createCursor, parseCursor } from '../plugins/core/lib/querying/knex-pagination-helpers.js'
7
+
8
+ const knex = knexLib({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true })
9
+ let api
10
+ let ids
11
+
12
+ describe('Pagination boundary audit', () => {
13
+ before(async () => { api = await createTemporalBoundaryApi(knex) })
14
+ after(async () => { await knex.destroy() })
15
+ beforeEach(async () => {
16
+ await cleanTables(knex, ['temporal_events', 'temporal_people'])
17
+ ids = []
18
+ for (let index = 0; index < 8; index++) {
19
+ const result = await api.resources.events.post({ inputRecord: createJsonApiDocument('events', {
20
+ name: `Event ${index}`, occurredAt: `2026-09-01T10:20:3${index}.000Z`
21
+ }), simplified: false })
22
+ ids.push(result.data.id)
23
+ }
24
+ })
25
+
26
+ it('rejects zero, negative, fractional and conflicting page parameters', async () => {
27
+ for (const page of [
28
+ { size: 0 }, { size: -1 }, { size: 0.5 }, { number: 0 }, { number: -1 }, { number: 1.5 },
29
+ { after: '' }, { after: 'id:1', before: 'id:8' }, { number: 1, after: 'id:1' }
30
+ ]) {
31
+ await assert.rejects(api.resources.events.query({ queryParams: { page }, simplified: false }), {
32
+ code: 'REST_API_VALIDATION'
33
+ }, JSON.stringify(page))
34
+ }
35
+ })
36
+
37
+ it('returns the adjacent page before a cursor rather than restarting at the beginning', async () => {
38
+ const result = await api.resources.events.query({ queryParams: {
39
+ sort: ['id'], page: { size: 2, before: `id:${ids[6]}` }
40
+ }, simplified: false })
41
+ assert.deepEqual(result.data.map(entry => entry.id), ids.slice(4, 6))
42
+ assert.equal(result.meta.pagination.hasMore, true)
43
+ const next = await api.resources.events.query({ queryParams: {
44
+ sort: ['id'], page: { size: 2, before: result.meta.pagination.cursor.next }
45
+ }, simplified: false })
46
+ assert.deepEqual(next.data.map(entry => entry.id), ids.slice(2, 4))
47
+ assert.equal(new URL(result.links.next, 'https://api.test').searchParams.get('page[before]'), result.meta.pagination.cursor.next)
48
+ })
49
+
50
+ it('caps default limits even without explicit page parameters', async () => {
51
+ const original = api.resources.events.vars.queryDefaultLimit
52
+ api.resources.events.vars.queryDefaultLimit = 20
53
+ try {
54
+ assert.equal((await api.resources.events.query({ simplified: false })).data.length, 3)
55
+ } finally {
56
+ api.resources.events.vars.queryDefaultLimit = original
57
+ }
58
+ })
59
+
60
+ it('distinguishes null values from literal strings in cursors and rejects duplicate fields', () => {
61
+ for (const value of [null, '~null', 'null', '', 'colon:comma,']) {
62
+ const cursor = createCursor({ id: 'opaque:id', name: value }, ['name', 'id'])
63
+ assert.equal(parseCursor(cursor).name, value)
64
+ assert.equal(parseCursor(cursor).id, 'opaque:id')
65
+ }
66
+ assert.throws(() => parseCursor('id:1,id:2'), /Duplicate/)
67
+ })
68
+
69
+ it('generates usable cursors when a sort field is repeated', async () => {
70
+ const sort = ['name', 'name', 'id', 'id']
71
+ const first = await api.resources.events.query({ queryParams: { sort, page: { size: 2 } } })
72
+ const second = await api.resources.events.query({ queryParams: {
73
+ sort, page: { size: 2, after: first.meta.pagination.cursor.next }
74
+ } })
75
+ assert.deepEqual(second.data.map(entry => entry.id), ids.slice(2, 4))
76
+ })
77
+
78
+ it('validates schema sorts without an explicit allowlist, alongside query projections', async () => {
79
+ const original = api.resources.events.vars.sortableFields
80
+ api.resources.events.vars.sortableFields = []
81
+ try {
82
+ for (const field of ['name', 'occurredAt', 'projectedAt']) {
83
+ const result = await api.resources.events.query({ queryParams: { sort: [field], page: { size: 2 } } })
84
+ assert.deepEqual(result.data.map(entry => entry.id), ids.slice(0, 2))
85
+ }
86
+ for (const field of ['missingField', 'constructor', 'producedAt']) {
87
+ await assert.rejects(api.resources.events.query({ queryParams: { sort: [field] } }), {
88
+ code: 'REST_API_VALIDATION'
89
+ })
90
+ }
91
+ await assert.rejects(api.resources.people.query({ queryParams: { sort: ['missingField'] } }), {
92
+ code: 'REST_API_VALIDATION'
93
+ })
94
+ } finally {
95
+ api.resources.events.vars.sortableFields = original
96
+ }
97
+ })
98
+
99
+ it('generates valid last-page links for an empty collection', async () => {
100
+ await cleanTables(knex, ['temporal_events', 'temporal_people'])
101
+ const original = api.resources.events.vars.enablePaginationCounts
102
+ api.resources.events.vars.enablePaginationCounts = true
103
+ try {
104
+ const result = await api.resources.events.query({ queryParams: { page: { number: 1, size: 2 } } })
105
+ const last = new URL(result.links.last, 'https://api.test')
106
+ const finalPage = await api.resources.events.query({ queryParams: {
107
+ page: { number: last.searchParams.get('page[number]'), size: last.searchParams.get('page[size]') }
108
+ } })
109
+ assert.deepEqual(finalPage.data, [])
110
+ } finally {
111
+ api.resources.events.vars.enablePaginationCounts = original
112
+ }
113
+ })
114
+
115
+ for (const sort of [['occurredAt'], ['-occurredAt']]) {
116
+ it(`traverses null sort values exactly once in both directions with sort=${sort}`, async () => {
117
+ for (const id of [ids[1], ids[4], ids[6]]) {
118
+ await api.resources.events.patch({ id, inputRecord: { data: {
119
+ type: 'events', id, attributes: { occurredAt: null }
120
+ } }, simplified: false })
121
+ }
122
+ const seen = []
123
+ let after
124
+ const pages = []
125
+ for (let index = 0; index < 6; index++) {
126
+ const page = await api.resources.events.query({ queryParams: {
127
+ sort, page: { size: 2, ...(after ? { after } : {}) }
128
+ }, simplified: false })
129
+ pages.push(page)
130
+ seen.push(...page.data.map(entry => entry.id))
131
+ after = page.meta.pagination.cursor?.next
132
+ if (!after) break
133
+ }
134
+ assert.equal(after, undefined)
135
+ assert.equal(seen.length, ids.length)
136
+ assert.equal(new Set(seen).size, ids.length)
137
+ const nonNull = ids.filter(id => ![ids[1], ids[4], ids[6]].includes(id))
138
+ if (sort[0].startsWith('-')) nonNull.reverse()
139
+ assert.deepEqual(seen.slice(0, nonNull.length), nonNull)
140
+
141
+ const firstOfLast = pages.at(-1).data[0]
142
+ let before = createCursor({ id: firstOfLast.id, ...firstOfLast.attributes }, ['occurredAt', 'id'])
143
+ const reversed = [...pages.at(-1).data.map(entry => entry.id)]
144
+ for (let index = 0; index < 6; index++) {
145
+ const page = await api.resources.events.query({ queryParams: { sort, page: { size: 2, before } }, simplified: false })
146
+ reversed.unshift(...page.data.map(entry => entry.id))
147
+ before = page.meta.pagination.cursor?.next
148
+ if (!before) break
149
+ }
150
+ assert.equal(before, undefined)
151
+ assert.deepEqual(reversed, seen)
152
+ })
153
+ }
154
+ })
@@ -0,0 +1,122 @@
1
+ import { describe, it, before, after, beforeEach } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import knexLib from 'knex'
4
+ import { createCursorPaginationApi } from './fixtures/api-configs.js'
5
+ import { cleanTables, createJsonApiDocument } from './helpers/test-utils.js'
6
+ import { storageMode } from './helpers/storage-mode.js'
7
+
8
+ const knex = knexLib({
9
+ client: 'better-sqlite3',
10
+ connection: { filename: ':memory:' },
11
+ useNullAsDefault: true
12
+ })
13
+ const recordCount = 205
14
+ let api
15
+
16
+ describe('Knex pagination contract', { skip: storageMode.isAnyApi() }, () => {
17
+ before(async () => {
18
+ api = await createCursorPaginationApi(knex)
19
+ api.resources.products.vars.defaultSort = ['-createdAt']
20
+ })
21
+
22
+ after(async () => {
23
+ await knex.destroy()
24
+ })
25
+
26
+ beforeEach(async () => {
27
+ await cleanTables(knex, ['cursor_products'])
28
+ for (let index = 0; index < recordCount; index++) {
29
+ await api.resources.products.post({
30
+ inputRecord: createJsonApiDocument('products', {
31
+ name: `Product ${index}`,
32
+ category: 'Fixture',
33
+ brand: 'Fixture',
34
+ price: index,
35
+ sku: `PAGE-${index}`,
36
+ createdAt: new Date(Date.UTC(2026, 8, 1, 0, 0, Math.floor(index / 3))).toISOString()
37
+ }),
38
+ simplified: false
39
+ })
40
+ }
41
+ })
42
+
43
+ it('traverses every record once when sparse fields omit the default sort field', async () => {
44
+ const expected = await knex('cursor_products').orderBy('created_at', 'desc').orderBy('id', 'asc').pluck('id')
45
+ const ids = []
46
+ const cursors = new Set()
47
+ let cursor
48
+
49
+ for (let page = 0; page < 4; page++) {
50
+ const result = await api.resources.products.query({
51
+ queryParams: {
52
+ fields: { products: 'name' },
53
+ page: { size: 100, ...(cursor ? { after: cursor } : {}) }
54
+ },
55
+ simplified: false
56
+ })
57
+ for (const record of result.data) {
58
+ assert.deepEqual(Object.keys(record.attributes), ['name'])
59
+ ids.push(record.id)
60
+ }
61
+ cursor = result.meta.pagination.cursor?.next
62
+ assert.equal(result.meta.pagination.hasMore, Boolean(cursor))
63
+ if (!cursor) break
64
+ assert.equal(cursors.has(cursor), false, 'Each cursor must advance')
65
+ cursors.add(cursor)
66
+ assert.match(cursor, /createdAt:/)
67
+ }
68
+
69
+ assert.equal(cursor, undefined, 'Traversal must reach the end')
70
+ assert.deepEqual(ids, expected.map(String))
71
+ assert.equal(new Set(ids).size, recordCount)
72
+ })
73
+
74
+ for (const mode of ['cursor', 'offset']) {
75
+ it(`uses the capped size for ${mode} pages, metadata, and links`, async () => {
76
+ const expected = await knex('cursor_products').orderBy('id', 'asc').pluck('id')
77
+ const ids = []
78
+ let cursor
79
+
80
+ for (let page = 1; page <= 3; page++) {
81
+ const result = await api.resources.products.query({
82
+ queryParams: {
83
+ sort: ['id'],
84
+ page: {
85
+ size: 200,
86
+ ...(mode === 'offset' ? { number: page } : cursor ? { after: cursor } : {})
87
+ }
88
+ },
89
+ simplified: false
90
+ })
91
+ ids.push(...result.data.map(record => record.id))
92
+ assert.equal(result.data.length, page < 3 ? 100 : 5)
93
+ assert.equal(result.meta.pagination.pageSize, 100)
94
+ assert.equal(result.meta.pagination.hasMore, page < 3)
95
+ assert.equal(Boolean(result.links.next), page < 3)
96
+ if (result.links.next) {
97
+ assert.equal(new URL(result.links.next, 'https://api.example.com').searchParams.get('page[size]'), '100')
98
+ }
99
+ cursor = result.meta.pagination.cursor?.next
100
+ if (mode === 'cursor') assert.equal(Boolean(cursor), page < 3)
101
+ }
102
+
103
+ assert.deepEqual(ids, expected.map(String))
104
+ assert.equal(new Set(ids).size, recordCount)
105
+ })
106
+ }
107
+
108
+ it('rejects cursors missing any sort value in either direction', async () => {
109
+ for (const direction of ['after', 'before']) {
110
+ for (const cursor of ['id:1', 'createdAt:2026-09-01T00%3A00%3A00.000Z']) {
111
+ await assert.rejects(api.resources.products.query({
112
+ queryParams: { page: { size: 100, [direction]: cursor } },
113
+ simplified: false
114
+ }), (error) => {
115
+ assert.equal(error.code, 'REST_API_VALIDATION')
116
+ assert.match(error.message, /Cursor.*missing.*sort field/i)
117
+ return true
118
+ })
119
+ }
120
+ }
121
+ })
122
+ })
@@ -337,6 +337,10 @@ describe('Multi-field Cursor Pagination', () => {
337
337
  firstPage.data.map((record) => record.attributes.name),
338
338
  ['Newest Product', 'Recent Product']
339
339
  )
340
+ assert.deepEqual(
341
+ firstPage.data.map((record) => record.attributes.createdAt),
342
+ ['2026-05-03T10:00:00.000Z', '2026-05-03T09:00:00.000Z']
343
+ )
340
344
  assert.deepEqual(
341
345
  secondPage.data.map((record) => record.attributes.name),
342
346
  ['Older Product']
@@ -391,9 +395,7 @@ describe('Multi-field Cursor Pagination', () => {
391
395
  queryParams: {
392
396
  page: {
393
397
  size: 4,
394
- before: secondPage.meta.pagination.cursor?.next ||
395
- // If no next cursor, create one from the last record
396
- `category:${encodeURIComponent(secondPage.data[0].attributes.category)},name:${encodeURIComponent(secondPage.data[0].attributes.name)},id:${encodeURIComponent(secondPage.data[0].id)}`
398
+ before: `category:${encodeURIComponent(secondPage.data[0].attributes.category)},name:${encodeURIComponent(secondPage.data[0].attributes.name)},id:${encodeURIComponent(secondPage.data[0].id)}`
397
399
  },
398
400
  sort: ['category', 'name']
399
401
  },
@@ -0,0 +1,56 @@
1
+ import { after, before, beforeEach, describe, it } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import knexLib from 'knex'
4
+ import {
5
+ createRelationshipIncludeStorageAdapterApi,
6
+ seedRelationshipIncludeStorageAdapterApi
7
+ } from './fixtures/api-configs.js'
8
+ import { cleanTables } from './helpers/test-utils.js'
9
+
10
+ const knex = knexLib({
11
+ client: 'better-sqlite3',
12
+ connection: {
13
+ filename: ':memory:'
14
+ },
15
+ useNullAsDefault: true
16
+ })
17
+
18
+ describe('Relationship include storage adapters', () => {
19
+ let api
20
+
21
+ before(async () => {
22
+ api = await createRelationshipIncludeStorageAdapterApi(knex)
23
+ })
24
+
25
+ beforeEach(async () => {
26
+ await cleanTables(knex, [
27
+ 'uninitialized_bookings',
28
+ 'uninitialized_pets'
29
+ ])
30
+ await seedRelationshipIncludeStorageAdapterApi(knex)
31
+ })
32
+
33
+ after(async () => {
34
+ await knex.destroy()
35
+ })
36
+
37
+ it('maps sparse fields for an included scope whose adapter is not initialized', async () => {
38
+ assert.equal(api.resources.pets.vars.storageAdapter, undefined)
39
+
40
+ const result = await api.resources.bookings.get({
41
+ id: 41,
42
+ queryParams: {
43
+ include: ['pet'],
44
+ fields: {
45
+ bookings: 'reference,petId',
46
+ pets: 'firstName'
47
+ }
48
+ },
49
+ simplified: false
50
+ })
51
+
52
+ const includedPet = result.included.find(resource => resource.type === 'pets')
53
+ assert(includedPet)
54
+ assert.deepEqual(includedPet.attributes, { firstName: 'Coco' })
55
+ })
56
+ })