fastify-auto-sqlapi 0.5.1 → 1.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.
- package/AGENTS.md +5 -5
- package/AGENTS_BACKEND.md +166 -130
- package/AGENTS_FRONTEND.md +60 -38
- package/BREAKING_CHANGES.md +9 -893
- package/CHANGELOG.md +246 -15
- package/README.md +71 -45
- package/dist/bin/generate-schema.js +12 -12
- package/dist/bin/generate-tables.js +1 -2
- package/dist/bin/utils.d.ts +2 -6
- package/dist/bin/utils.d.ts.map +1 -1
- package/dist/bin/utils.js +13 -33
- package/dist/index.d.ts +13 -33
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -37
- package/dist/lib/adapters/mysql-adapter.d.ts +5 -2
- package/dist/lib/adapters/mysql-adapter.d.ts.map +1 -1
- package/dist/lib/adapters/pg-adapter.d.ts +5 -2
- package/dist/lib/adapters/pg-adapter.d.ts.map +1 -1
- package/dist/lib/agent/manifest.d.ts +27 -10
- package/dist/lib/agent/manifest.d.ts.map +1 -1
- package/dist/lib/agent/manifest.js +43 -26
- package/dist/lib/agent/tool-schemas.d.ts +5 -4
- package/dist/lib/agent/tool-schemas.d.ts.map +1 -1
- package/dist/lib/agent/tool-schemas.js +5 -5
- package/dist/lib/cli/config.d.ts +37 -2
- package/dist/lib/cli/config.d.ts.map +1 -1
- package/dist/lib/cli/config.js +106 -16
- package/dist/lib/cli/mysql-introspect.d.ts +6 -1
- package/dist/lib/cli/mysql-introspect.d.ts.map +1 -1
- package/dist/lib/cli/mysql-introspect.js +15 -15
- package/dist/lib/cli/pg-introspect.d.ts +0 -1
- package/dist/lib/cli/pg-introspect.d.ts.map +1 -1
- package/dist/lib/cli/pg-introspect.js +2 -13
- package/dist/lib/cli/tables-codegen.d.ts +0 -4
- package/dist/lib/cli/tables-codegen.d.ts.map +1 -1
- package/dist/lib/cli/tables-codegen.js +24 -87
- package/dist/lib/db.d.ts +42 -17
- package/dist/lib/db.d.ts.map +1 -1
- package/dist/lib/db.js +114 -40
- package/dist/lib/dialect.d.ts +5 -0
- package/dist/lib/dialect.d.ts.map +1 -1
- package/dist/lib/dialect.js +3 -0
- package/dist/lib/engine/bulk/bulk-delete.d.ts +5 -0
- package/dist/lib/engine/bulk/bulk-delete.d.ts.map +1 -1
- package/dist/lib/engine/bulk/bulk-delete.js +66 -30
- package/dist/lib/engine/bulk/bulk-upsert.d.ts.map +1 -1
- package/dist/lib/engine/bulk/bulk-upsert.js +45 -26
- package/dist/lib/engine/read-hooks.d.ts +3 -3
- package/dist/lib/engine/read-hooks.d.ts.map +1 -1
- package/dist/lib/engine/read-hooks.js +3 -3
- package/dist/lib/engine/rest/delete.d.ts.map +1 -1
- package/dist/lib/engine/rest/delete.js +12 -18
- package/dist/lib/engine/rest/get.js +8 -8
- package/dist/lib/engine/rest/insert.d.ts.map +1 -1
- package/dist/lib/engine/rest/insert.js +31 -18
- package/dist/lib/engine/rest/update.d.ts.map +1 -1
- package/dist/lib/engine/rest/update.js +34 -17
- package/dist/lib/engine/search/aggregations.d.ts +3 -3
- package/dist/lib/engine/search/aggregations.d.ts.map +1 -1
- package/dist/lib/engine/search/aggregations.js +20 -16
- package/dist/lib/engine/search/conditions.d.ts +9 -5
- package/dist/lib/engine/search/conditions.d.ts.map +1 -1
- package/dist/lib/engine/search/conditions.js +31 -20
- package/dist/lib/engine/search/fields.d.ts +44 -11
- package/dist/lib/engine/search/fields.d.ts.map +1 -1
- package/dist/lib/engine/search/fields.js +93 -27
- package/dist/lib/engine/search/join-families.d.ts +7 -7
- package/dist/lib/engine/search/join-families.d.ts.map +1 -1
- package/dist/lib/engine/search/join-families.js +84 -75
- package/dist/lib/engine/search/joins.d.ts +15 -7
- package/dist/lib/engine/search/joins.d.ts.map +1 -1
- package/dist/lib/engine/search/joins.js +23 -13
- package/dist/lib/engine/search/order-by.d.ts +11 -12
- package/dist/lib/engine/search/order-by.d.ts.map +1 -1
- package/dist/lib/engine/search/order-by.js +24 -28
- package/dist/lib/engine/search/search.d.ts.map +1 -1
- package/dist/lib/engine/search/search.js +111 -64
- package/dist/lib/engine/validate.d.ts +21 -3
- package/dist/lib/engine/validate.d.ts.map +1 -1
- package/dist/lib/engine/validate.js +106 -16
- package/dist/lib/engine/write-helpers.d.ts +69 -16
- package/dist/lib/engine/write-helpers.d.ts.map +1 -1
- package/dist/lib/engine/write-helpers.js +257 -105
- package/dist/lib/errors.d.ts +42 -10
- package/dist/lib/errors.d.ts.map +1 -1
- package/dist/lib/errors.js +69 -15
- package/dist/lib/nullable.d.ts +3 -2
- package/dist/lib/nullable.d.ts.map +1 -1
- package/dist/lib/nullable.js +14 -5
- package/dist/lib/read-access.d.ts +25 -16
- package/dist/lib/read-access.d.ts.map +1 -1
- package/dist/lib/read-access.js +33 -17
- package/dist/lib/schema/bulk-delete.d.ts +13 -7
- package/dist/lib/schema/bulk-delete.d.ts.map +1 -1
- package/dist/lib/schema/bulk-delete.js +18 -8
- package/dist/lib/schema/bulk-upsert.d.ts +3 -3
- package/dist/lib/schema/bulk-upsert.d.ts.map +1 -1
- package/dist/lib/schema/bulk-upsert.js +9 -14
- package/dist/lib/schema/get.d.ts +1 -1
- package/dist/lib/schema/get.d.ts.map +1 -1
- package/dist/lib/schema/get.js +2 -2
- package/dist/lib/schema/helpers.d.ts +41 -23
- package/dist/lib/schema/helpers.d.ts.map +1 -1
- package/dist/lib/schema/helpers.js +80 -33
- package/dist/lib/schema/insert.d.ts +1 -1
- package/dist/lib/schema/insert.d.ts.map +1 -1
- package/dist/lib/schema/insert.js +12 -20
- package/dist/lib/schema/search.d.ts +2 -13
- package/dist/lib/schema/search.d.ts.map +1 -1
- package/dist/lib/schema/search.js +64 -61
- package/dist/lib/schema/update.d.ts +1 -1
- package/dist/lib/schema/update.d.ts.map +1 -1
- package/dist/lib/schema/update.js +6 -13
- package/dist/lib/sql-api.d.ts +47 -25
- package/dist/lib/sql-api.d.ts.map +1 -1
- package/dist/lib/sql-api.js +70 -27
- package/dist/lib/table-helpers.d.ts +92 -14
- package/dist/lib/table-helpers.d.ts.map +1 -1
- package/dist/lib/table-helpers.js +367 -128
- package/dist/lib/tenant.d.ts +16 -22
- package/dist/lib/tenant.d.ts.map +1 -1
- package/dist/lib/tenant.js +38 -54
- package/dist/lib/write-access.d.ts +15 -9
- package/dist/lib/write-access.d.ts.map +1 -1
- package/dist/lib/write-access.js +12 -4
- package/dist/routes/auto/agent-manifest.routes.d.ts +1 -1
- package/dist/routes/auto/agent-manifest.routes.js +2 -2
- package/dist/routes/auto/bulk-delete.routes.d.ts +2 -2
- package/dist/routes/auto/bulk-delete.routes.d.ts.map +1 -1
- package/dist/routes/auto/bulk-delete.routes.js +1 -7
- package/dist/routes/auto/bulk-upsert.routes.d.ts +2 -2
- package/dist/routes/auto/bulk-upsert.routes.d.ts.map +1 -1
- package/dist/routes/auto/bulk-upsert.routes.js +2 -2
- package/dist/routes/auto/delete.routes.d.ts +2 -2
- package/dist/routes/auto/delete.routes.d.ts.map +1 -1
- package/dist/routes/auto/delete.routes.js +8 -10
- package/dist/routes/auto/get.routes.d.ts +2 -2
- package/dist/routes/auto/get.routes.d.ts.map +1 -1
- package/dist/routes/auto/get.routes.js +5 -5
- package/dist/routes/auto/insert.routes.d.ts +2 -2
- package/dist/routes/auto/insert.routes.d.ts.map +1 -1
- package/dist/routes/auto/insert.routes.js +1 -7
- package/dist/routes/auto/plugin.d.ts +6 -0
- package/dist/routes/auto/plugin.d.ts.map +1 -1
- package/dist/routes/auto/plugin.js +60 -36
- package/dist/routes/auto/route-helpers.d.ts +26 -12
- package/dist/routes/auto/route-helpers.d.ts.map +1 -1
- package/dist/routes/auto/route-helpers.js +50 -19
- package/dist/routes/auto/search.routes.d.ts +2 -2
- package/dist/routes/auto/search.routes.d.ts.map +1 -1
- package/dist/routes/auto/search.routes.js +36 -24
- package/dist/routes/auto/update.routes.d.ts +2 -2
- package/dist/routes/auto/update.routes.d.ts.map +1 -1
- package/dist/routes/auto/update.routes.js +1 -8
- package/dist/routes/sql-api-decorator.d.ts +30 -12
- package/dist/routes/sql-api-decorator.d.ts.map +1 -1
- package/dist/routes/sql-api-decorator.js +44 -27
- package/dist/types/cli.d.ts +17 -6
- package/dist/types/cli.d.ts.map +1 -1
- package/dist/types/computed.d.ts +1 -1
- package/dist/types/computed.d.ts.map +1 -1
- package/dist/types/conditions.d.ts +3 -1
- package/dist/types/conditions.d.ts.map +1 -1
- package/dist/types/db.d.ts +44 -4
- package/dist/types/db.d.ts.map +1 -1
- package/dist/types/dml.d.ts +26 -17
- package/dist/types/dml.d.ts.map +1 -1
- package/dist/types/hooks.d.ts +62 -0
- package/dist/types/hooks.d.ts.map +1 -0
- package/dist/types/hooks.js +1 -0
- package/dist/types/join.d.ts +25 -8
- package/dist/types/join.d.ts.map +1 -1
- package/dist/types/plugin.d.ts +58 -19
- package/dist/types/plugin.d.ts.map +1 -1
- package/dist/types/plugin.js +2 -0
- package/dist/types/request.d.ts +2 -2
- package/dist/types/schema.d.ts +3 -3
- package/dist/types/schema.d.ts.map +1 -1
- package/dist/types/search.d.ts +28 -13
- package/dist/types/search.d.ts.map +1 -1
- package/dist/types/search.js +2 -1
- package/dist/types/table.d.ts +109 -94
- package/dist/types/table.d.ts.map +1 -1
- package/dist/types/table.js +7 -2
- package/dist/types/tenant.d.ts +28 -2
- package/dist/types/tenant.d.ts.map +1 -1
- package/dist/types/tenant.js +7 -1
- package/dist/types/validation.d.ts +69 -13
- package/dist/types/validation.d.ts.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -0
- package/docs/GLOSSARY.md +11 -5
- package/docs/adr/0003-bulk-not-transactional.md +2 -1
- package/docs/adr/0006-raw-db-errors.md +2 -1
- package/docs/adr/0013-sanitized-db-errors.md +2 -1
- package/docs/adr/0014-what-follows-a-write-join.md +1 -1
- package/docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md +88 -0
- package/docs/adr/0023-a-write-runs-in-a-transaction-or-not-at-all.md +60 -0
- package/docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md +78 -0
- package/docs/adr/0025-validatebulk-replaces-validate-in-a-bulk-upsert.md +46 -0
- package/docs/adr/0026-update-carries-its-primary-key-in-main.md +43 -0
- package/docs/adr/0027-the-1-0-contract.md +74 -0
- package/docs/adr/0028-select-star-is-the-default-projection.md +64 -0
- package/docs/adr/0029-a-write-names-its-child-rows-by-action.md +96 -0
- package/docs/adr/0030-a-child-row-is-validated-by-its-own-table.md +117 -0
- package/docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md +58 -0
- package/docs/adr/0032-tenant-scope-names-schema-fields.md +56 -0
- package/docs/adr/README.md +12 -1
- package/docs/upgrading/0.x.md +906 -0
- package/docs/upgrading/1.0.md +628 -0
- package/package.json +4 -5
|
@@ -1,7 +1,11 @@
|
|
|
1
|
+
import { STATUS_CODES } from 'node:http';
|
|
1
2
|
import fp from 'fastify-plugin';
|
|
2
3
|
import { ConditionBuilder } from 'node-condition-builder';
|
|
3
4
|
import { getDialect } from '../../lib/dialect.js';
|
|
4
|
-
import {
|
|
5
|
+
import { validateDbTables } from '../../lib/table-helpers.js';
|
|
6
|
+
import { assertDbErrors, isSanitized } from '../../lib/errors.js';
|
|
7
|
+
import { routeHandlerReached, sanitizeAndLog } from './route-helpers.js';
|
|
8
|
+
import { createRegistrationSqlApi, decorateSqlApi, REGISTRATION_SQL_API, } from '../sql-api-decorator.js';
|
|
5
9
|
import { setupSwagger } from '../setup-swagger.js';
|
|
6
10
|
import searchRoutes from './search.routes.js';
|
|
7
11
|
import getRoutes from './get.routes.js';
|
|
@@ -11,6 +15,7 @@ import deleteRoutes from './delete.routes.js';
|
|
|
11
15
|
import bulkUpsertRoutes from './bulk-upsert.routes.js';
|
|
12
16
|
import bulkDeleteRoutes from './bulk-delete.routes.js';
|
|
13
17
|
import agentManifestRoutes from './agent-manifest.routes.js';
|
|
18
|
+
import { TABLE_OPERATIONS } from '../../types.js';
|
|
14
19
|
// Schema combinators for which Ajv reports one error per failed branch plus a
|
|
15
20
|
// single combinator-level summary error, all targeting the same path.
|
|
16
21
|
const COMBINATOR_KEYWORDS = new Set(['anyOf', 'oneOf']);
|
|
@@ -35,8 +40,8 @@ function normalizeAjvErrors(errors) {
|
|
|
35
40
|
};
|
|
36
41
|
const mapped = errors.map((v) => ({
|
|
37
42
|
path: toPath(v),
|
|
38
|
-
message: v.message || 'invalid',
|
|
39
43
|
code: v.keyword || 'unknown',
|
|
44
|
+
message: v.message || 'invalid',
|
|
40
45
|
}));
|
|
41
46
|
const combinatorPaths = new Set(mapped.filter((f) => COMBINATOR_KEYWORDS.has(f.code)).map((f) => f.path));
|
|
42
47
|
const seen = new Set();
|
|
@@ -50,48 +55,67 @@ function normalizeAjvErrors(errors) {
|
|
|
50
55
|
return true;
|
|
51
56
|
});
|
|
52
57
|
}
|
|
58
|
+
/** Refuse an `operations` option the routes could not honour, at registration. */
|
|
59
|
+
function assertPluginOperations(operations) {
|
|
60
|
+
if (operations === undefined)
|
|
61
|
+
return;
|
|
62
|
+
if (!Array.isArray(operations)) {
|
|
63
|
+
throw new TypeError(`the plugin option 'operations' is an array of: ${TABLE_OPERATIONS.join(', ')}`);
|
|
64
|
+
}
|
|
65
|
+
for (const op of operations) {
|
|
66
|
+
if (!TABLE_OPERATIONS.includes(op)) {
|
|
67
|
+
throw new TypeError(`the plugin option 'operations' names '${op}', which is not one of: ${TABLE_OPERATIONS.join(', ')}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
53
71
|
export default fp(async function fastifyAutoSqlApi(fastify, options) {
|
|
72
|
+
// Refused, not ignored: without it the registration would run with no tables at all.
|
|
73
|
+
if (Object.hasOwn(options, 'DbTables')) {
|
|
74
|
+
throw new TypeError("the plugin option 'DbTables' is now 'dbTables' (camelCase, like every other option)");
|
|
75
|
+
}
|
|
76
|
+
validateDbTables(options.dbTables);
|
|
77
|
+
assertPluginOperations(options.operations);
|
|
78
|
+
assertDbErrors(options.dbErrors);
|
|
54
79
|
// Set ConditionBuilder dialect globally
|
|
55
80
|
const dialect = getDialect(options.dialect || 'postgres');
|
|
56
81
|
ConditionBuilder.DIALECT = dialect.cbDialect;
|
|
57
|
-
// SqlApi:
|
|
58
|
-
|
|
82
|
+
// This registration's SqlApi: its routes run through it whatever else is registered.
|
|
83
|
+
// Exposed to the parent scope via fp as `sqlApi`, unless `decorate: false`.
|
|
84
|
+
const getSqlApi = createRegistrationSqlApi(fastify, options);
|
|
85
|
+
if (options.decorate !== false)
|
|
86
|
+
decorateSqlApi(fastify, getSqlApi);
|
|
59
87
|
// Routes in a child scope — prefix applies here, not at fp level
|
|
60
|
-
const { prefix, ...
|
|
88
|
+
const { prefix, ...consumerRouteOptions } = options;
|
|
89
|
+
const routeOptions = { ...consumerRouteOptions, [REGISTRATION_SQL_API]: getSqlApi };
|
|
61
90
|
await fastify.register(async (instance) => {
|
|
62
|
-
//
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
//
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
fields: validationErrors,
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
const statusCode = error.statusCode || 500;
|
|
85
|
-
// A sanitized error carries the request id so the client can point at the log line
|
|
86
|
-
// holding the real cause, and — under `exposeDebugInfo` — the description of that
|
|
87
|
-
// cause (ADR 0013). Both are additive: the fields above never change shape.
|
|
88
|
-
const sanitized = error;
|
|
91
|
+
// One envelope for every error, whoever raised it:
|
|
92
|
+
// { statusCode, error, message, requestId, fields? }
|
|
93
|
+
// `error` is the status' reason phrase, never a JS error's class name. `requestId` is the
|
|
94
|
+
// same value Fastify logs as `reqId`, so any error can be traced to its log line. Every
|
|
95
|
+
// 400 carries `fields` — from the request schema (Ajv), from `validate`/`validateBulk`,
|
|
96
|
+
// or from the engine through `httpError` — so a client has one place to look, and an
|
|
97
|
+
// empty array when the rejection is not attributable to one input. A driver error the
|
|
98
|
+
// consumer mapped through `dbErrors` carries its code there too, whatever its status
|
|
99
|
+
// (ADR 0024). `debugInfo` is additive, under `exposeDebugInfo` only (ADR 0013).
|
|
100
|
+
instance.setErrorHandler((raised, request, reply) => {
|
|
101
|
+
// An error raised after a route handler ran, outside its catch — the serializer refusing a
|
|
102
|
+
// stored value the Schema no longer describes, quoting it — is sanitized here like any
|
|
103
|
+
// other route error. One raised before (the consumer's onRequests) is left as it is.
|
|
104
|
+
const error = routeHandlerReached(request) && !isSanitized(raised)
|
|
105
|
+
? sanitizeAndLog(raised, request, options)
|
|
106
|
+
: raised;
|
|
107
|
+
const carried = error;
|
|
108
|
+
const statusCode = error.validation ? 400 : (error.statusCode || 500);
|
|
109
|
+
const fields = error.validation ? normalizeAjvErrors(error.validation) : carried.validationErrors;
|
|
89
110
|
reply.status(statusCode).send({
|
|
90
111
|
statusCode,
|
|
91
|
-
error:
|
|
92
|
-
message: error.message,
|
|
93
|
-
|
|
94
|
-
|
|
112
|
+
error: STATUS_CODES[statusCode] ?? 'Error',
|
|
113
|
+
message: error.validation ? 'Validation failed' : error.message,
|
|
114
|
+
requestId: request.id,
|
|
115
|
+
// Every 400 has fields; another status has them only when its cause carries a code
|
|
116
|
+
// (a `dbErrors` answer), so a client reads machine codes in one place.
|
|
117
|
+
...(statusCode === 400 || fields ? { fields: fields ?? [] } : {}),
|
|
118
|
+
...(carried.debugInfo ? { debugInfo: carried.debugInfo } : {}),
|
|
95
119
|
});
|
|
96
120
|
});
|
|
97
121
|
if (options.swagger) {
|
|
@@ -1,37 +1,51 @@
|
|
|
1
1
|
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
|
2
|
-
import
|
|
3
|
-
|
|
2
|
+
import { type RegistrationOptions } from '../sql-api-decorator.js';
|
|
3
|
+
import type { SqlApi } from '../../lib/sql-api.js';
|
|
4
|
+
import type { TableConfig, SqlApiPluginOptions, DbTables, TableOperation } from '../../types.js';
|
|
5
|
+
export declare function buildWriteDescription(action: string, tableName: string, tableConf: TableConfig): string;
|
|
4
6
|
interface RouteSchema {
|
|
5
7
|
body?: any;
|
|
6
8
|
params?: any;
|
|
7
9
|
querystring?: any;
|
|
8
10
|
response?: any;
|
|
9
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* Whether this request reached a route handler of the plugin. An error raised from then on is
|
|
14
|
+
* the route's to answer, even one raised after the handler returned (the serializer refusing a
|
|
15
|
+
* stored value); one raised before it, by the consumer's `onRequests`, is the consumer's own.
|
|
16
|
+
*/
|
|
17
|
+
export declare function routeHandlerReached(request: FastifyRequest): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Answer an error a route did not raise itself: replace it with one that carries no database
|
|
20
|
+
* detail (`sanitizeRouteError`, ADR 0013) and log the original under the request's `reqId`.
|
|
21
|
+
* A 4xx comes back unchanged.
|
|
22
|
+
*/
|
|
23
|
+
export declare function sanitizeAndLog(err: unknown, request: FastifyRequest, options: Pick<SqlApiPluginOptions, 'exposeDebugInfo' | 'dbErrors'>): unknown;
|
|
10
24
|
export interface AutoRouteSpec {
|
|
11
|
-
/** Operation key matched against `
|
|
25
|
+
/** Operation key matched against `TableConfig.operations` to decide whether to register the route. */
|
|
12
26
|
operation: TableOperation;
|
|
13
27
|
/**
|
|
14
|
-
* Set when the route addresses records by a single PK value (get, delete
|
|
28
|
+
* Set when the route addresses records by a single PK value in its path (get, delete).
|
|
15
29
|
* Tables with a composite primary key skip these routes: matching on the first PK column
|
|
16
30
|
* alone would touch every row sharing that value. Explicitly listing the operation in
|
|
17
|
-
* `
|
|
31
|
+
* `TableConfig.operations` for such a table throws at registration.
|
|
18
32
|
*/
|
|
19
33
|
singlePkOnly?: boolean;
|
|
20
34
|
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
21
35
|
/**
|
|
22
|
-
* URL builder receiving the `
|
|
36
|
+
* URL builder receiving the `dbTables` key — never `Schema.tableName`: several table
|
|
23
37
|
* configs may expose the same physical table, and each key needs its own route.
|
|
24
38
|
*/
|
|
25
39
|
url: (tableName: string) => string;
|
|
26
40
|
successStatus: 200 | 201;
|
|
27
41
|
/** Build per-table schemas (body, params, querystring, response). Response is wrapped with `{ [successStatus]: ... }` automatically. */
|
|
28
|
-
schemas: (dbTables: DbTables, tableName: string, tableConf:
|
|
42
|
+
schemas: (dbTables: DbTables, tableName: string, tableConf: TableConfig) => RouteSchema;
|
|
29
43
|
summary: string;
|
|
30
|
-
description: (tableName: string, tableConf:
|
|
31
|
-
/** Translates the request to a sqlApi
|
|
32
|
-
* the registrar will reply.status(successStatus).send(returnValue). */
|
|
33
|
-
handle: (
|
|
44
|
+
description: (tableName: string, tableConf: TableConfig, schemas: RouteSchema) => string;
|
|
45
|
+
/** Translates the request to a call on this registration's sqlApi. If it does not call
|
|
46
|
+
* reply.send/status itself, the registrar will reply.status(successStatus).send(returnValue). */
|
|
47
|
+
handle: (sqlApi: SqlApi, tableName: string, tableConf: TableConfig, request: FastifyRequest, reply: FastifyReply) => Promise<unknown>;
|
|
34
48
|
}
|
|
35
|
-
export declare function registerForAllTables(fastify: FastifyInstance, options:
|
|
49
|
+
export declare function registerForAllTables(fastify: FastifyInstance, options: RegistrationOptions, spec: AutoRouteSpec): Promise<void>;
|
|
36
50
|
export {};
|
|
37
51
|
//# sourceMappingURL=route-helpers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-helpers.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/route-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"route-helpers.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/route-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAwB,KAAK,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEzF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAEnD,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAQjG,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,GAAG,MAAM,CAQvG;AAED,UAAU,WAAW;IAEnB,IAAI,CAAC,EAAE,GAAG,CAAC;IAEX,MAAM,CAAC,EAAE,GAAG,CAAC;IAEb,WAAW,CAAC,EAAE,GAAG,CAAC;IAElB,QAAQ,CAAC,EAAE,GAAG,CAAC;CAChB;AAKD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAEpE;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,OAAO,EACZ,OAAO,EAAE,cAAc,EACvB,OAAO,EAAE,IAAI,CAAC,mBAAmB,EAAE,iBAAiB,GAAG,UAAU,CAAC,GACjE,OAAO,CAaT;AAED,MAAM,WAAW,aAAa;IAC5B,sGAAsG;IACtG,SAAS,EAAE,cAAc,CAAC;IAC1B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;IAC1C;;;OAGG;IACH,GAAG,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,aAAa,EAAE,GAAG,GAAG,GAAG,CAAC;IACzB,wIAAwI;IACxI,OAAO,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,KAAK,WAAW,CAAC;IACxF,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,KAAK,MAAM,CAAC;IACzF;qGACiG;IACjG,MAAM,EAAE,CACN,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,WAAW,EACtB,OAAO,EAAE,cAAc,EACvB,KAAK,EAAE,YAAY,KAChB,OAAO,CAAC,OAAO,CAAC,CAAC;CACvB;AA+DD,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,EAC5B,IAAI,EAAE,aAAa,GAClB,OAAO,CAAC,IAAI,CAAC,CA2Bf"}
|
|
@@ -1,20 +1,51 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { REGISTRATION_SQL_API } from '../sql-api-decorator.js';
|
|
2
2
|
import { sanitizeRouteError } from '../../lib/errors.js';
|
|
3
3
|
import { isCompositePrimary } from '../../types.js';
|
|
4
4
|
function mergeOnRequests(options, tableConf) {
|
|
5
5
|
return [...(options.onRequests || []), ...(tableConf.onRequests || [])];
|
|
6
6
|
}
|
|
7
7
|
export function buildWriteDescription(action, tableName, tableConf) {
|
|
8
|
-
const joinList = tableConf.
|
|
8
|
+
const joinList = tableConf.writeJoins
|
|
9
9
|
?.map((j) => j.alias)
|
|
10
10
|
.join(', ');
|
|
11
11
|
return [
|
|
12
12
|
`${action} ${tableName}`,
|
|
13
|
-
joinList && `
|
|
13
|
+
joinList && `Child rows (upsert, delete, replace) for: ${joinList}`,
|
|
14
14
|
].filter(Boolean).join('. ');
|
|
15
15
|
}
|
|
16
|
+
/** Requests that reached one of the plugin's route handlers. */
|
|
17
|
+
const HANDLER_REACHED = new WeakSet();
|
|
16
18
|
/**
|
|
17
|
-
*
|
|
19
|
+
* Whether this request reached a route handler of the plugin. An error raised from then on is
|
|
20
|
+
* the route's to answer, even one raised after the handler returned (the serializer refusing a
|
|
21
|
+
* stored value); one raised before it, by the consumer's `onRequests`, is the consumer's own.
|
|
22
|
+
*/
|
|
23
|
+
export function routeHandlerReached(request) {
|
|
24
|
+
return HANDLER_REACHED.has(request);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Answer an error a route did not raise itself: replace it with one that carries no database
|
|
28
|
+
* detail (`sanitizeRouteError`, ADR 0013) and log the original under the request's `reqId`.
|
|
29
|
+
* A 4xx comes back unchanged.
|
|
30
|
+
*/
|
|
31
|
+
export function sanitizeAndLog(err, request, options) {
|
|
32
|
+
const safe = sanitizeRouteError(err, {
|
|
33
|
+
requestId: request.id,
|
|
34
|
+
exposeDebugInfo: options.exposeDebugInfo,
|
|
35
|
+
dbErrors: options.dbErrors,
|
|
36
|
+
});
|
|
37
|
+
if (safe !== err) {
|
|
38
|
+
// A code the consumer mapped is an expected outcome, not a server fault: the
|
|
39
|
+
// driver error stays in the log, at a level that does not page anyone.
|
|
40
|
+
if (safe.statusCode >= 500)
|
|
41
|
+
request.log.error({ err }, 'sqlapi: unhandled error');
|
|
42
|
+
else
|
|
43
|
+
request.log.info({ err }, 'sqlapi: database error answered through dbErrors');
|
|
44
|
+
}
|
|
45
|
+
return safe;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Iterates over every table in `options.dbTables` and registers one Fastify route for it
|
|
18
49
|
* following `spec`. Centralizes onRequest hook merging, tags, schema response wrapping,
|
|
19
50
|
* default reply when handler returns a value.
|
|
20
51
|
*/
|
|
@@ -25,8 +56,10 @@ export function buildWriteDescription(action, tableName, tableConf) {
|
|
|
25
56
|
* the consumer explicitly listed the operation it is a configuration error: failing at
|
|
26
57
|
* startup beats a route that silently never exists.
|
|
27
58
|
*/
|
|
28
|
-
function isTableRoutable(tableName, tableConf, spec) {
|
|
29
|
-
//
|
|
59
|
+
function isTableRoutable(tableName, tableConf, spec, allowed) {
|
|
60
|
+
// Both whitelists apply, the registration's and the table's; an omitted one allows all.
|
|
61
|
+
if (allowed && !allowed.includes(spec.operation))
|
|
62
|
+
return false;
|
|
30
63
|
if (tableConf.operations && !tableConf.operations.includes(spec.operation))
|
|
31
64
|
return false;
|
|
32
65
|
if (!spec.singlePkOnly || !isCompositePrimary(tableConf.primary))
|
|
@@ -34,7 +67,7 @@ function isTableRoutable(tableName, tableConf, spec) {
|
|
|
34
67
|
if (tableConf.operations?.includes(spec.operation)) {
|
|
35
68
|
throw new Error(`Table "${tableName}" has a composite primary key (${tableConf.primary.join(', ')}): ` +
|
|
36
69
|
`operation "${spec.operation}" addresses records by a single PK value and cannot be exposed. ` +
|
|
37
|
-
`Remove it from "operations"
|
|
70
|
+
`Remove it from "operations": read it with search, write it with update, delete it with bulkDelete.`);
|
|
38
71
|
}
|
|
39
72
|
return false;
|
|
40
73
|
}
|
|
@@ -62,30 +95,28 @@ function buildRouteSchema(tableName, tableConf, spec, schemas) {
|
|
|
62
95
|
return schema;
|
|
63
96
|
}
|
|
64
97
|
export async function registerForAllTables(fastify, options, spec) {
|
|
65
|
-
//
|
|
66
|
-
//
|
|
67
|
-
|
|
68
|
-
const {
|
|
69
|
-
for (const [tableName, tableConf] of Object.entries(
|
|
70
|
-
if (!isTableRoutable(tableName, tableConf, spec))
|
|
98
|
+
// The routes run through the SqlApi of the registration that declared them, never through
|
|
99
|
+
// whatever `fastify.sqlApi` resolves to in their scope.
|
|
100
|
+
const getSqlApi = options[REGISTRATION_SQL_API];
|
|
101
|
+
const { dbTables } = options;
|
|
102
|
+
for (const [tableName, tableConf] of Object.entries(dbTables)) {
|
|
103
|
+
if (!isTableRoutable(tableName, tableConf, spec, options.operations))
|
|
71
104
|
continue;
|
|
72
|
-
const schemas = spec.schemas(
|
|
105
|
+
const schemas = spec.schemas(dbTables, tableName, tableConf);
|
|
73
106
|
fastify.route({
|
|
74
107
|
method: spec.method,
|
|
75
108
|
url: spec.url(tableName),
|
|
76
109
|
schema: buildRouteSchema(tableName, tableConf, spec, schemas),
|
|
77
110
|
onRequest: mergeOnRequests(options, tableConf),
|
|
78
111
|
handler: async (request, reply) => {
|
|
112
|
+
HANDLER_REACHED.add(request);
|
|
79
113
|
try {
|
|
80
|
-
const result = await spec.handle(
|
|
114
|
+
const result = await spec.handle(getSqlApi(), tableName, tableConf, request, reply);
|
|
81
115
|
if (!reply.sent)
|
|
82
116
|
reply.status(spec.successStatus).send(result);
|
|
83
117
|
}
|
|
84
118
|
catch (err) {
|
|
85
|
-
|
|
86
|
-
if (safe !== err)
|
|
87
|
-
request.log.error({ err }, 'sqlapi: unhandled error');
|
|
88
|
-
throw safe;
|
|
119
|
+
throw sanitizeAndLog(err, request, options);
|
|
89
120
|
}
|
|
90
121
|
},
|
|
91
122
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { FastifyInstance } from 'fastify';
|
|
2
|
-
import type {
|
|
3
|
-
export default function searchRoutes(fastify: FastifyInstance, options:
|
|
2
|
+
import type { RegistrationOptions } from '../sql-api-decorator.js';
|
|
3
|
+
export default function searchRoutes(fastify: FastifyInstance, options: RegistrationOptions): Promise<void>;
|
|
4
4
|
//# sourceMappingURL=search.routes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/search.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"search.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/search.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAG/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AA+BnE,wBAA8B,YAAY,CACxC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAoDf"}
|
|
@@ -1,16 +1,34 @@
|
|
|
1
|
-
import { SearchTableBodyPost,
|
|
1
|
+
import { SearchTableBodyPost, SearchTableResponse } from '../../lib/schema/search.js';
|
|
2
2
|
import { registerForAllTables } from './route-helpers.js';
|
|
3
|
-
import {
|
|
4
|
-
import { DEFAULT_MAX_ITEMS_PER_PAGE } from '../../types.js';
|
|
3
|
+
import { rejectRetiredKey, rejectRetiredSearchKeys } from '../../lib/engine/search/fields.js';
|
|
4
|
+
import { DEFAULT_ITEMS_PER_PAGE, DEFAULT_MAX_ITEMS_PER_PAGE } from '../../types.js';
|
|
5
|
+
/**
|
|
6
|
+
* The querystring keys the search read before 1.0. They moved into the body; a client still
|
|
7
|
+
* sending one gets a 400 naming it instead of a result that silently ignores its ordering,
|
|
8
|
+
* paging or aggregates. Any other querystring key is left alone, as on every route.
|
|
9
|
+
*/
|
|
10
|
+
const RETIRED_QUERY_KEYS = {
|
|
11
|
+
orderBy: `send 'orderBy' in the body`,
|
|
12
|
+
page: `send 'paginator': { page, itemsPerPage } in the body`,
|
|
13
|
+
itemsPerPage: `send 'paginator': { page, itemsPerPage } in the body`,
|
|
14
|
+
computeMin: `send 'compute': { min: [field] } in the body`,
|
|
15
|
+
computeMax: `send 'compute': { max: [field] } in the body`,
|
|
16
|
+
computeSum: `send 'compute': { sum: [field] } in the body`,
|
|
17
|
+
computeAvg: `send 'compute': { avg: [field] } in the body`,
|
|
18
|
+
};
|
|
19
|
+
function rejectRetiredQuery(query) {
|
|
20
|
+
for (const [key, instead] of Object.entries(RETIRED_QUERY_KEYS))
|
|
21
|
+
rejectRetiredKey(query, key, key, instead);
|
|
22
|
+
}
|
|
5
23
|
export default async function searchRoutes(fastify, options) {
|
|
24
|
+
const maxRows = options.maxItemsPerPage ?? DEFAULT_MAX_ITEMS_PER_PAGE;
|
|
6
25
|
await registerForAllTables(fastify, options, {
|
|
7
26
|
operation: 'search',
|
|
8
27
|
method: 'POST',
|
|
9
28
|
url: (tableName) => `/search/${tableName}`,
|
|
10
29
|
successStatus: 200,
|
|
11
30
|
schemas: (db, table) => ({
|
|
12
|
-
body: SearchTableBodyPost(db, table),
|
|
13
|
-
querystring: SearchTableQuery(options.maxItemsPerPage ?? DEFAULT_MAX_ITEMS_PER_PAGE),
|
|
31
|
+
body: SearchTableBodyPost(db, table, maxRows),
|
|
14
32
|
response: SearchTableResponse(db, table),
|
|
15
33
|
}),
|
|
16
34
|
summary: 'Search',
|
|
@@ -24,32 +42,26 @@ export default async function searchRoutes(fastify, options) {
|
|
|
24
42
|
leftAliases.length && `Available joinLeft aliases: ${leftAliases.join(', ')}`,
|
|
25
43
|
].filter(Boolean).join('. ');
|
|
26
44
|
},
|
|
27
|
-
handle: async (
|
|
28
|
-
|
|
45
|
+
handle: async (sqlApi, tableName, _tc, request) => {
|
|
46
|
+
rejectRetiredQuery(request.query);
|
|
29
47
|
const body = request.body;
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
//
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const result = await fastify.sqlApi.search(tableName, {
|
|
48
|
+
rejectRetiredSearchKeys(body);
|
|
49
|
+
// The page size cap is the schemas' `maximum` (a structured 400); `maxRows` is the LIMIT
|
|
50
|
+
// applied when the client does not paginate, and the ceiling of the page-only default.
|
|
51
|
+
const paginator = body.paginator
|
|
52
|
+
? { page: body.paginator.page ?? 1, itemsPerPage: body.paginator.itemsPerPage ?? Math.min(DEFAULT_ITEMS_PER_PAGE, maxRows) }
|
|
53
|
+
: undefined;
|
|
54
|
+
const result = await sqlApi.search(tableName, {
|
|
38
55
|
filters: body.filters,
|
|
39
56
|
conditions: body.conditions,
|
|
40
57
|
joinMustExist: body.joinMustExist,
|
|
41
58
|
joinMultiple: body.joinMultiple,
|
|
42
59
|
joinGroup: body.joinGroup,
|
|
43
60
|
joinLeft: body.joinLeft,
|
|
44
|
-
|
|
45
|
-
orderBy:
|
|
46
|
-
paginator
|
|
47
|
-
|
|
48
|
-
: undefined,
|
|
49
|
-
computeMin: query.computeMin,
|
|
50
|
-
computeMax: query.computeMax,
|
|
51
|
-
computeSum: query.computeSum,
|
|
52
|
-
computeAvg: query.computeAvg,
|
|
61
|
+
select: body.select,
|
|
62
|
+
orderBy: body.orderBy,
|
|
63
|
+
paginator,
|
|
64
|
+
compute: body.compute,
|
|
53
65
|
maxRows,
|
|
54
66
|
}, request);
|
|
55
67
|
return { table: tableName, ...result };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { FastifyInstance } from 'fastify';
|
|
2
|
-
import type {
|
|
3
|
-
export default function updateRoutes(fastify: FastifyInstance, options:
|
|
2
|
+
import type { RegistrationOptions } from '../sql-api-decorator.js';
|
|
3
|
+
export default function updateRoutes(fastify: FastifyInstance, options: RegistrationOptions): Promise<void>;
|
|
4
4
|
//# sourceMappingURL=update.routes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/update.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAG/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"update.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/update.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAG/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAGnE,wBAA8B,YAAY,CACxC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAef"}
|
|
@@ -12,13 +12,6 @@ export default async function updateRoutes(fastify, options) {
|
|
|
12
12
|
}),
|
|
13
13
|
summary: 'Update',
|
|
14
14
|
description: (name, tc) => buildWriteDescription('Update a record in', name, tc),
|
|
15
|
-
handle: (
|
|
16
|
-
const body = request.body;
|
|
17
|
-
return fastify.sqlApi.update(tableName, {
|
|
18
|
-
record: body.main,
|
|
19
|
-
secondaries: body.secondaries,
|
|
20
|
-
deletions: body.deletions,
|
|
21
|
-
}, request);
|
|
22
|
-
},
|
|
15
|
+
handle: (sqlApi, tableName, _tc, request) => sqlApi.update(tableName, request.body, request),
|
|
23
16
|
});
|
|
24
17
|
}
|
|
@@ -1,18 +1,36 @@
|
|
|
1
1
|
import type { FastifyInstance } from 'fastify';
|
|
2
2
|
import { type SqlApi } from '../lib/sql-api.js';
|
|
3
3
|
import type { SqlApiPluginOptions } from '../types.js';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
sqlApi: SqlApi;
|
|
7
|
-
}
|
|
8
|
-
}
|
|
4
|
+
/** Resolves a registration's SqlApi on first use (the pool may be decorated after registration). */
|
|
5
|
+
export type SqlApiGetter = () => SqlApi;
|
|
9
6
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* `registerForAllTables` so they also work standalone, each within its own
|
|
14
|
-
* encapsulation context. The underlying pool (`fastify.pg` / `fastify.mysql`)
|
|
15
|
-
* is shared either way.
|
|
7
|
+
* Route options key under which the main plugin hands its own SqlApi to the internal route
|
|
8
|
+
* plugins it registers, so all of them share one instance. A symbol: it is not an option a
|
|
9
|
+
* consumer can set, and it never collides with one.
|
|
16
10
|
*/
|
|
17
|
-
export declare
|
|
11
|
+
export declare const REGISTRATION_SQL_API: unique symbol;
|
|
12
|
+
/** Route plugin options as the main plugin passes them: the consumer's, plus its SqlApi. */
|
|
13
|
+
export type RegistrationOptions = SqlApiPluginOptions & {
|
|
14
|
+
[REGISTRATION_SQL_API]: SqlApiGetter;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The SqlApi of ONE registration, built lazily from that registration's options: its
|
|
18
|
+
* `dbTables`, `getTenantId`, `dialect` and `debug`. The routes of a registration always run
|
|
19
|
+
* through it, never through whatever `fastify.sqlApi` resolves to in their scope — with the
|
|
20
|
+
* plugin registered under two prefixes, that decorator belongs to the first registration, and
|
|
21
|
+
* the second one's tables, tenant scopes and rules would silently be ignored.
|
|
22
|
+
*
|
|
23
|
+
* The underlying pool (`fastify.pg` / `fastify.mysql`) is shared by every registration.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createRegistrationSqlApi(fastify: FastifyInstance, options: SqlApiPluginOptions): SqlApiGetter;
|
|
26
|
+
/**
|
|
27
|
+
* Decorates `fastify.sqlApi` (lazy getter) for application code. Called by the main plugin at
|
|
28
|
+
* the fp level, so the decorator lands on the scope the plugin was registered in.
|
|
29
|
+
*
|
|
30
|
+
* The decorator is for the consumer's own routes only: the auto routes never read it. It
|
|
31
|
+
* belongs to exactly one registration: when the scope already has one — another registration
|
|
32
|
+
* of this plugin, or the application's own — registration fails instead of leaving
|
|
33
|
+
* `app.sqlApi` to whichever came first.
|
|
34
|
+
*/
|
|
35
|
+
export declare function decorateSqlApi(fastify: FastifyInstance, getSqlApi: SqlApiGetter): void;
|
|
18
36
|
//# sourceMappingURL=sql-api-decorator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sql-api-decorator.d.ts","sourceRoot":"","sources":["../../src/routes/sql-api-decorator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAI/C,OAAO,EAAgB,KAAK,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEvD,
|
|
1
|
+
{"version":3,"file":"sql-api-decorator.d.ts","sourceRoot":"","sources":["../../src/routes/sql-api-decorator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAI/C,OAAO,EAAgB,KAAK,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEvD,oGAAoG;AACpG,MAAM,MAAM,YAAY,GAAG,MAAM,MAAM,CAAC;AAExC;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,eAAmD,CAAC;AAErF,4FAA4F;AAC5F,MAAM,MAAM,mBAAmB,GAAG,mBAAmB,GAAG;IAAE,CAAC,oBAAoB,CAAC,EAAE,YAAY,CAAA;CAAE,CAAC;AAEjG;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,YAAY,CAsBd;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,YAAY,GAAG,IAAI,CAStF"}
|
|
@@ -3,38 +3,55 @@ import { pgQueryable } from '../lib/adapters/pg-adapter.js';
|
|
|
3
3
|
import { mysqlQueryable } from '../lib/adapters/mysql-adapter.js';
|
|
4
4
|
import { createSqlApi } from '../lib/sql-api.js';
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* `registerForAllTables` so they also work standalone, each within its own
|
|
10
|
-
* encapsulation context. The underlying pool (`fastify.pg` / `fastify.mysql`)
|
|
11
|
-
* is shared either way.
|
|
6
|
+
* Route options key under which the main plugin hands its own SqlApi to the internal route
|
|
7
|
+
* plugins it registers, so all of them share one instance. A symbol: it is not an option a
|
|
8
|
+
* consumer can set, and it never collides with one.
|
|
12
9
|
*/
|
|
13
|
-
export
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
10
|
+
export const REGISTRATION_SQL_API = Symbol('fastify-auto-sqlapi.registrationSqlApi');
|
|
11
|
+
/**
|
|
12
|
+
* The SqlApi of ONE registration, built lazily from that registration's options: its
|
|
13
|
+
* `dbTables`, `getTenantId`, `dialect` and `debug`. The routes of a registration always run
|
|
14
|
+
* through it, never through whatever `fastify.sqlApi` resolves to in their scope — with the
|
|
15
|
+
* plugin registered under two prefixes, that decorator belongs to the first registration, and
|
|
16
|
+
* the second one's tables, tenant scopes and rules would silently be ignored.
|
|
17
|
+
*
|
|
18
|
+
* The underlying pool (`fastify.pg` / `fastify.mysql`) is shared by every registration.
|
|
19
|
+
*/
|
|
20
|
+
export function createRegistrationSqlApi(fastify, options) {
|
|
21
|
+
let cachedSqlApi;
|
|
22
|
+
return () => {
|
|
23
|
+
if (!cachedSqlApi) {
|
|
20
24
|
const pool = (options.dialect === 'mysql' || options.dialect === 'mariadb')
|
|
21
25
|
? mysqlQueryable(fastify.mysql)
|
|
22
26
|
: pgQueryable(fastify.pg);
|
|
23
|
-
|
|
27
|
+
const db = createQueryClient(pool, options.dialect);
|
|
24
28
|
if (options.debug)
|
|
25
|
-
|
|
29
|
+
db.setDebug(true);
|
|
30
|
+
// Reads work either way; the first insert or update would fail with the same message.
|
|
31
|
+
// Said once, here, so a misconfigured client is found before that request arrives.
|
|
32
|
+
if (!db.supportsTransactions) {
|
|
33
|
+
fastify.log.warn('sqlapi: the database client has no connect(): inserts and updates need a transaction ' +
|
|
34
|
+
'and will fail. Decorate a pool (fastify.pg from @fastify/postgres, a mysql2/promise pool).');
|
|
35
|
+
}
|
|
36
|
+
cachedSqlApi = createSqlApi(db, options.dbTables, { getTenantId: options.getTenantId });
|
|
26
37
|
}
|
|
27
|
-
return
|
|
38
|
+
return cachedSqlApi;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Decorates `fastify.sqlApi` (lazy getter) for application code. Called by the main plugin at
|
|
43
|
+
* the fp level, so the decorator lands on the scope the plugin was registered in.
|
|
44
|
+
*
|
|
45
|
+
* The decorator is for the consumer's own routes only: the auto routes never read it. It
|
|
46
|
+
* belongs to exactly one registration: when the scope already has one — another registration
|
|
47
|
+
* of this plugin, or the application's own — registration fails instead of leaving
|
|
48
|
+
* `app.sqlApi` to whichever came first.
|
|
49
|
+
*/
|
|
50
|
+
export function decorateSqlApi(fastify, getSqlApi) {
|
|
51
|
+
if (fastify.hasDecorator('sqlApi')) {
|
|
52
|
+
throw new Error('fastify-auto-sqlapi: `sqlApi` is already decorated, by another registration of this plugin ' +
|
|
53
|
+
'or by the application. Pass `decorate: false` to this registration: its routes run with ' +
|
|
54
|
+
'their own configuration either way, and createSqlApi() gives application code another instance.');
|
|
28
55
|
}
|
|
29
|
-
|
|
30
|
-
fastify.decorate('sqlApi', {
|
|
31
|
-
getter() {
|
|
32
|
-
if (!cachedSqlApi) {
|
|
33
|
-
cachedSqlApi = createSqlApi(getDb(), options.DbTables, {
|
|
34
|
-
getTenantId: options.getTenantId,
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
return cachedSqlApi;
|
|
38
|
-
},
|
|
39
|
-
});
|
|
56
|
+
fastify.decorate('sqlApi', { getter: getSqlApi });
|
|
40
57
|
}
|