json-rest-api 1.0.29 → 2.0.0

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 (292) hide show
  1. package/LICENSE +10 -670
  2. package/LICENSE-GPL-3.0 +674 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +39 -30
  5. package/docs/API.md +744 -1273
  6. package/docs/GUIDE/01-getting-started.md +338 -0
  7. package/docs/GUIDE/02-resources-and-relationships.md +33 -0
  8. package/docs/GUIDE/03-running-example.md +87 -0
  9. package/docs/GUIDE/04-creating-and-querying.md +181 -0
  10. package/docs/GUIDE/05-belongs-to.md +177 -0
  11. package/docs/GUIDE/06-has-many.md +184 -0
  12. package/docs/GUIDE/07-polymorphic-relationships.md +191 -0
  13. package/docs/GUIDE/08-many-to-many.md +184 -0
  14. package/docs/GUIDE/09-pagination-and-sorting.md +149 -0
  15. package/docs/GUIDE/10-put-and-patch.md +174 -0
  16. package/docs/GUIDE/11-relationship-endpoints.md +174 -0
  17. package/docs/GUIDE/12-field-transformations.md +287 -0
  18. package/docs/GUIDE/13-hooks-and-lifecycle.md +479 -0
  19. package/docs/GUIDE/14-custom-resource-methods.md +125 -0
  20. package/docs/GUIDE/15-query-projections.md +266 -0
  21. package/docs/GUIDE/{GUIDE_X_Autofiltering.md → 16-autofiltering.md} +77 -15
  22. package/docs/GUIDE/{GUIDE_X_Row_Policies.md → 17-row-policies.md} +137 -44
  23. package/docs/GUIDE/18-labels.md +86 -0
  24. package/docs/GUIDE/19-managed-transactions.md +179 -0
  25. package/docs/GUIDE/20-transaction-outcomes.md +207 -0
  26. package/docs/GUIDE/21-schema-and-migrations.md +634 -0
  27. package/docs/GUIDE/22-version-field-migrations.md +208 -0
  28. package/docs/GUIDE/23-fastify.md +179 -0
  29. package/docs/GUIDE/24-cors.md +172 -0
  30. package/docs/GUIDE/{GUIDE_X_URL_Management.md → 25-url-management.md} +7 -1
  31. package/docs/GUIDE/26-file-uploads.md +278 -0
  32. package/docs/GUIDE/27-bulk-operations.md +277 -0
  33. package/docs/GUIDE/28-socketio.md +325 -0
  34. package/docs/GUIDE/29-writing-plugins.md +278 -0
  35. package/docs/GUIDE/30-backend-capabilities.md +100 -0
  36. package/docs/GUIDE/31-positioning.md +181 -0
  37. package/docs/GUIDE/{GUIDE_Y_Appendices.md → 32-date-and-time.md} +74 -30
  38. package/docs/GUIDE/33-migrating-to-v2.md +3827 -0
  39. package/docs/GUIDE/index.md +51 -59
  40. package/docs/QUICKSTART.md +120 -287
  41. package/docs/architecture.md +75 -0
  42. package/docs/contributing.md +178 -0
  43. package/index.d.ts +36 -0
  44. package/index.js +1 -22
  45. package/lib/enhanced-logger.js +91 -85
  46. package/lib/error-context.js +445 -5
  47. package/lib/error-formatter.js +219 -59
  48. package/lib/knex-transaction.js +64 -0
  49. package/lib/logger-types.d.ts +22 -0
  50. package/lib/missing-package.js +4 -0
  51. package/lib/rest-api-errors.js +103 -8
  52. package/lib/runtime/json-rest-api.js +172 -0
  53. package/lib/transaction-types.d.ts +59 -0
  54. package/package.json +97 -27
  55. package/plugins/core/bulk-operations-plugin.js +191 -184
  56. package/plugins/core/connectors/express-plugin.js +148 -219
  57. package/plugins/core/connectors/fastify-plugin.js +125 -82
  58. package/plugins/core/connectors/lib/busboy-detector.js +74 -156
  59. package/plugins/core/connectors/lib/connector-core.js +144 -20
  60. package/plugins/core/connectors/lib/formidable-detector.js +63 -120
  61. package/plugins/core/connectors/lib/http-validators.js +77 -0
  62. package/plugins/core/connectors/lib/multipart-helpers.js +18 -0
  63. package/plugins/core/connectors/lib/request-helpers.js +10 -1
  64. package/plugins/core/connectors/lib/transport-http-helpers.js +89 -8
  65. package/plugins/core/connectors/lib/transport-route-schemas.js +7 -4
  66. package/plugins/core/file-handling-plugin.js +87 -177
  67. package/plugins/core/lib/anyapi/anyapi-registry.js +213 -164
  68. package/plugins/core/lib/anyapi/canonical-link-store.js +507 -0
  69. package/plugins/core/lib/anyapi/canonical-relationship-reader.js +598 -0
  70. package/plugins/core/lib/anyapi/schema-utils.js +25 -16
  71. package/plugins/core/lib/anyapi/utils/descriptor-helpers.js +0 -64
  72. package/plugins/core/lib/dbIntrospection.js +228 -21
  73. package/plugins/core/lib/dbTablesOperations.js +409 -92
  74. package/plugins/core/lib/fractional-positioning.js +12 -48
  75. package/plugins/core/lib/querying/identifier-query.js +19 -0
  76. package/plugins/core/lib/querying/include-query-helpers.js +364 -0
  77. package/plugins/core/lib/querying/include-to-many.js +428 -0
  78. package/plugins/core/lib/querying/include-to-one.js +579 -0
  79. package/plugins/core/lib/querying/knex-cross-table-search.js +31 -307
  80. package/plugins/core/lib/querying/knex-json-api-transformers-querying.js +99 -401
  81. package/plugins/core/lib/querying/knex-pagination-helpers.js +48 -317
  82. package/plugins/core/lib/querying/knex-process-includes.js +5 -110
  83. package/plugins/core/lib/querying/knex-query-helpers-base.js +21 -56
  84. package/plugins/core/lib/querying/knex-query-helpers.js +298 -448
  85. package/plugins/core/lib/querying/knex-relationship-includes.js +120 -2138
  86. package/plugins/core/lib/querying/knex-window-queries.js +62 -253
  87. package/plugins/core/lib/querying/query-builder-utils.js +44 -4
  88. package/plugins/core/lib/querying/query-constraint.d.ts +12 -0
  89. package/plugins/core/lib/querying/query-constraint.js +27 -0
  90. package/plugins/core/lib/querying/query-field-sort-helpers.js +134 -37
  91. package/plugins/core/lib/querying/relationship-identifiers.js +208 -0
  92. package/plugins/core/lib/querying/sort-helpers.js +13 -1
  93. package/plugins/core/lib/querying/storage-adapter-utils.js +13 -5
  94. package/plugins/core/lib/querying/url-helpers.js +11 -4
  95. package/plugins/core/lib/querying-writing/compile-schemas.js +148 -249
  96. package/plugins/core/lib/querying-writing/connectors-query-parser.js +33 -118
  97. package/plugins/core/lib/querying-writing/database-capabilities.js +149 -223
  98. package/plugins/core/lib/querying-writing/database-value-normalizers.js +179 -194
  99. package/plugins/core/lib/querying-writing/default-data-helpers.js +15 -45
  100. package/plugins/core/lib/querying-writing/field-selection-types.d.ts +43 -0
  101. package/plugins/core/lib/querying-writing/field-utils.js +113 -92
  102. package/plugins/core/lib/querying-writing/knex-constants.d.ts +18 -0
  103. package/plugins/core/lib/querying-writing/knex-constants.js +2 -26
  104. package/plugins/core/lib/querying-writing/knex-field-helpers.js +100 -290
  105. package/plugins/core/lib/querying-writing/knex-json-api-transformers.js +31 -120
  106. package/plugins/core/lib/querying-writing/query-field-helpers.js +108 -32
  107. package/plugins/core/lib/querying-writing/query-field-types.d.ts +60 -0
  108. package/plugins/core/lib/querying-writing/relationship-contracts.js +33 -13
  109. package/plugins/core/lib/querying-writing/request-contracts.js +93 -38
  110. package/plugins/core/lib/querying-writing/resource-id-normalization.js +23 -5
  111. package/plugins/core/lib/querying-writing/response-options.js +35 -0
  112. package/plugins/core/lib/querying-writing/schema-helpers.js +203 -324
  113. package/plugins/core/lib/querying-writing/scope-validations.js +92 -290
  114. package/plugins/core/lib/querying-writing/simplified-helpers.js +113 -712
  115. package/plugins/core/lib/storage/canonical-data-helpers.js +683 -0
  116. package/plugins/core/lib/storage/canonical-storage-mapping.js +51 -20
  117. package/plugins/core/lib/storage/ordinary-data-helpers.js +710 -0
  118. package/plugins/core/lib/storage/storage-adapter.js +128 -62
  119. package/plugins/core/lib/storage/storage-mapping.js +78 -28
  120. package/plugins/core/lib/storage/storage-types.d.ts +502 -0
  121. package/plugins/core/lib/writing/many-to-many-manipulations.js +114 -284
  122. package/plugins/core/lib/writing/relationship-processor.js +94 -158
  123. package/plugins/core/lib/writing/resource-version.js +172 -0
  124. package/plugins/core/lib/writing/reverse-relationship-manipulations.js +110 -0
  125. package/plugins/core/rest-api-anyapi-knex-plugin.js +116 -2485
  126. package/plugins/core/rest-api-autofilter-plugin.js +17 -19
  127. package/plugins/core/rest-api-cors-plugin.js +52 -205
  128. package/plugins/core/rest-api-knex-plugin.js +45 -1077
  129. package/plugins/core/rest-api-label-plugin.js +25 -38
  130. package/plugins/core/rest-api-plugin-hooks/register-relationship-routes.js +5 -5
  131. package/plugins/core/rest-api-plugin-hooks/register-scope-routes.js +9 -6
  132. package/plugins/core/rest-api-plugin-hooks/turn-scope-init-into-vars.js +7 -26
  133. package/plugins/core/rest-api-plugin-hooks/validate-include-configurations.js +20 -26
  134. package/plugins/core/rest-api-plugin-methods/add-route.js +4 -6
  135. package/plugins/core/rest-api-plugin-methods/apply-query-filters.js +42 -13
  136. package/plugins/core/rest-api-plugin-methods/check-permissions.js +11 -5
  137. package/plugins/core/rest-api-plugin-methods/common.js +291 -395
  138. package/plugins/core/rest-api-plugin-methods/delete-relationship.js +49 -47
  139. package/plugins/core/rest-api-plugin-methods/delete.js +31 -25
  140. package/plugins/core/rest-api-plugin-methods/enrich-attributes.js +108 -148
  141. package/plugins/core/rest-api-plugin-methods/get-related.js +113 -305
  142. package/plugins/core/rest-api-plugin-methods/get-relationship.js +25 -18
  143. package/plugins/core/rest-api-plugin-methods/get.js +36 -68
  144. package/plugins/core/rest-api-plugin-methods/lifecycle-types.d.ts +225 -0
  145. package/plugins/core/rest-api-plugin-methods/patch-relationship.js +28 -25
  146. package/plugins/core/rest-api-plugin-methods/patch.js +46 -99
  147. package/plugins/core/rest-api-plugin-methods/post-relationship.js +49 -53
  148. package/plugins/core/rest-api-plugin-methods/post.js +51 -51
  149. package/plugins/core/rest-api-plugin-methods/put.js +69 -148
  150. package/plugins/core/rest-api-plugin-methods/query.js +37 -81
  151. package/plugins/core/rest-api-plugin-methods/release.js +2 -1
  152. package/plugins/core/rest-api-plugin.js +32 -46
  153. package/plugins/core/rest-api-positioning-plugin.js +183 -628
  154. package/plugins/core/rest-api-query-projections-plugin.js +19 -102
  155. package/plugins/core/rest-api-row-policy-plugin.js +3 -3
  156. package/plugins/core/socketio-plugin.js +364 -344
  157. package/plugins/storage/local-storage.js +40 -36
  158. package/types/autofilter.d.ts +57 -0
  159. package/types/bulk-methods.d.ts +63 -0
  160. package/types/errors.d.ts +118 -0
  161. package/types/fastify-options.d.ts +19 -0
  162. package/types/file-detectors.d.ts +33 -0
  163. package/types/file-storage.d.ts +48 -0
  164. package/types/hook-context.d.ts +180 -0
  165. package/types/plugin-options.d.ts +53 -0
  166. package/types/relationship-methods.d.ts +74 -0
  167. package/types/representations.d.ts +50 -0
  168. package/types/resource-methods.d.ts +95 -0
  169. package/types/resource-schema.d.ts +157 -0
  170. package/types/row-policy.d.ts +31 -0
  171. package/types/runtime.d.ts +132 -0
  172. package/types/transactions.d.ts +21 -0
  173. package/.claude/agents/library-guide-expert.md +0 -30
  174. package/.claude/agents/rest-api-internals-expert.md +0 -54
  175. package/.claude/settings.local.json +0 -70
  176. package/AGENTS.md +0 -34
  177. package/CLAUDE.md +0 -160
  178. package/CRUSH.md +0 -55
  179. package/JSKIT_BACKEND_MIGRATION_TRACKER.txt +0 -180
  180. package/SINGLE_VALIDATION_CONTRACT_TODO.txt +0 -172
  181. package/TODO.todo +0 -13
  182. package/connectors_ideas/fastify.js +0 -217
  183. package/connectors_ideas/koa-plugin.js +0 -112
  184. package/docs/.bundle/config +0 -2
  185. package/docs/COMPARISON.md +0 -433
  186. package/docs/GUIDE/GUIDE_1_Initial_Setup.md +0 -1057
  187. package/docs/GUIDE/GUIDE_2_1_The_Starting_Point.md +0 -88
  188. package/docs/GUIDE/GUIDE_2_2_Manipulating_And_Searching_Tables.md +0 -808
  189. package/docs/GUIDE/GUIDE_2_3_BelongsTo_Relationships.md +0 -491
  190. package/docs/GUIDE/GUIDE_2_4_HasMany_Records.md +0 -398
  191. package/docs/GUIDE/GUIDE_2_5_HasMany_Polymorphic.md +0 -898
  192. package/docs/GUIDE/GUIDE_2_6_Many_To_Many.md +0 -712
  193. package/docs/GUIDE/GUIDE_2_7_Pagination_And_Ordering.md +0 -1247
  194. package/docs/GUIDE/GUIDE_2_8_Effects_of_PUT_and_PATCH.md +0 -748
  195. package/docs/GUIDE/GUIDE_2_9_Relationships_Urls.md +0 -517
  196. package/docs/GUIDE/GUIDE_2_Data_And_Relations.md +0 -66
  197. package/docs/GUIDE/GUIDE_3_Field_Transformations.md +0 -1252
  198. package/docs/GUIDE/GUIDE_5_Non-Db_Resources.md +0 -1107
  199. package/docs/GUIDE/GUIDE_6_Positioning.md +0 -692
  200. package/docs/GUIDE/GUIDE_7_Hooks_Data_Management_And_Plugins.md +0 -1491
  201. package/docs/GUIDE/GUIDE_X_Bulk_Operations.md +0 -732
  202. package/docs/GUIDE/GUIDE_X_Cors.md +0 -1957
  203. package/docs/GUIDE/GUIDE_X_Fastify.md +0 -78
  204. package/docs/GUIDE/GUIDE_X_File_Uploads.md +0 -729
  205. package/docs/GUIDE/GUIDE_X_Knex_Schema_And_Migrations.md +0 -370
  206. package/docs/GUIDE/GUIDE_X_Query_Projections.md +0 -159
  207. package/docs/GUIDE/GUIDE_X_SocketIO.md +0 -1040
  208. package/docs/GUIDE/GUIDE_X_Writing_Plugins.md +0 -201
  209. package/docs/Gemfile +0 -6
  210. package/docs/Gemfile.lock +0 -308
  211. package/docs/ONBOARDING.md +0 -315
  212. package/docs/_config.yml +0 -36
  213. package/docs/_layouts/default.html +0 -123
  214. package/docs/apple-touch-icon.svg +0 -4
  215. package/docs/assets/css/style.scss +0 -392
  216. package/docs/favicon.svg +0 -4
  217. package/docs/index.md +0 -164
  218. package/docs/mini-guides/file-uploads-complete.md +0 -161
  219. package/eslint.config.js +0 -13
  220. package/examples/url-override-example.js +0 -137
  221. package/fixing_plan.md +0 -112
  222. package/plugins/core/lib/anyapi/query/anyapi-query-adapter.js +0 -657
  223. package/plugins/core/lib/querying-writing/return-record-settings.js +0 -47
  224. package/plugins/core/lib/writing/knex-json-api-transformers-writing.js +0 -110
  225. package/plugins/storage/s3-storage.js +0 -93
  226. package/quickTest.js +0 -136
  227. package/scripts/debug-anyapi-review-filter.mjs +0 -63
  228. package/scripts/inspect-anyapi-descriptor-country.mjs +0 -19
  229. package/scripts/inspect-anyapi-descriptor.mjs +0 -19
  230. package/scripts/run-docs.js +0 -133
  231. package/test-debug.js +0 -59
  232. package/tests/README.md +0 -202
  233. package/tests/TEST_TEMPLATE.test.js +0 -178
  234. package/tests/anyapi-basic.test.js +0 -105
  235. package/tests/anyapi-cursor-pagination.test.js +0 -148
  236. package/tests/anyapi-custom-idproperty.test.js +0 -163
  237. package/tests/autofilter.test.js +0 -463
  238. package/tests/bulk-operations.test.js +0 -657
  239. package/tests/computed-fields.test.js +0 -586
  240. package/tests/cors.test.js +0 -834
  241. package/tests/curl.test.js +0 -467
  242. package/tests/custom-id-mysql-returning-fallback.test.js +0 -128
  243. package/tests/custom-id-simplified-post.test.js +0 -75
  244. package/tests/custom-idproperty-relationships.test.js +0 -932
  245. package/tests/db-introspection.test.js +0 -521
  246. package/tests/db-table-operations.test.js +0 -798
  247. package/tests/fastify-plugin.test.js +0 -184
  248. package/tests/field-getters.test.js +0 -370
  249. package/tests/field-setters.test.js +0 -306
  250. package/tests/file-handling.test.js +0 -155
  251. package/tests/fixtures/api-configs.js +0 -2566
  252. package/tests/full-jsonapi-belongsto-linkage.test.js +0 -150
  253. package/tests/helpers/fake-fastify.js +0 -99
  254. package/tests/helpers/storage-mode.js +0 -65
  255. package/tests/helpers/test-utils.js +0 -203
  256. package/tests/http-connectors-parity.test.js +0 -395
  257. package/tests/id-normalization.test.js +0 -444
  258. package/tests/include-depth-validation.test.js +0 -331
  259. package/tests/includes.test.js +0 -427
  260. package/tests/local-storage.test.js +0 -96
  261. package/tests/logical-id-write-validation.test.js +0 -151
  262. package/tests/nested-includes.test.js +0 -617
  263. package/tests/pagination-boundaries.test.js +0 -154
  264. package/tests/pagination-contract.test.js +0 -122
  265. package/tests/pagination-cursor-multifield.test.js +0 -641
  266. package/tests/pagination-enhanced.test.js +0 -563
  267. package/tests/polymorphic-relationships.test.js +0 -347
  268. package/tests/polymorphic-simple.test.js +0 -148
  269. package/tests/positioning-advanced.test.js +0 -692
  270. package/tests/positioning-extended.test.js +0 -915
  271. package/tests/positioning-multifilter.test.js +0 -699
  272. package/tests/positioning.test.js +0 -560
  273. package/tests/post-commit-hooks.test.js +0 -120
  274. package/tests/projected-fields.test.js +0 -319
  275. package/tests/public-exports.test.js +0 -15
  276. package/tests/put-create-parity.test.js +0 -216
  277. package/tests/queries.test.js +0 -521
  278. package/tests/query-limits.test.js +0 -584
  279. package/tests/relationship-endpoints.test.js +0 -620
  280. package/tests/relationship-include-storage-adapter.test.js +0 -56
  281. package/tests/relationships.test.js +0 -681
  282. package/tests/rest-api.test.js +0 -337
  283. package/tests/return-record-settings.test.js +0 -184
  284. package/tests/row-policy.test.js +0 -489
  285. package/tests/s3-storage.test.js +0 -38
  286. package/tests/searchschema-knex-behavior.test.js +0 -187
  287. package/tests/searchschema-merge.test.js +0 -151
  288. package/tests/socketio.test.js +0 -860
  289. package/tests/storage-mapping.test.js +0 -362
  290. package/tests/temporal-boundaries.test.js +0 -208
  291. package/tests/test-development-guide.md +0 -370
  292. package/tests/virtual-fields.test.js +0 -404
