@atscript/moost-db 0.1.55 → 0.1.56
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/README.md +3 -1
- package/dist/index.cjs +467 -3
- package/dist/index.d.cts +165 -2
- package/dist/index.d.mts +165 -2
- package/dist/index.mjs +460 -5
- package/package.json +4 -2
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { ValidatorError, defineAnnotatedType, serializeAnnotatedType, throwFeatureDisabled } from "@atscript/typescript/utils";
|
|
2
2
|
import { Body, Delete, Get, HttpError, Patch, Post, Put, Query, Url } from "@moostjs/event-http";
|
|
3
|
-
import { ApplyDecorators, Controller, Inherit, Inject, Intercept, Moost, Param, Provide, TInterceptorPriority, defineInterceptor, useControllerContext } from "moost";
|
|
3
|
+
import { ApplyDecorators, Controller, Inherit, Inject, Intercept, Moost, Param, Provide, Resolve, TInterceptorPriority, defineInterceptor, getMoostMate, useControllerContext } from "moost";
|
|
4
4
|
import { parseUrl } from "@uniqu/url";
|
|
5
5
|
import { DbError } from "@atscript/db";
|
|
6
|
+
import { useBody } from "@wooksjs/http-body";
|
|
6
7
|
//#region src/validation-interceptor.ts
|
|
7
8
|
const dbErrorCodeToStatus = { CONFLICT: 409 };
|
|
8
9
|
function transformValidationError(error, reply) {
|
|
@@ -179,6 +180,196 @@ function findSortOffender(sort, isAllowed) {
|
|
|
179
180
|
}
|
|
180
181
|
}
|
|
181
182
|
//#endregion
|
|
183
|
+
//#region src/actions/keys.ts
|
|
184
|
+
/** Method-level metadata key — written by `@DbAction(name, opts)`. */
|
|
185
|
+
const MOOST_DB_ACTION = "atscript_db_action";
|
|
186
|
+
/** Class-level metadata key — written by `@DbActions` and the level-pinned shortcuts. Stored as an array; decorators accumulate. */
|
|
187
|
+
const MOOST_DB_ACTIONS = "atscript_db_actions";
|
|
188
|
+
/** Param-level metadata key — written by `@DbActionPK()` / `@DbActionPKs()`. Drives level inference. */
|
|
189
|
+
const MOOST_DB_ACTION_PARAM = "atscript_db_action_param";
|
|
190
|
+
/**
|
|
191
|
+
* Shared method-decorator update used by `@DbAction` and `@DbActionDefault`:
|
|
192
|
+
* read the existing `MOOST_DB_ACTION` slot, merge the patch (later-applied
|
|
193
|
+
* fields win), and write it back. `name` is empty until `@DbAction` provides
|
|
194
|
+
* one — `discoverActions` warns and drops actions with no name.
|
|
195
|
+
*/
|
|
196
|
+
function mergeActionMeta(current, patch) {
|
|
197
|
+
const existing = current[MOOST_DB_ACTION];
|
|
198
|
+
return {
|
|
199
|
+
name: patch.name ?? existing?.name ?? "",
|
|
200
|
+
opts: {
|
|
201
|
+
...existing?.opts,
|
|
202
|
+
...patch.opts
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
//#endregion
|
|
207
|
+
//#region src/actions/discover.ts
|
|
208
|
+
/** Optional fields shared between method opts and class-level entries. */
|
|
209
|
+
const OPTIONAL_FIELDS = [
|
|
210
|
+
"icon",
|
|
211
|
+
"intent",
|
|
212
|
+
"description",
|
|
213
|
+
"order",
|
|
214
|
+
"default",
|
|
215
|
+
"promptText"
|
|
216
|
+
];
|
|
217
|
+
const WARN_PREFIX = "[moost-db actions]";
|
|
218
|
+
const actionsCache = /* @__PURE__ */ new WeakMap();
|
|
219
|
+
/**
|
|
220
|
+
* Discover all actions declared on a controller and produce the `/meta` array.
|
|
221
|
+
* Reads class + method metadata via `getMoostMate()` and resolves bound POST
|
|
222
|
+
* paths through the Moost controller overview.
|
|
223
|
+
*
|
|
224
|
+
* Result is memoized per controller constructor — discovery walks every
|
|
225
|
+
* handler entry and reads decorator metadata, which is wasted work to repeat
|
|
226
|
+
* across instances.
|
|
227
|
+
*/
|
|
228
|
+
function discoverActions(controllerCtor, app, logger) {
|
|
229
|
+
const cached = actionsCache.get(controllerCtor);
|
|
230
|
+
if (cached) return cached;
|
|
231
|
+
const overview = app.getControllersOverview?.()?.find((o) => o.type === controllerCtor);
|
|
232
|
+
const out = [];
|
|
233
|
+
collectMethodActions(controllerCtor, overview, logger, out);
|
|
234
|
+
collectClassActions(controllerCtor, logger, out);
|
|
235
|
+
applyDefaultPerLevel(out, logger);
|
|
236
|
+
actionsCache.set(controllerCtor, out);
|
|
237
|
+
return out;
|
|
238
|
+
}
|
|
239
|
+
function collectMethodActions(ctor, overview, logger, out) {
|
|
240
|
+
if (!overview) return;
|
|
241
|
+
const byMethod = /* @__PURE__ */ new Map();
|
|
242
|
+
for (const h of overview.handlers) {
|
|
243
|
+
const list = byMethod.get(h.method);
|
|
244
|
+
if (list) list.push(h);
|
|
245
|
+
else byMethod.set(h.method, [h]);
|
|
246
|
+
}
|
|
247
|
+
for (const [methodName, handlers] of byMethod) {
|
|
248
|
+
const methodMeta = handlers[0].meta;
|
|
249
|
+
const action = methodMeta[MOOST_DB_ACTION];
|
|
250
|
+
if (!action) continue;
|
|
251
|
+
if (!action.name) {
|
|
252
|
+
logger.warn(`${WARN_PREFIX} method "${methodName}" has @DbActionDefault() but no @DbAction(name) — dropping`);
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const levelInfer = inferMethodLevel(methodMeta.params ?? [], action.name, logger);
|
|
256
|
+
if (!levelInfer) continue;
|
|
257
|
+
if (levelInfer.bodyConflict) {
|
|
258
|
+
logger.warn(`${WARN_PREFIX} action "${action.name}" cannot mix @DbActionPK*/@DbActionPKs with @Body() — dropping`);
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
const postEntry = handlers.find((h) => h.handler.type === "HTTP" && h.handler.method === "POST");
|
|
262
|
+
if (!postEntry) {
|
|
263
|
+
logger.warn(`${WARN_PREFIX} action "${action.name}" requires @Post(...); no POST handler bound to ${methodName} — dropping`);
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
const path = postEntry.registeredAs[0]?.path;
|
|
267
|
+
if (!path) {
|
|
268
|
+
logger.warn(`${WARN_PREFIX} action "${action.name}" — POST handler ${methodName} has no registered path — dropping`);
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
const label = action.opts.label ?? methodMeta.label;
|
|
272
|
+
if (!label) {
|
|
273
|
+
logger.warn(`${WARN_PREFIX} action "${action.name}" requires a label (opts.label or @Label) — dropping`);
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
const info = {
|
|
277
|
+
name: action.name,
|
|
278
|
+
label,
|
|
279
|
+
level: levelInfer.level,
|
|
280
|
+
processor: "backend",
|
|
281
|
+
value: path
|
|
282
|
+
};
|
|
283
|
+
copyOptionalFields(info, action.opts);
|
|
284
|
+
out.push(info);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function inferMethodLevel(params, actionName, logger) {
|
|
288
|
+
let hasPk = false;
|
|
289
|
+
let hasPks = false;
|
|
290
|
+
let hasBody = false;
|
|
291
|
+
for (const p of params) {
|
|
292
|
+
const kind = p[MOOST_DB_ACTION_PARAM];
|
|
293
|
+
if (kind === "pk") hasPk = true;
|
|
294
|
+
else if (kind === "pks") hasPks = true;
|
|
295
|
+
if (p.paramSource === "BODY") hasBody = true;
|
|
296
|
+
}
|
|
297
|
+
if (hasPk && hasPks) {
|
|
298
|
+
logger.warn(`${WARN_PREFIX} action "${actionName}" has both @DbActionPK and @DbActionPKs — dropping`);
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
const level = hasPk ? "row" : hasPks ? "rows" : "table";
|
|
302
|
+
return {
|
|
303
|
+
level,
|
|
304
|
+
bodyConflict: hasBody && level !== "table"
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
function collectClassActions(ctor, logger, out) {
|
|
308
|
+
const list = getMoostMate().read(ctor)?.[MOOST_DB_ACTIONS];
|
|
309
|
+
if (!list) return;
|
|
310
|
+
for (const { name, entry, forcedLevel } of list) {
|
|
311
|
+
const built = buildClassEntry(name, entry, forcedLevel, logger);
|
|
312
|
+
if (built) out.push(built);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function buildClassEntry(name, entry, forcedLevel, logger) {
|
|
316
|
+
const level = forcedLevel ?? entry.level;
|
|
317
|
+
if (!level) {
|
|
318
|
+
logger.warn(`${WARN_PREFIX} class-level action "${name}" requires a level — dropping. Use @DbTableActions/@DbRowActions/@DbRowsActions or set "level" explicitly.`);
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
if (!entry.label) {
|
|
322
|
+
logger.warn(`${WARN_PREFIX} class-level action "${name}" requires a label — dropping`);
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
const processor = entry.processor;
|
|
326
|
+
let value;
|
|
327
|
+
if (processor === "navigate" || processor === "backend") {
|
|
328
|
+
const v = entry.value;
|
|
329
|
+
if (typeof v !== "string" || v === "") {
|
|
330
|
+
logger.warn(`${WARN_PREFIX} class-level action "${name}" with processor "${processor}" requires a non-empty "value" — dropping`);
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
value = v;
|
|
334
|
+
} else if (processor === "custom") {
|
|
335
|
+
const v = entry.value;
|
|
336
|
+
if (v !== void 0 && v !== null) {
|
|
337
|
+
logger.warn(`${WARN_PREFIX} class-level action "${name}" with processor "custom" forbids "value" (always derived from the dict key) — dropping`);
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
value = name;
|
|
341
|
+
} else {
|
|
342
|
+
logger.warn(`${WARN_PREFIX} class-level action "${name}" has unknown processor "${String(processor)}" — dropping`);
|
|
343
|
+
return null;
|
|
344
|
+
}
|
|
345
|
+
const info = {
|
|
346
|
+
name,
|
|
347
|
+
label: entry.label,
|
|
348
|
+
level,
|
|
349
|
+
processor,
|
|
350
|
+
value
|
|
351
|
+
};
|
|
352
|
+
copyOptionalFields(info, entry);
|
|
353
|
+
return info;
|
|
354
|
+
}
|
|
355
|
+
function applyDefaultPerLevel(actions, logger) {
|
|
356
|
+
const winners = /* @__PURE__ */ new Map();
|
|
357
|
+
for (const a of actions) {
|
|
358
|
+
if (!a.default) continue;
|
|
359
|
+
const existing = winners.get(a.level);
|
|
360
|
+
if (existing) {
|
|
361
|
+
a.default = false;
|
|
362
|
+
logger.warn(`${WARN_PREFIX} duplicate default action at level "${a.level}": "${existing}" wins, "${a.name}" demoted`);
|
|
363
|
+
} else winners.set(a.level, a.name);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
function copyOptionalFields(info, source) {
|
|
367
|
+
for (const key of OPTIONAL_FIELDS) {
|
|
368
|
+
const value = source[key];
|
|
369
|
+
if (value !== void 0) info[key] = value;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
//#endregion
|
|
182
373
|
//#region \0@oxc-project+runtime@0.120.0/helpers/decorateMetadata.js
|
|
183
374
|
function __decorateMetadata(k, v) {
|
|
184
375
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
@@ -364,6 +555,8 @@ let AsReadableController = class AsReadableController {
|
|
|
364
555
|
* Builds the `/meta` payload. Override in subclasses to populate source-specific
|
|
365
556
|
* fields. Defaults return a minimal envelope with the serialized type and the
|
|
366
557
|
* read-only flag; value-help dicts populate their capability hints here.
|
|
558
|
+
* Subclasses that fully replace the envelope must call {@link buildActions}
|
|
559
|
+
* directly so `@DbAction*` decorators still surface.
|
|
367
560
|
*/
|
|
368
561
|
async buildMetaResponse() {
|
|
369
562
|
return {
|
|
@@ -374,9 +567,18 @@ let AsReadableController = class AsReadableController {
|
|
|
374
567
|
readOnly: this._isReadOnly(),
|
|
375
568
|
relations: [],
|
|
376
569
|
fields: {},
|
|
377
|
-
type: this.getSerializedType()
|
|
570
|
+
type: this.getSerializedType(),
|
|
571
|
+
actions: this.buildActions()
|
|
378
572
|
};
|
|
379
573
|
}
|
|
574
|
+
/**
|
|
575
|
+
* Discovers `@DbAction*` and `@DbActions`-style class metadata on this
|
|
576
|
+
* controller and produces the `actions` array. Returns `[]` for value-help
|
|
577
|
+
* controllers — see {@link AsValueHelpController#buildMetaResponse}.
|
|
578
|
+
*/
|
|
579
|
+
buildActions() {
|
|
580
|
+
return discoverActions(this.constructor, this.app, this.logger);
|
|
581
|
+
}
|
|
380
582
|
};
|
|
381
583
|
__decorate([
|
|
382
584
|
Get("meta"),
|
|
@@ -732,7 +934,8 @@ let AsDbReadableController = class AsDbReadableController extends AsReadableCont
|
|
|
732
934
|
readOnly: this._isReadOnly(),
|
|
733
935
|
relations,
|
|
734
936
|
fields,
|
|
735
|
-
type: this.getSerializedType()
|
|
937
|
+
type: this.getSerializedType(),
|
|
938
|
+
actions: this.buildActions()
|
|
736
939
|
};
|
|
737
940
|
}
|
|
738
941
|
};
|
|
@@ -1014,9 +1217,13 @@ let AsValueHelpController = class AsValueHelpController extends AsReadableContro
|
|
|
1014
1217
|
readOnly: this._isReadOnly(),
|
|
1015
1218
|
relations: [],
|
|
1016
1219
|
fields,
|
|
1017
|
-
type: this.getSerializedType()
|
|
1220
|
+
type: this.getSerializedType(),
|
|
1221
|
+
actions: []
|
|
1018
1222
|
};
|
|
1019
1223
|
}
|
|
1224
|
+
buildActions() {
|
|
1225
|
+
return [];
|
|
1226
|
+
}
|
|
1020
1227
|
};
|
|
1021
1228
|
__decorate([
|
|
1022
1229
|
Get("query"),
|
|
@@ -1211,4 +1418,252 @@ function applySelect(rows, select) {
|
|
|
1211
1418
|
});
|
|
1212
1419
|
}
|
|
1213
1420
|
//#endregion
|
|
1214
|
-
|
|
1421
|
+
//#region src/actions/db-action.decorator.ts
|
|
1422
|
+
/**
|
|
1423
|
+
* Mark a controller method as a database action surfaced via `/meta`.
|
|
1424
|
+
*
|
|
1425
|
+
* Metadata-only — pair with `@Post(...)` for Moost to bind the route. The
|
|
1426
|
+
* meta builder reads this metadata plus the bound POST path lazily and
|
|
1427
|
+
* emits the action with `processor: 'backend'`. Order vs.
|
|
1428
|
+
* `@DbActionDefault()` does not matter — both merge into the same slot.
|
|
1429
|
+
*
|
|
1430
|
+
* @example
|
|
1431
|
+
* ```ts
|
|
1432
|
+
* @Post('actions/block')
|
|
1433
|
+
* @DbAction('block', { label: 'Block', icon: 'i-as-block', intent: 'negative' })
|
|
1434
|
+
* async blockUser(@DbActionPK() id: string) { ... }
|
|
1435
|
+
* ```
|
|
1436
|
+
*/
|
|
1437
|
+
function DbAction(name, opts = {}) {
|
|
1438
|
+
return getMoostMate().decorate((current) => {
|
|
1439
|
+
const meta = current;
|
|
1440
|
+
return {
|
|
1441
|
+
...current,
|
|
1442
|
+
[MOOST_DB_ACTION]: mergeActionMeta(meta, {
|
|
1443
|
+
name,
|
|
1444
|
+
opts
|
|
1445
|
+
})
|
|
1446
|
+
};
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
//#endregion
|
|
1450
|
+
//#region src/actions/db-action-default.decorator.ts
|
|
1451
|
+
/**
|
|
1452
|
+
* Sugar that flips `default: true` on the same method's `@DbAction` metadata.
|
|
1453
|
+
* Equivalent to passing `opts.default = true`. Decorator order does not matter.
|
|
1454
|
+
*/
|
|
1455
|
+
function DbActionDefault() {
|
|
1456
|
+
return getMoostMate().decorate((current) => {
|
|
1457
|
+
const meta = current;
|
|
1458
|
+
return {
|
|
1459
|
+
...current,
|
|
1460
|
+
[MOOST_DB_ACTION]: mergeActionMeta(meta, { opts: { default: true } })
|
|
1461
|
+
};
|
|
1462
|
+
});
|
|
1463
|
+
}
|
|
1464
|
+
//#endregion
|
|
1465
|
+
//#region src/actions/pk-source.ts
|
|
1466
|
+
/**
|
|
1467
|
+
* Extract the PK validation source from a controller instance. Looks for
|
|
1468
|
+
* `readable` (set by {@link AsDbReadableController}) or `table` (set by
|
|
1469
|
+
* {@link AsDbController}).
|
|
1470
|
+
*
|
|
1471
|
+
* If the controller has no typed table attached (e.g. a value-help
|
|
1472
|
+
* controller, or a plain Moost controller without `@TableController`),
|
|
1473
|
+
* throws an HTTP 500 — this is a **server misconfiguration**, not a client
|
|
1474
|
+
* error. The body parser has nothing to validate against, so the request
|
|
1475
|
+
* cannot proceed. Use `@Body()` and parse the PK manually if you need to
|
|
1476
|
+
* accept PK-shaped bodies on a controller without an attached table.
|
|
1477
|
+
*/
|
|
1478
|
+
function resolvePkSource(controller) {
|
|
1479
|
+
const c = controller;
|
|
1480
|
+
const candidate = c.readable ?? c.table;
|
|
1481
|
+
if (!isPkValidationSource(candidate)) throw new HttpError(500, "@DbActionPK/@DbActionPKs requires a controller with an attached table (via @TableController / @ReadableController). Use @Body() instead if your controller has no typed table.");
|
|
1482
|
+
return candidate;
|
|
1483
|
+
}
|
|
1484
|
+
function isPkValidationSource(value) {
|
|
1485
|
+
if (!value || typeof value !== "object") return false;
|
|
1486
|
+
const v = value;
|
|
1487
|
+
return Array.isArray(v.primaryKeys) && Array.isArray(v.fieldDescriptors);
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* Build a parameter decorator that parses the JSON request body, validates
|
|
1491
|
+
* it against the bound table's PK schema with `validate`, and tags the param
|
|
1492
|
+
* so {@link discoverActions} can infer the action's `level`.
|
|
1493
|
+
*/
|
|
1494
|
+
function createPkParamDecorator(kind, validate, resolverName) {
|
|
1495
|
+
return ApplyDecorators(getMoostMate().decorate(MOOST_DB_ACTION_PARAM, kind), Resolve(async () => {
|
|
1496
|
+
const body = await useBody().parseBody();
|
|
1497
|
+
validate(body, resolvePkSource(useControllerContext().getController()));
|
|
1498
|
+
return body;
|
|
1499
|
+
}, resolverName));
|
|
1500
|
+
}
|
|
1501
|
+
//#endregion
|
|
1502
|
+
//#region src/actions/pk-validation.ts
|
|
1503
|
+
/**
|
|
1504
|
+
* Validate a JSON-decoded body against a single-row PK shape (scalar or
|
|
1505
|
+
* composite). Throws {@link ValidatorError} with structured `errors` so the
|
|
1506
|
+
* existing validation interceptor returns HTTP 400.
|
|
1507
|
+
*/
|
|
1508
|
+
function validateSinglePk(body, source, path = "") {
|
|
1509
|
+
const errors = collectPkErrors(body, source, path);
|
|
1510
|
+
if (errors.length > 0) throw new ValidatorError(errors);
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* Validate a JSON-decoded body against an array of PK shapes (`@DbActionPKs`).
|
|
1514
|
+
* The body MUST be an array; each element is validated against the PK schema.
|
|
1515
|
+
*/
|
|
1516
|
+
function validateMultiPk(body, source) {
|
|
1517
|
+
if (!Array.isArray(body)) throw new ValidatorError([{
|
|
1518
|
+
path: "",
|
|
1519
|
+
message: "Expected JSON array of primary keys",
|
|
1520
|
+
details: []
|
|
1521
|
+
}]);
|
|
1522
|
+
const errors = [];
|
|
1523
|
+
for (let i = 0; i < body.length; i++) errors.push(...collectPkErrors(body[i], source, `[${i}]`));
|
|
1524
|
+
if (errors.length > 0) throw new ValidatorError(errors);
|
|
1525
|
+
}
|
|
1526
|
+
function collectPkErrors(value, source, pathPrefix) {
|
|
1527
|
+
const pkFields = source.primaryKeys;
|
|
1528
|
+
if (pkFields.length === 0) return [{
|
|
1529
|
+
path: pathPrefix,
|
|
1530
|
+
message: "Table has no primary key configured",
|
|
1531
|
+
details: []
|
|
1532
|
+
}];
|
|
1533
|
+
const errors = [];
|
|
1534
|
+
if (pkFields.length === 1) {
|
|
1535
|
+
const err = checkScalar(value, findFieldDescriptor(source, pkFields[0]), pathPrefix);
|
|
1536
|
+
if (err) errors.push(err);
|
|
1537
|
+
return errors;
|
|
1538
|
+
}
|
|
1539
|
+
if (!isPlainObject(value)) {
|
|
1540
|
+
errors.push({
|
|
1541
|
+
path: pathPrefix,
|
|
1542
|
+
message: "Expected JSON object for composite primary key",
|
|
1543
|
+
details: []
|
|
1544
|
+
});
|
|
1545
|
+
return errors;
|
|
1546
|
+
}
|
|
1547
|
+
for (const fieldName of pkFields) {
|
|
1548
|
+
const sub = pathPrefix ? `${pathPrefix}.${fieldName}` : fieldName;
|
|
1549
|
+
if (!(fieldName in value)) {
|
|
1550
|
+
errors.push({
|
|
1551
|
+
path: sub,
|
|
1552
|
+
message: `Missing primary-key field "${fieldName}"`,
|
|
1553
|
+
details: []
|
|
1554
|
+
});
|
|
1555
|
+
continue;
|
|
1556
|
+
}
|
|
1557
|
+
const fd = findFieldDescriptor(source, fieldName);
|
|
1558
|
+
const err = checkScalar(value[fieldName], fd, sub);
|
|
1559
|
+
if (err) errors.push(err);
|
|
1560
|
+
}
|
|
1561
|
+
return errors;
|
|
1562
|
+
}
|
|
1563
|
+
function findFieldDescriptor(source, name) {
|
|
1564
|
+
for (const fd of source.fieldDescriptors) if (fd.path === name) return fd;
|
|
1565
|
+
}
|
|
1566
|
+
function checkScalar(value, fd, path) {
|
|
1567
|
+
const expected = fd?.designType ?? "string";
|
|
1568
|
+
if (expected === "string" && typeof value !== "string") return scalarMismatch(path, expected, value);
|
|
1569
|
+
if (expected === "number" && typeof value !== "number") return scalarMismatch(path, expected, value);
|
|
1570
|
+
if (expected === "boolean" && typeof value !== "boolean") return scalarMismatch(path, expected, value);
|
|
1571
|
+
}
|
|
1572
|
+
function scalarMismatch(path, expected, value) {
|
|
1573
|
+
return {
|
|
1574
|
+
path,
|
|
1575
|
+
message: `Expected primary-key value to be ${expected}, got ${describe(value)}`,
|
|
1576
|
+
details: []
|
|
1577
|
+
};
|
|
1578
|
+
}
|
|
1579
|
+
function describe(value) {
|
|
1580
|
+
if (value === null) return "null";
|
|
1581
|
+
if (Array.isArray(value)) return "array";
|
|
1582
|
+
return typeof value;
|
|
1583
|
+
}
|
|
1584
|
+
function isPlainObject(value) {
|
|
1585
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1586
|
+
}
|
|
1587
|
+
//#endregion
|
|
1588
|
+
//#region src/actions/db-action-pk.decorator.ts
|
|
1589
|
+
/**
|
|
1590
|
+
* Parameter resolver that reads the primary key from the JSON request body
|
|
1591
|
+
* and validates it against the bound table's PK schema.
|
|
1592
|
+
*
|
|
1593
|
+
* - Single-field PK → JSON-encoded scalar (`"abc"`, `42`, `true`).
|
|
1594
|
+
* - Composite PK → JSON object with all PK fields.
|
|
1595
|
+
*
|
|
1596
|
+
* Validation is strict — no type coercion. Mismatches throw a
|
|
1597
|
+
* `ValidatorError` which the existing validation interceptor surfaces as
|
|
1598
|
+
* HTTP 400 with the same envelope as DTO failures.
|
|
1599
|
+
*
|
|
1600
|
+
* Marks the param so {@link discoverActions} can infer the action's `level`
|
|
1601
|
+
* as `'row'`.
|
|
1602
|
+
*/
|
|
1603
|
+
function DbActionPK() {
|
|
1604
|
+
return createPkParamDecorator("pk", validateSinglePk, "dbActionPk");
|
|
1605
|
+
}
|
|
1606
|
+
//#endregion
|
|
1607
|
+
//#region src/actions/db-action-pks.decorator.ts
|
|
1608
|
+
/**
|
|
1609
|
+
* Parameter resolver that reads a JSON array of primary keys from the request
|
|
1610
|
+
* body and validates each entry against the bound table's PK schema.
|
|
1611
|
+
*
|
|
1612
|
+
* - Scalar PK → JSON array of scalars (`["a","b","c"]`).
|
|
1613
|
+
* - Composite PK → JSON array of objects.
|
|
1614
|
+
*
|
|
1615
|
+
* Validation is strict — no type coercion. Marks the param so
|
|
1616
|
+
* {@link discoverActions} can infer the action's `level` as `'rows'`.
|
|
1617
|
+
*/
|
|
1618
|
+
function DbActionPKs() {
|
|
1619
|
+
return createPkParamDecorator("pks", validateMultiPk, "dbActionPks");
|
|
1620
|
+
}
|
|
1621
|
+
//#endregion
|
|
1622
|
+
//#region src/actions/db-actions.decorator.ts
|
|
1623
|
+
/**
|
|
1624
|
+
* Declare class-level actions on a controller. Entries are flat dicts with
|
|
1625
|
+
* `processor: 'navigate' | 'custom' | 'backend'` matching the `/meta` wire
|
|
1626
|
+
* shape (see {@link TDbActionsEntry}). Each entry MUST specify `level`. Use
|
|
1627
|
+
* the level-pinned shortcuts (`@DbTableActions`, `@DbRowActions`,
|
|
1628
|
+
* `@DbRowsActions`) to avoid repeating `level`.
|
|
1629
|
+
*
|
|
1630
|
+
* The dictionary key serves as the action `name`. Entries do NOT bind any
|
|
1631
|
+
* HTTP route — the meta builder surfaces them in `/meta` only. For
|
|
1632
|
+
* `processor: 'backend'`, the dev-supplied `value` MUST point to a real
|
|
1633
|
+
* `@Post`-bound endpoint accepting the level-determined body shape.
|
|
1634
|
+
*
|
|
1635
|
+
* Multiple `@DbActions` (and shortcut) decorators on the same class
|
|
1636
|
+
* accumulate.
|
|
1637
|
+
*/
|
|
1638
|
+
function DbActions(dict) {
|
|
1639
|
+
return classLevelActions(dict);
|
|
1640
|
+
}
|
|
1641
|
+
/** Sugar for `@DbActions` with `level: 'table'` injected into each entry. */
|
|
1642
|
+
function DbTableActions(dict) {
|
|
1643
|
+
return classLevelActions(dict, "table");
|
|
1644
|
+
}
|
|
1645
|
+
/** Sugar for `@DbActions` with `level: 'row'` injected into each entry. */
|
|
1646
|
+
function DbRowActions(dict) {
|
|
1647
|
+
return classLevelActions(dict, "row");
|
|
1648
|
+
}
|
|
1649
|
+
/** Sugar for `@DbActions` with `level: 'rows'` injected into each entry. */
|
|
1650
|
+
function DbRowsActions(dict) {
|
|
1651
|
+
return classLevelActions(dict, "rows");
|
|
1652
|
+
}
|
|
1653
|
+
function classLevelActions(dict, forcedLevel) {
|
|
1654
|
+
const entries = [];
|
|
1655
|
+
for (const [name, entry] of Object.entries(dict)) entries.push({
|
|
1656
|
+
name,
|
|
1657
|
+
entry,
|
|
1658
|
+
forcedLevel
|
|
1659
|
+
});
|
|
1660
|
+
return getMoostMate().decorate((current) => {
|
|
1661
|
+
const existing = current["atscript_db_actions"] ?? [];
|
|
1662
|
+
return {
|
|
1663
|
+
...current,
|
|
1664
|
+
[MOOST_DB_ACTIONS]: [...existing, ...entries]
|
|
1665
|
+
};
|
|
1666
|
+
});
|
|
1667
|
+
}
|
|
1668
|
+
//#endregion
|
|
1669
|
+
export { AsDbController, AsDbReadableController, AsJsonValueHelpController, AsReadableController, AsValueHelpController, DbAction, DbActionDefault, DbActionPK, DbActionPKs, DbActions, DbRowActions, DbRowsActions, DbTableActions, READABLE_DEF, ReadableController, TABLE_DEF, TableController, UseValidationErrorTransform, ViewController, discoverActions, validationErrorTransform };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atscript/moost-db",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.56",
|
|
4
4
|
"description": "Generic database controller for Moost with Atscript.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"annotations",
|
|
@@ -45,6 +45,7 @@
|
|
|
45
45
|
"@atscript/typescript": "^0.1.50",
|
|
46
46
|
"@moostjs/event-http": "^0.6.8",
|
|
47
47
|
"@uniqu/core": "^0.1.5",
|
|
48
|
+
"@wooksjs/http-body": "^0.7.10",
|
|
48
49
|
"moost": "^0.6.8",
|
|
49
50
|
"unplugin-atscript": "^0.1.50"
|
|
50
51
|
},
|
|
@@ -52,8 +53,9 @@
|
|
|
52
53
|
"@atscript/typescript": "^0.1.50",
|
|
53
54
|
"@moostjs/event-http": "^0.6.8",
|
|
54
55
|
"@uniqu/core": "^0.1.5",
|
|
56
|
+
"@wooksjs/http-body": "^0.7.10",
|
|
55
57
|
"moost": "^0.6.8",
|
|
56
|
-
"@atscript/db": "^0.1.
|
|
58
|
+
"@atscript/db": "^0.1.56"
|
|
57
59
|
},
|
|
58
60
|
"scripts": {
|
|
59
61
|
"postinstall": "asc -f dts",
|