json-rest-api 1.0.28 → 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.
- package/docs/API.md +2 -0
- package/docs/GUIDE/GUIDE_2_7_Pagination_And_Ordering.md +9 -0
- package/docs/GUIDE/GUIDE_3_Field_Transformations.md +1 -1
- package/docs/GUIDE/GUIDE_Y_Appendices.md +17 -2
- package/package.json +1 -1
- package/plugins/core/file-handling-plugin.js +3 -0
- package/plugins/core/lib/querying/knex-pagination-helpers.js +19 -13
- package/plugins/core/lib/querying/query-field-sort-helpers.js +93 -15
- package/plugins/core/lib/querying/sort-helpers.js +8 -1
- package/plugins/core/lib/querying-writing/database-value-normalizers.js +74 -8
- package/plugins/core/lib/querying-writing/knex-field-helpers.js +15 -1
- package/plugins/core/lib/querying-writing/request-contracts.js +16 -6
- package/plugins/core/lib/storage/storage-adapter.js +15 -1
- package/plugins/core/rest-api-anyapi-knex-plugin.js +36 -60
- package/plugins/core/rest-api-knex-plugin.js +28 -20
- package/plugins/core/rest-api-plugin-methods/common.js +11 -1
- package/plugins/core/rest-api-plugin-methods/enrich-attributes.js +3 -0
- package/plugins/core/rest-api-plugin-methods/get.js +2 -1
- package/plugins/core/rest-api-plugin-methods/query.js +2 -1
- package/tests/anyapi-cursor-pagination.test.js +1 -3
- package/tests/file-handling.test.js +37 -0
- package/tests/fixtures/api-configs.js +57 -0
- package/tests/pagination-boundaries.test.js +154 -0
- package/tests/pagination-contract.test.js +122 -0
- package/tests/pagination-cursor-multifield.test.js +1 -3
- package/tests/temporal-boundaries.test.js +208 -0
|
@@ -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
|
+
})
|
|
@@ -395,9 +395,7 @@ describe('Multi-field Cursor Pagination', () => {
|
|
|
395
395
|
queryParams: {
|
|
396
396
|
page: {
|
|
397
397
|
size: 4,
|
|
398
|
-
before: secondPage.
|
|
399
|
-
// If no next cursor, create one from the last record
|
|
400
|
-
`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)}`
|
|
401
399
|
},
|
|
402
400
|
sort: ['category', 'name']
|
|
403
401
|
},
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { after, before, beforeEach, describe, it } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { applyFieldSetters, handleRecordReturnAfterWrite } from '../plugins/core/rest-api-plugin-methods/common.js'
|
|
4
|
+
import knexLib from 'knex'
|
|
5
|
+
import { createTemporalBoundaryApi } from './fixtures/api-configs.js'
|
|
6
|
+
import { cleanTables, createJsonApiDocument } from './helpers/test-utils.js'
|
|
7
|
+
import { mapRestApiErrorToHttp } from '../plugins/core/connectors/lib/transport-http-helpers.js'
|
|
8
|
+
import { normalizeAttributes, normalizeRecordAttributes } from '../plugins/core/lib/querying-writing/database-value-normalizers.js'
|
|
9
|
+
import { storageMode } from './helpers/storage-mode.js'
|
|
10
|
+
import { RestApiTemporalDataError } from '../lib/rest-api-errors.js'
|
|
11
|
+
|
|
12
|
+
const knex = knexLib({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true })
|
|
13
|
+
let api
|
|
14
|
+
let finishValue
|
|
15
|
+
const document = (attributes = {}) => createJsonApiDocument('events', { name: 'Event', ...attributes })
|
|
16
|
+
const assertValidationError = (error) => {
|
|
17
|
+
assert.equal(error.code, 'REST_API_VALIDATION')
|
|
18
|
+
assert.equal(mapRestApiErrorToHttp(error).status, 422)
|
|
19
|
+
return true
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe('Temporal storage and response boundaries', () => {
|
|
23
|
+
before(async () => {
|
|
24
|
+
api = await createTemporalBoundaryApi(knex)
|
|
25
|
+
const handler = async ({ context }) => {
|
|
26
|
+
if (finishValue === undefined || context.scopeName !== 'events') return
|
|
27
|
+
const attributes = context.simplified ? context.responseRecord : context.responseRecord?.data?.attributes
|
|
28
|
+
if (attributes) attributes.producedAt = finishValue
|
|
29
|
+
if (context.simplified && attributes?.person) attributes.person.producedAt = finishValue
|
|
30
|
+
for (const included of context.responseRecord?.included || []) included.attributes.producedAt = finishValue
|
|
31
|
+
}
|
|
32
|
+
await api.customize({ hooks: {
|
|
33
|
+
finishPost: { functionName: 'temporal-finish-post', handler },
|
|
34
|
+
finishPut: { functionName: 'temporal-finish-put', handler },
|
|
35
|
+
finishPatch: { functionName: 'temporal-finish-patch', handler }
|
|
36
|
+
} })
|
|
37
|
+
})
|
|
38
|
+
after(async () => { await knex.destroy() })
|
|
39
|
+
beforeEach(async () => {
|
|
40
|
+
finishValue = undefined
|
|
41
|
+
await cleanTables(knex, ['temporal_events', 'temporal_people'])
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it('rejects submillisecond writes without inserting or changing data', async () => {
|
|
45
|
+
const precise = '2026-09-01T10:20:30.123456Z'
|
|
46
|
+
await assert.rejects(api.resources.events.post({ inputRecord: document({ occurredAt: precise }) }), assertValidationError)
|
|
47
|
+
assert.equal((await api.resources.events.query()).data.length, 0)
|
|
48
|
+
const created = await api.resources.events.post({ inputRecord: document({ occurredAt: '2026-09-01T10:20:30.123000Z' }) })
|
|
49
|
+
for (const method of ['put', 'patch']) {
|
|
50
|
+
const inputRecord = document({ occurredAt: precise })
|
|
51
|
+
inputRecord.data.id = created.data.id
|
|
52
|
+
await assert.rejects(api.resources.events[method]({ id: created.data.id, inputRecord }), assertValidationError)
|
|
53
|
+
const result = await api.resources.events.get({ id: created.data.id })
|
|
54
|
+
assert.equal(result.data.attributes.occurredAt, '2026-09-01T10:20:30.123Z')
|
|
55
|
+
}
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('retains submillisecond precision supplied by storage, including timezone offsets', () => {
|
|
59
|
+
for (const value of ['2026-09-01 10:20:30.123456', '2026-09-01T18:20:30.123456+08:00']) {
|
|
60
|
+
const result = normalizeAttributes({ occurredAt: value }, { occurredAt: { type: 'dateTime', temporalPrecision: 6 } })
|
|
61
|
+
assert.equal(result.occurredAt, '2026-09-01T10:20:30.123456Z')
|
|
62
|
+
}
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('normalizes numeric epoch values returned as strings or bigints by drivers', () => {
|
|
66
|
+
const schema = { milliseconds: { type: 'epochMilliseconds' }, seconds: { type: 'epochSeconds' } }
|
|
67
|
+
assert.deepEqual(normalizeAttributes({ milliseconds: '1788258030123', seconds: 1788258030n }, schema), {
|
|
68
|
+
milliseconds: 1788258030123, seconds: 1788258030
|
|
69
|
+
})
|
|
70
|
+
for (const value of ['bad', '8640000000000001', 1.25]) {
|
|
71
|
+
assert.throws(() => normalizeAttributes({ milliseconds: value }, schema), { code: 'REST_API_TEMPORAL_DATA_INVALID' })
|
|
72
|
+
}
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('normalizes temporal query projections and follows their cursors', async () => {
|
|
76
|
+
for (let index = 0; index < 4; index++) {
|
|
77
|
+
await api.resources.events.post({ inputRecord: document({ occurredAt: `2026-09-01T10:20:3${index}.123Z` }) })
|
|
78
|
+
}
|
|
79
|
+
const queryParams = { sort: ['projectedAt'], fields: { events: 'projectedAt' }, page: { size: 2 } }
|
|
80
|
+
const first = await api.resources.events.query({ queryParams })
|
|
81
|
+
assert.equal(first.data[0].attributes.projectedAt, '2026-09-01T10:20:30.123Z')
|
|
82
|
+
const second = await api.resources.events.query({ queryParams: {
|
|
83
|
+
...queryParams, page: { size: 2, after: first.meta.pagination.cursor.next }
|
|
84
|
+
} })
|
|
85
|
+
assert.equal(second.data[0].attributes.projectedAt, '2026-09-01T10:20:32.123Z')
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it('uses a custom serializer consistently for writes and filters', { skip: storageMode.isAnyApi() }, async () => {
|
|
89
|
+
const value = '2026-09-01T10:20:30.123456Z'
|
|
90
|
+
const created = await api.resources.events.post({ inputRecord: document({ serializedAt: value }) })
|
|
91
|
+
assert.equal(created.data.attributes.serializedAt, value)
|
|
92
|
+
const filtered = await api.resources.events.query({ queryParams: { filters: { serializedAt: value } } })
|
|
93
|
+
assert.deepEqual(filtered.data.map(entry => entry.id), [created.data.id])
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
it('validates included fieldsets even when the relationship or collection is empty', async () => {
|
|
97
|
+
const queryParams = { include: ['person'], fields: { people: 'missingField' } }
|
|
98
|
+
await assert.rejects(api.resources.events.query({ queryParams }), { code: 'REST_API_FIELDSET_INVALID' })
|
|
99
|
+
const created = await api.resources.events.post({ inputRecord: document() })
|
|
100
|
+
await assert.rejects(api.resources.events.get({ id: created.data.id, queryParams }), { code: 'REST_API_FIELDSET_INVALID' })
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
it('rejects inherited object names as unknown sparse fields', async () => {
|
|
104
|
+
for (const field of ['constructor', 'toString', '__proto__']) {
|
|
105
|
+
await assert.rejects(api.resources.events.query({ queryParams: { fields: { events: field } } }), {
|
|
106
|
+
code: 'REST_API_FIELDSET_INVALID'
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
it('normalizes nested simplified to-many and polymorphic resources without changing ordinary objects', () => {
|
|
112
|
+
const date = new Date('2026-09-08T11:22:33.987Z')
|
|
113
|
+
const child = { id: 'child', producedAt: date }
|
|
114
|
+
const payload = { id: 'event', person: { id: 'person', events: [child, child] },
|
|
115
|
+
subject: { id: 'person', _type: 'people', producedAt: date },
|
|
116
|
+
arbitrary: { producedAt: date, value: 'unchanged' } }
|
|
117
|
+
const result = normalizeRecordAttributes(payload, api.resources, { simplified: true, resourceType: 'events', source: 'response' })
|
|
118
|
+
assert.equal(result.person.events[0].producedAt, '2026-09-08T11:22:33Z')
|
|
119
|
+
assert.equal(result.person.events[0], result.person.events[1])
|
|
120
|
+
assert.equal(result.subject.producedAt, '2026-09-08T11:22:33Z')
|
|
121
|
+
assert.equal(result.subject._type, 'people')
|
|
122
|
+
assert.equal(result.arbitrary, payload.arbitrary)
|
|
123
|
+
assert.equal(child.producedAt, date)
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
it('preserves typed API errors thrown by computed fields', async () => {
|
|
127
|
+
const created = await api.resources.events.post({ inputRecord: document() })
|
|
128
|
+
const definition = api.resources.events.vars.schemaInfo.computed.producedAt
|
|
129
|
+
const original = definition.compute
|
|
130
|
+
const error = new RestApiTemporalDataError({ field: 'producedAt', resourceType: 'events', fieldType: 'dateTime', source: 'response' })
|
|
131
|
+
definition.compute = () => { throw error }
|
|
132
|
+
try {
|
|
133
|
+
await assert.rejects(api.resources.events.get({ id: created.data.id }), actual => actual === error)
|
|
134
|
+
} finally {
|
|
135
|
+
definition.compute = original
|
|
136
|
+
}
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it('preserves typed API errors thrown by getters', async () => {
|
|
140
|
+
const created = await api.resources.events.post({ inputRecord: document() })
|
|
141
|
+
const schemaInfo = api.resources.events.vars.schemaInfo
|
|
142
|
+
const originalGetters = schemaInfo.fieldGetters
|
|
143
|
+
const originalOrder = schemaInfo.sortedGetterFields
|
|
144
|
+
const error = new RestApiTemporalDataError({ field: 'name', resourceType: 'events', source: 'response' })
|
|
145
|
+
schemaInfo.fieldGetters = { name: { getter: () => { throw error } } }
|
|
146
|
+
schemaInfo.sortedGetterFields = ['name']
|
|
147
|
+
try {
|
|
148
|
+
await assert.rejects(api.resources.events.get({ id: created.data.id }), actual => actual === error)
|
|
149
|
+
} finally {
|
|
150
|
+
schemaInfo.fieldGetters = originalGetters
|
|
151
|
+
schemaInfo.sortedGetterFields = originalOrder
|
|
152
|
+
}
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
it('preserves typed errors from setters and post-write storage reads', async () => {
|
|
156
|
+
const error = new RestApiTemporalDataError({ field: 'occurredAt', resourceType: 'events' })
|
|
157
|
+
await assert.rejects(applyFieldSetters({ occurredAt: '2026-09-08T00:00:00Z' }, {
|
|
158
|
+
fieldSetters: { occurredAt: { setter: () => { throw error } } },
|
|
159
|
+
sortedSetterFields: ['occurredAt']
|
|
160
|
+
}, { scopeName: 'events' }), actual => actual === error)
|
|
161
|
+
await assert.rejects(handleRecordReturnAfterWrite({
|
|
162
|
+
context: { method: 'POST' }, scopeName: 'events',
|
|
163
|
+
helpers: { dataGetMinimal: async () => { throw error } },
|
|
164
|
+
log: { warn () {} }
|
|
165
|
+
}), actual => actual === error)
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
for (const direction of ['after', 'before']) {
|
|
169
|
+
it(`rejects malformed temporal and numeric values in page[${direction}] as client errors`, async () => {
|
|
170
|
+
for (const [field, value] of [['occurredAt', 'garbage'], ['day', '2026-02-30'], ['atTime', '25:30'], ['observedAtMs', 'NaN']]) {
|
|
171
|
+
await assert.rejects(api.resources.events.query({ queryParams: {
|
|
172
|
+
sort: [field], page: { size: 2, [direction]: `${field}:${encodeURIComponent(value)},id:1` }
|
|
173
|
+
} }), (error) => {
|
|
174
|
+
assertValidationError(error)
|
|
175
|
+
assert.deepEqual(error.details.fields, [`page.${direction}`])
|
|
176
|
+
return true
|
|
177
|
+
})
|
|
178
|
+
}
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
for (const simplified of [false, true]) {
|
|
183
|
+
for (const method of ['post', 'put', 'patch']) {
|
|
184
|
+
it(`normalizes ${method} finish values and included resources with simplified=${simplified}`, async () => {
|
|
185
|
+
const person = await api.resources.people.post({ inputRecord: createJsonApiDocument('people', { name: 'Person' }) })
|
|
186
|
+
const inputRecord = document()
|
|
187
|
+
inputRecord.data.relationships = { person: { data: { type: 'people', id: person.data.id } } }
|
|
188
|
+
const created = method === 'post' ? null : await api.resources.events.post({ inputRecord })
|
|
189
|
+
if (created) inputRecord.data.id = created.data.id
|
|
190
|
+
finishValue = new Date('2026-09-08T11:22:33.987Z')
|
|
191
|
+
const result = await api.resources.events[method]({
|
|
192
|
+
...(created ? { id: created.data.id } : {}), inputRecord,
|
|
193
|
+
queryParams: { include: ['person'] }, simplified
|
|
194
|
+
})
|
|
195
|
+
assert.equal((simplified ? result : result.data.attributes).producedAt, '2026-09-08T11:22:33Z')
|
|
196
|
+
assert.equal((simplified ? result.person : result.included[0].attributes).producedAt, '2026-09-08T11:22:33Z')
|
|
197
|
+
})
|
|
198
|
+
}
|
|
199
|
+
it(`rejects invalid finish values with simplified=${simplified}`, async () => {
|
|
200
|
+
finishValue = 'not-a-date'
|
|
201
|
+
await assert.rejects(api.resources.events.post({ inputRecord: document(), simplified }), (error) => {
|
|
202
|
+
assert.equal(error.code, 'REST_API_TEMPORAL_DATA_INVALID')
|
|
203
|
+
assert.equal(mapRestApiErrorToHttp(error).status, 500)
|
|
204
|
+
return true
|
|
205
|
+
})
|
|
206
|
+
})
|
|
207
|
+
}
|
|
208
|
+
})
|