@@ -0,0 +1,100 @@
1
+ ---
2
+ title: "Backend capabilities and limits"
3
+ chapter: 30
4
+ chapter_label: "30"
5
+ ---
6
+
7
+ # 30. Backend capabilities and limits
8
+
9
+ This reference describes the v2 storage contracts. Follow the
10
+ [migration guide](33-migrating-to-v2.md) before upgrading an application.
11
+ Node 24 or later is required; verification runs on Node 24 only.
12
+
13
+ ## Database and storage choices
14
+
15
+ | Combination | Verification and limits |
16
+ | --- | --- |
17
+ | SQLite through `better-sqlite3` | Verified with SQLite 3.49.2. Ordering helpers require SQLite 3.30 or later. Concurrent writers can fail with busy/snapshot conflicts; the library does not make SQLite a multi-writer database. |
18
+ | PostgreSQL through `pg` | Verified on PostgreSQL 16. Native precision, constraints, transaction visibility and failure paths have dedicated checks. |
19
+ | MySQL through `mysql2` | Verified on MySQL 8. DDL can implicitly commit and is not treated as an atomic rollbackable migration. |
20
+ | MariaDB, MSSQL, Oracle and other Knex clients | Unverified, including dialects with branches in capability helpers. Those branches are not a support guarantee. |
21
+
22
+ The library does not ship a generic remote-service or NoSQL CRUD backend. See
23
+ [custom data sources](14-custom-resource-methods.md) for the distinction between
24
+ custom service methods and a complete storage integration.
25
+
26
+ The SQL matrix exercises ordinary resource tables and canonical AnyAPI storage.
27
+ Canonical storage uses shared tables with tenant/resource predicates and opaque
28
+ logical IDs; those IDs sort lexically. Ordinary numeric IDs sort numerically.
29
+ Neither storage choice changes the database's transaction or collation behavior.
30
+ Dedicated collation tests cover selected cases, not arbitrary database collations.
31
+ Other server versions and Windows remain unverified.
32
+
33
+ Per-parent include limits require window-function capability. Capability detection
34
+ does not establish support for every query on an otherwise unverified dialect.
35
+ See [contributing](../contributing.md#real-databases-and-redis) for native
36
+ database verification commands. A passing SQLite suite is not native PostgreSQL/MySQL
37
+ evidence, even when launched with a different storage-mode environment variable.
38
+
39
+ ## Temporal values
40
+
41
+ Public date/dateTime inputs are strings; time inputs remain strings too. Built-in
42
+ dateTime writes pass through JavaScript Date and support millisecond precision.
43
+ They reject nonzero submillisecond digits. Declaring precision 6 does not enable
44
+ microsecond writes through that conversion. Database string reads can retain
45
+ microseconds; library PostgreSQL/MySQL queries request temporal strings to avoid
46
+ loss through driver Date conversion. Caller-owned raw queries retain their own
47
+ driver parsing behavior.
48
+
49
+ Native PostgreSQL/MySQL time/dateTime columns accept declared precision 0–6.
50
+ New columns default to precision 6; existing columns require a reviewed migration.
51
+ MySQL native DATE/DATETIME writes reject years below 1000. Custom text mappings
52
+ and synchronous serializers can support different storage representations, but
53
+ must satisfy the chosen column, driver and read-normalization contracts.
54
+ See [temporal migration details](33-migrating-to-v2.md#temporal-values-and-storage-serializers)
55
+ for calendar ranges, UTC normalization, time formatting and old canonical slots.
56
+
57
+ ## Schema changes
58
+
59
+ Generated diffs describe the declared schema versus the live table; they are not
60
+ a migration-history engine. Review warnings and generated SQL. Unsupported
61
+ changes can be omitted with warnings, and destructive `down` migrations are not
62
+ generated automatically. SQLite check/enum changes can require a reviewed table
63
+ rebuild. Native SET fields require an explicit MySQL target.
64
+
65
+ AnyAPI field additions persist slot metadata; `alterKnexFields` is unsupported.
66
+ Re-registering populated resources cannot remove or remap stored fields. Preserve
67
+ slot maps and migrate stored data explicitly when changing layouts. Old canonical
68
+ temporal storage needs the documented data migration, not just a package update.
69
+ See [table helpers and migration limits](21-schema-and-migrations.md).
70
+
71
+ ## Transaction ownership and failures
72
+
73
+ Use `api.transaction` to group library writes and raw SQL. Its callback receives
74
+ a real Knex transaction, but the library owns completion and deferred hooks.
75
+ Pass that handle to each participating operation and await each call. Unmanaged
76
+ raw Knex transactions and child savepoints are rejected by library write methods.
77
+ Raw transactions remain usable for direct SQL, low-level helpers and read-only
78
+ API calls; each low-level schema/registry helper retains its documented contract.
79
+
80
+ A rejected write can already be committed. Inspect the recorded transaction
81
+ outcome; an unknown outcome requires reconciliation rather than blind replay or
82
+ upload deletion. The library does not automatically retry conflicts. See
83
+ [transactions and errors](33-migrating-to-v2.md#transactions-and-errors) for ownership,
84
+ completion-hook behavior and migration examples.
85
+
86
+ ## Files, notifications and known gaps
87
+
88
+ `LocalStorage` writes real files. Remote storage uses application-provided
89
+ adapters implementing `upload` and `delete`. File cleanup is best effort; failures remain in
90
+ diagnostic context for reconciliation. See [file storage and cleanup](26-file-uploads.md).
91
+
92
+ Socket.IO has real WebSocket/polling and Redis integration checks. These are
93
+ resource invalidations, not a durable event log or exactly-once delivery system;
94
+ see the [Socket.IO contract](28-socketio.md).
95
+
96
+ [Positioning](31-positioning.md) uses transaction-owned coordinator rows and has
97
+ separate-connection insertion/move/rollback coverage on PostgreSQL and MySQL in
98
+ both storage modes. Writes to one positioned resource are serialized. SQLite
99
+ busy conflicts and stale PostgreSQL snapshots can still require an application
100
+ retry; column collation and offline imports remain application responsibilities.
@@ -0,0 +1,181 @@
1
+ ---
2
+ title: "Positioning"
3
+ chapter: 31
4
+ chapter_label: "31"
5
+ ---
6
+
7
+ # 31. Positioning
8
+
9
+ The positioning plugin assigns fractional string keys for custom ordering within
10
+ groups, such as sortable lists and drag-and-drop interfaces.
11
+
12
+ Position allocation is coordinated by the database and participates in the
13
+ resource operation's managed transaction. Separate-connection tests cover
14
+ concurrent inserts, moves, group changes, rollback and earlier transaction
15
+ snapshots on PostgreSQL and MySQL, in both ordinary and canonical storage.
16
+ SQLite reports a busy/snapshot conflict when another connection holds its write
17
+ lock; it does not silently allocate the same key.
18
+
19
+ ## Setup
20
+
21
+ Install `fractional-indexing` alongside the ordinary Knex dependencies. The plugin
22
+ is available through its package subpath, rather than the root exports:
23
+
24
+ ```javascript
25
+ import { JsonRestApi, RestApiPlugin, RestApiKnexPlugin } from 'json-rest-api'
26
+ import { PositioningPlugin } from 'json-rest-api/plugins/core/rest-api-positioning-plugin.js'
27
+
28
+ // knex is application-owned; use bytewise position-column/database collation.
29
+ const api = new JsonRestApi({ name: 'ordered-tasks' })
30
+ await api.use(RestApiPlugin)
31
+ await api.use(RestApiKnexPlugin, { knex })
32
+ await api.use(PositioningPlugin, { filters: ['status'], autoIndex: false })
33
+
34
+ await api.addResource('tasks', {
35
+ schema: {
36
+ title: { type: 'string', required: true },
37
+ status: { type: 'string', required: true, search: true },
38
+ position: { type: 'string', max: 255, maxLength: 255, search: true },
39
+ beforeId: { type: 'string', virtual: true }
40
+ }
41
+ })
42
+ await api.resources.tasks.createKnexTable()
43
+ ```
44
+
45
+ Declare the position field yourself. The plugin validates its presence; it does
46
+ not add the field or migrate an existing database. Install the plugin before
47
+ registering participating resources. Each resource not excluded by configuration
48
+ must also declare the grouping fields.
49
+
50
+ Validation uses the compiled schema after `schema:enrich`, so a setup hook may
51
+ supply the position field. Its final definition must be a string without a setter.
52
+
53
+ Installation creates the internal `json_rest_api_positioning_locks` table when
54
+ it is absent. It stores one coordinator row per physical resource, including
55
+ the tenant/resource identity for canonical storage. Provision that table during
56
+ deployment if the runtime database account cannot create tables:
57
+
58
+ ```javascript
59
+ await knex.schema.createTable('json_rest_api_positioning_locks', table => {
60
+ table.string('resource', 64).primary()
61
+ })
62
+ ```
63
+
64
+ The plugin then needs ordinary read/write access to the table. Keep the table
65
+ and its rows while applications are running; removing a live coordinator would
66
+ allow writers to use different locks.
67
+
68
+ ## Resource calls
69
+
70
+ ```javascript
71
+ const first = await api.resources.tasks.post({
72
+ data: { title: 'First task', status: 'todo' }
73
+ })
74
+ const last = await api.resources.tasks.post({
75
+ data: { title: 'Last task', status: 'todo', beforeId: null }
76
+ })
77
+ await api.resources.tasks.post({
78
+ data: { title: 'Middle task', status: 'todo', beforeId: last.id }
79
+ })
80
+ await api.resources.tasks.patch({
81
+ id: last.id,
82
+ data: { beforeId: first.id }
83
+ })
84
+ ```
85
+
86
+ `beforeId` identifies another item in the destination group. `null` means the end
87
+ of that group, and `'FIRST'` means its beginning. New records without `beforeId`
88
+ use `defaultPosition`. Updates within the same group retain their position when
89
+ `beforeId` is omitted; changing a grouping field allocates a position in the
90
+ destination group using `defaultPosition`. An explicit `beforeId` chooses a
91
+ different placement. PUT creates and replacements follow the same rules.
92
+
93
+ A self-targeted move within the same group keeps its position. Missing targets
94
+ and targets outside the destination group fall back to appending. Explicit
95
+ targets pass through the resource's normal GET visibility and permission checks;
96
+ a permission error rejects the write. Manual position values are ignored.
97
+
98
+ The plugin supplies position sorting when a query has no explicit sort. Position
99
+ keys are strings, not numbers. Use a bytewise collation for the stored position
100
+ column so ordinary queries display their intended order: PostgreSQL `C`, MySQL
101
+ `utf8mb4_bin`, or SQLite `BINARY`, for example. The allocator uses explicit binary
102
+ comparisons, but ordinary sorting and cursor predicates still use the column's
103
+ database collation. A case-insensitive collation can display or paginate the
104
+ wrong order. Do not substitute arbitrary integer strings for valid fractional keys.
105
+ Grouping separates ordering sequences; it does not provide authorization.
106
+ Use [row policies](17-row-policies.md) for mandatory visibility restrictions.
107
+
108
+ ## HTTP input
109
+
110
+ The connectors accept JSON:API documents. A request to move an existing task
111
+ uses `PATCH /api/tasks/42` with `Content-Type: application/vnd.api+json`:
112
+
113
+ ```json
114
+ {
115
+ "data": {
116
+ "type": "tasks",
117
+ "id": "42",
118
+ "attributes": { "beforeId": "17" }
119
+ }
120
+ }
121
+ ```
122
+
123
+ Plain records belong in programmatic `data` arguments; they are not the
124
+ HTTP document contract.
125
+
126
+ ## Configuration and limits
127
+
128
+ | Option | Default | Behavior |
129
+ | --- | --- | --- |
130
+ | `field` | `position` | Declared string field holding the ordering key |
131
+ | `filters` | `[]` | Fields defining independent position groups |
132
+ | `excludeResources` | `['system_migrations', 'system_logs']` | Resources exempt from positioning |
133
+ | `beforeIdField` | `beforeId` | Request attribute containing the placement target |
134
+ | `defaultPosition` | `last` | Default placement for new records; `first` is also supported |
135
+ | `strategy` | `fractional` | The implemented strategy; `integer` rejects |
136
+ | `autoIndex` | `true` | Attempts an ordinary-table index during resource registration |
137
+
138
+ Automatic index creation skips canonical storage and tables that do not yet
139
+ exist. Failures are logged rather than aborting setup. Manage required indexes
140
+ through reviewed [schema migrations](21-schema-and-migrations.md); do not assume
141
+ that enabling `autoIndex` created an index.
142
+
143
+ `api.positioning.getConfig()` returns the configuration, and
144
+ `api.positioning.isEnabled(resourceName)` reports whether a registered resource
145
+ participates. The old no-op `api.positioning.reorder()` helper has been removed;
146
+ use resource PATCH operations or [atomic bulk PATCH](27-bulk-operations.md).
147
+ The formerly inert `rebalanceThreshold` option now rejects.
148
+
149
+ There is no automatic rebalancing. Keys that exceed the tighter of the schema's
150
+ `max` and `maxLength` (default physical length: 255) reject before storage, so a
151
+ database cannot silently truncate a newly allocated key. The
152
+ `rebalancePositions()` utility calculates replacement keys in memory; it does
153
+ not persist them. `getUnpositionedItems()` and `assignInitialPositions()` support
154
+ offline data migrations, using actual fractional-key validation.
155
+
156
+ ## Concurrency and transaction boundaries
157
+
158
+ Positioned POST/PUT/PATCH operations lock one coordinator row before processing
159
+ the request. All position groups within that resource share the lock. This
160
+ deliberately serializes positioned writes to keep empty groups and moves between
161
+ groups safe without multiple group locks. The lock lasts until the owning
162
+ transaction commits or rolls back, including when the operation borrows an
163
+ `api.transaction()` handle. Keep those transactions short.
164
+
165
+ PostgreSQL and MySQL wait for the earlier writer and then allocate against
166
+ current rows. PostgreSQL repeatable-read transactions with an older snapshot
167
+ can reject with a serialization conflict; SQLite can reject with a busy/snapshot
168
+ conflict. Deadlocks, timeouts and connection failures remain ordinary transaction
169
+ failures. No hooks or external effects are replayed automatically. When an
170
+ application retries a failed move, it must start a fresh operation/transaction.
171
+
172
+ The coordination guarantee covers writers using this plugin against the same
173
+ database and lock table. Direct SQL imports, manual rebalancing and other writers
174
+ must not change positions concurrently. Do not add a setter to the managed
175
+ position field or change position/group fields after allocation. The plugin
176
+ retains normal resource permissions, validation and commit/rollback handling.
177
+
178
+ For existing data, plan a separate migration with valid keys, explicit ordering
179
+ and database-appropriate collation. Back up data and inspect the result before
180
+ enabling the plugin; registration does not convert existing positions or repair
181
+ duplicate keys. Existing groups must start with valid, distinct keys.
@@ -1,4 +1,10 @@
1
- # Appendices: Date and Time Handling
1
+ ---
2
+ title: "Date and time"
3
+ chapter: 32
4
+ chapter_label: "32"
5
+ ---
6
+
7
+ # 32. Date and time
2
8
 
3
9
  ## Overview
4
10
 
@@ -39,15 +45,25 @@ The API supports three string temporal types and two numeric epoch types in sche
39
45
 
40
46
  ## Schema Definition
41
47
 
42
- Define date/time fields in your schema like this:
48
+ The following three executable blocks form one scenario. Add them to the
49
+ [starting script](03-running-example.md) after installing storage and
50
+ before starting the server, on a fresh database. Other snippets are illustrative
51
+ payloads or configuration fragments.
43
52
 
44
53
  ```javascript
45
- const articleSchema = {
46
- publishedDate: { type: 'date', required: true },
47
- createdAt: { type: 'dateTime', temporalPrecision: 3, defaultTo: () => new Date().toISOString() },
48
- updatedAt: { type: 'dateTime', temporalPrecision: 3, defaultTo: () => new Date().toISOString() },
49
- dailyPostTime: { type: 'time', nullable: true }
50
- };
54
+ await api.addResource('articles', {
55
+ schema: {
56
+ title: { type: 'string', required: true },
57
+ publishedDate: { type: 'date', required: true, search: true },
58
+ createdAt: { type: 'dateTime', temporalPrecision: 3, required: true },
59
+ dailyPostTime: { type: 'time', nullable: true },
60
+ publishedEpoch: { type: 'epochMilliseconds', required: true }
61
+ },
62
+ searchSchema: {
63
+ createdBetween: { type: 'array', actualField: 'createdAt', filterOperator: 'between' }
64
+ }
65
+ })
66
+ await api.resources.articles.createKnexTable()
51
67
  ```
52
68
 
53
69
  `Date.prototype.toISOString()` always emits three fractional-second digits, so
@@ -63,19 +79,28 @@ than silently truncating it.
63
79
  The API validates and normalizes date/time inputs:
64
80
 
65
81
  ```javascript
66
- // POST /api/articles
67
- {
68
- "data": {
69
- "type": "articles",
70
- "attributes": {
71
- "publishedDate": "2024-01-15", // Valid date
72
- "createdAt": "2024-01-15T14:30:00Z", // Valid dateTime (ISO 8601)
73
- "dailyPostTime": "14:30:00" // Valid time
74
- }
82
+ const januaryArticle = await api.resources.articles.post({
83
+ data: {
84
+ title: 'January', publishedDate: '2024-01-15',
85
+ createdAt: '2024-01-15T22:30:00+08:00', dailyPostTime: '14:30:00',
86
+ publishedEpoch: '1705329000000'
75
87
  }
76
- }
88
+ })
89
+ await api.resources.articles.post({
90
+ data: {
91
+ title: 'February', publishedDate: '2024-02-01',
92
+ createdAt: '2024-02-01T00:00:00Z', dailyPostTime: null,
93
+ publishedEpoch: 1706745600000
94
+ }
95
+ })
96
+ console.log(januaryArticle)
77
97
  ```
78
98
 
99
+ The first result retains date `2024-01-15` and time `14:30:00`, normalizes
100
+ createdAt to `2024-01-15T14:30:00.000Z`, and returns publishedEpoch as the number
101
+ `1705329000000`. Its dateTime offset describes the same instant as UTC; callers
102
+ are not required to send only `Z` inputs.
103
+
79
104
  **Accepted Input Formats:**
80
105
  - **date**: a real calendar date in `YYYY-MM-DD` form
81
106
  - **dateTime**: an RFC 3339 string with seconds and an explicit timezone, such as `2024-01-15T14:30:00Z` or `2024-01-15T22:30:00+08:00`
@@ -106,7 +131,7 @@ epoch data.
106
131
 
107
132
  All date/time values are normalized when returned from the API:
108
133
 
109
- ```javascript
134
+ ```js
110
135
  // GET /api/articles/123
111
136
  {
112
137
  "data": {
@@ -131,7 +156,7 @@ All date/time values are normalized when returned from the API:
131
156
  Normalization runs once after the database read and again at the final response
132
157
  boundary. The final pass covers getters, computed fields, query projections,
133
158
  and finishing hooks that produce native `Date` values, including nested
134
- relationships in simplified write responses. A malformed non-null temporal value is not
159
+ relationships in plain write responses. A malformed non-null temporal value is not
135
160
  reported as `null`; it fails with `REST_API_TEMPORAL_DATA_INVALID` and HTTP 500
136
161
  so stored-data or enrichment defects remain visible.
137
162
 
@@ -150,7 +175,7 @@ so stored-data or enrichment defects remain visible.
150
175
  ## Best Practices
151
176
 
152
177
  ### 1. Always Store in UTC
153
- ```javascript
178
+ ```js
154
179
  // Good: Store timestamps in UTC
155
180
  const article = {
156
181
  createdAt: new Date().toISOString() // "2024-01-15T14:30:00.000Z"
@@ -168,21 +193,40 @@ const article = {
168
193
  - Use `time` for recurring daily events
169
194
 
170
195
  ### 3. Timezone Handling
171
- - Send all dateTime values to the API in UTC
196
+ - Send dateTime values with an explicit timezone; UTC is convenient, and valid offsets are accepted
172
197
  - The API always returns dateTime values in UTC (with 'Z' suffix)
173
198
  - Handle timezone conversion in your client application
174
199
 
175
200
  ### 4. Filtering and Querying
176
- When filtering by dates, use ISO 8601 format:
201
+
202
+ Declare public filter names in the schema or search schema, then use
203
+ `queryParams.filters` in programmatic calls. Temporal filter values use the
204
+ same declared field conversion as writes.
177
205
 
178
206
  ```javascript
179
- // Filter articles published after a date
180
- GET /api/articles?filters[publishedDate][$gte]=2024-01-01
207
+ const onDate = await api.resources.articles.query({
208
+ queryParams: { filters: { publishedDate: '2024-01-15' } }
209
+ })
210
+ const inJanuary = await api.resources.articles.query({
211
+ queryParams: {
212
+ filters: { createdBetween: ['2024-01-01T00:00:00Z', '2024-01-31T23:59:59.999Z'] }
213
+ }
214
+ })
215
+ console.log(onDate.data.map(article => article.title), inJanuary.data.map(article => article.title))
216
+ ```
217
+
218
+ Both queries return January only. `between` includes both boundaries. The
219
+ corresponding HTTP equality query uses the singular `filter` key:
181
220
 
182
- // Filter by datetime range
183
- GET /api/articles?filters[createdAt][$gte]=2024-01-01T00:00:00Z&filters[createdAt][$lt]=2024-02-01T00:00:00Z
221
+ ```http
222
+ GET /api/articles?filter[publishedDate]=2024-01-15
184
223
  ```
185
224
 
225
+ Use declared aliases such as `createdBetween`; arbitrary `$gte`/`$lt` objects
226
+ are not the public filter grammar. See
227
+ [searching](04-creating-and-querying.md) for custom ranges and
228
+ [backend limits](30-backend-capabilities.md#temporal-values) for precision rules.
229
+
186
230
  ## Migration Considerations
187
231
 
188
232
  ### From Existing Systems
@@ -198,18 +242,18 @@ If migrating from a system that stores dates differently:
198
242
  For optimal date handling, configure your database connection:
199
243
 
200
244
  **MySQL** (in Knex config):
201
- ```javascript
245
+ ```js
202
246
  {
203
247
  client: 'mysql2',
204
248
  connection: {
205
249
  // ... other config
206
- timezone: 'UTC'
250
+ timezone: 'Z'
207
251
  }
208
252
  }
209
253
  ```
210
254
 
211
255
  **PostgreSQL** (in Knex config):
212
- ```javascript
256
+ ```js
213
257
  {
214
258
  client: 'pg',
215
259
  connection: {