@nest-my-admin/core 0.8.1 → 0.9.1
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 +34 -2
- package/dist/api/action.service.d.ts +9 -1
- package/dist/api/action.service.js +73 -7
- package/dist/api/admin-api.service.d.ts +3 -1
- package/dist/api/admin-api.service.js +42 -16
- package/dist/audit/audit-reader.js +3 -2
- package/dist/auth/auth.service.js +9 -1
- package/dist/contract.d.ts +9 -0
- package/dist/crud/computed-columns.js +9 -0
- package/dist/dashboard/dashboard.service.js +2 -1
- package/dist/dashboard/widget-data.d.ts +8 -0
- package/dist/dashboard/widget-data.js +55 -0
- package/dist/decorators/admin-action.d.ts +43 -5
- package/dist/decorators/admin-action.js +77 -15
- package/dist/decorators/admin-print.d.ts +4 -1
- package/dist/decorators/admin-print.js +0 -6
- package/dist/decorators/admin-resource.d.ts +6 -2
- package/dist/decorators/admin-scope.d.ts +5 -2
- package/dist/decorators/admin-scope.js +0 -6
- package/dist/decorators/admin-settings-page.d.ts +2 -1
- package/dist/decorators/admin-widget.d.ts +2 -1
- package/dist/decorators/hooks.d.ts +11 -6
- package/dist/decorators/hooks.js +3 -3
- package/dist/decorators/typed.d.ts +20 -0
- package/dist/decorators/typed.js +2 -0
- package/dist/files/file-owner.js +2 -1
- package/dist/host-contract.d.ts +30 -0
- package/dist/host-contract.js +91 -0
- package/dist/http/admin-http.server.js +1 -0
- package/dist/http/error-response.js +4 -0
- package/dist/i18n/texts.js +9 -3
- package/dist/index.d.ts +2 -1
- package/dist/inlines/inline-reader.js +3 -2
- package/dist/inlines/inline-writer.js +3 -2
- package/dist/options.js +23 -1
- package/dist/pages/page-registry.js +3 -2
- package/dist/policy/admin-policy.service.js +30 -11
- package/dist/policy/explain.js +3 -2
- package/dist/rbac/rbac-routes.js +2 -1
- package/dist/registry/resource-registry.js +1 -1
- package/dist/resource/admin-resource-base.js +16 -5
- package/dist/resource/admin-source-base.d.ts +2 -0
- package/package.json +2 -2
|
@@ -2,8 +2,10 @@ import 'reflect-metadata';
|
|
|
2
2
|
import type { ActionSchema } from '../contract.js';
|
|
3
3
|
import { type LocalizedText } from '../i18n/localized-text.js';
|
|
4
4
|
import { type DtoForm } from '../schema/dto-form.js';
|
|
5
|
-
import type
|
|
5
|
+
import { type DtoClass } from '../schema/dto-fields.js';
|
|
6
6
|
import type { ScopedText } from '../i18n/texts.js';
|
|
7
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
8
|
+
import type { Awaitable, RecordMethodDecorator, TypedMethodDecorator } from './typed.js';
|
|
7
9
|
export interface AdminActionOptions {
|
|
8
10
|
/**
|
|
9
11
|
* `'Mark shipped'` or `{ en: 'Mark shipped', fa: 'ارسال شد' }`. Defaults to the humanized method name. A label per
|
|
@@ -38,14 +40,24 @@ export interface AdminActionOptions {
|
|
|
38
40
|
/**
|
|
39
41
|
* A DTO for a form in the dialog. It is validated like a write (whitelist, class-validator) before the method
|
|
40
42
|
* runs; `@AdminField` on its properties sets labels, help and widgets. Files and rich text are not supported.
|
|
43
|
+
* Left out, the class of the method's input parameter is used (it needs `emitDecoratorMetadata`); `false` says
|
|
44
|
+
* the action takes no input, where the parameter types cannot be read.
|
|
41
45
|
*/
|
|
42
|
-
input?: DtoClass;
|
|
46
|
+
input?: DtoClass | false;
|
|
47
|
+
/**
|
|
48
|
+
* Input fields whose values come from a list made when the dialog opens (a dropdown): `{ field: 'methodName' }`.
|
|
49
|
+
* The method `(ctx)` of the resource returns the choices, `string`s or `{ value, label }`s (sync or async); a run
|
|
50
|
+
* re-reads them and refuses a value that is no longer one of them (422).
|
|
51
|
+
*/
|
|
52
|
+
choices?: Record<string, string>;
|
|
43
53
|
icon?: string;
|
|
44
54
|
}
|
|
45
55
|
/** What an action method may return: a message for the person who ran it. */
|
|
46
56
|
export interface ActionOutcome {
|
|
47
57
|
message?: LocalizedText;
|
|
48
58
|
}
|
|
59
|
+
/** What an action method returns: nothing, or an `ActionOutcome`. */
|
|
60
|
+
export type ActionReturn = ActionOutcome | void | null | undefined;
|
|
49
61
|
/** An `@AdminAction` as declared. `name` is the method name: the URL segment and the `{resource}.action.{name}` code. */
|
|
50
62
|
export interface ActionDefinition extends AdminActionOptions {
|
|
51
63
|
name: string;
|
|
@@ -65,6 +77,8 @@ export interface RegisteredAction {
|
|
|
65
77
|
icon?: string;
|
|
66
78
|
input?: DtoClass;
|
|
67
79
|
form?: DtoForm;
|
|
80
|
+
/** Input fields whose choices a resource method gives: field → method name. */
|
|
81
|
+
choices?: Map<string, string>;
|
|
68
82
|
}
|
|
69
83
|
/**
|
|
70
84
|
* A custom action of a resource (spec §5.2): a button on a record, on a list selection (`bulk`) or on the list
|
|
@@ -74,13 +88,37 @@ export interface RegisteredAction {
|
|
|
74
88
|
* wrote is undone when it throws, and `atomic` actions are refused at boot. Throw an `HttpException` (or
|
|
75
89
|
* `AdminFieldError` for input fields) to refuse.
|
|
76
90
|
*/
|
|
77
|
-
export declare function AdminAction(options
|
|
91
|
+
export declare function AdminAction<I extends object>(options: AdminActionOptions & {
|
|
92
|
+
target: 'resource';
|
|
93
|
+
input: new (...args: any[]) => I;
|
|
94
|
+
choices?: {
|
|
95
|
+
[K in keyof I & string]?: string;
|
|
96
|
+
};
|
|
97
|
+
}): TypedMethodDecorator<(input: I, ctx: AdminContext) => Awaitable<ActionReturn>>;
|
|
98
|
+
export declare function AdminAction(options: AdminActionOptions & {
|
|
99
|
+
target: 'resource';
|
|
100
|
+
}): TypedMethodDecorator<(input: any, ctx: AdminContext) => Awaitable<ActionReturn>>;
|
|
101
|
+
export declare function AdminAction<I extends object>(options: AdminActionOptions & {
|
|
102
|
+
target?: 'record';
|
|
103
|
+
input: new (...args: any[]) => I;
|
|
104
|
+
choices?: {
|
|
105
|
+
[K in keyof I & string]?: string;
|
|
106
|
+
};
|
|
107
|
+
}): RecordMethodDecorator<[input: I, ctx: AdminContext], Awaitable<ActionReturn>>;
|
|
108
|
+
export declare function AdminAction(options?: AdminActionOptions & {
|
|
109
|
+
target?: 'record';
|
|
110
|
+
}): RecordMethodDecorator<[input: any, ctx: AdminContext], Awaitable<ActionReturn>>;
|
|
111
|
+
export declare function AdminAction(options?: AdminActionOptions): TypedMethodDecorator<(...args: any[]) => Awaitable<ActionReturn>>;
|
|
78
112
|
/** The actions declared on a resource class (inherited ones first), by name. */
|
|
79
113
|
export declare function getActions(resourceClass: Function): Map<string, ActionDefinition>;
|
|
80
114
|
/**
|
|
81
115
|
* Boot-time checks of a resource class's actions and of its `@AdminCan` names; returns the actions ready to run.
|
|
82
|
-
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over
|
|
116
|
+
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over; `row` is the class of
|
|
117
|
+
* the records (the entity, or a source's row), checked against a record action's first parameter.
|
|
118
|
+
*
|
|
119
|
+
* The method's parameter types (when the build emits them: tsc, SWC, Bun; not esbuild or Vite) are checked against the
|
|
120
|
+
* action: `input` must be the class of its input parameter, and an action without `input` takes it from that parameter.
|
|
83
121
|
*/
|
|
84
|
-
export declare function resolveActions(resourceClass: Function, reserved: readonly string[], fail: (message: string) => never): Map<string, RegisteredAction>;
|
|
122
|
+
export declare function resolveActions(resourceClass: Function, reserved: readonly string[], fail: (message: string) => never, row?: Function): Map<string, RegisteredAction>;
|
|
85
123
|
/** The action as one request gets it, texts through `text` (keys `actions.<name>.…` of the resource). */
|
|
86
124
|
export declare function toActionSchema(action: RegisteredAction, text: ScopedText): ActionSchema;
|
|
@@ -1,17 +1,11 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
import { ADMIN_ACTIONS_METADATA } from '../constants.js';
|
|
3
3
|
import { buildDtoForm, localizeDtoForm } from '../schema/dto-form.js';
|
|
4
|
+
import { dtoPropertyNames } from '../schema/dto-fields.js';
|
|
5
|
+
import { describeValue, HostContractError, isLocalizedText } from '../host-contract.js';
|
|
4
6
|
import { humanize } from '../schema/humanize.js';
|
|
5
7
|
import { didYouMean } from '../schema/suggest.js';
|
|
6
8
|
import { getCanRuleNames } from './admin-scope.js';
|
|
7
|
-
/**
|
|
8
|
-
* A custom action of a resource (spec §5.2): a button on a record, on a list selection (`bulk`) or on the list
|
|
9
|
-
* (`target: 'resource'`). The method name is the action's name; running it needs `{resource}.action.{name}`, and for
|
|
10
|
-
* record actions `{resource}.update`, the user's row scopes and any `@AdminCan('<name>')` rule. It runs inside the
|
|
11
|
-
* admin's write transaction (`ctx.manager`), unless the admin runs with `transactions: false`: then nothing a method
|
|
12
|
-
* wrote is undone when it throws, and `atomic` actions are refused at boot. Throw an `HttpException` (or
|
|
13
|
-
* `AdminFieldError` for input fields) to refuse.
|
|
14
|
-
*/
|
|
15
9
|
export function AdminAction(options = {}) {
|
|
16
10
|
return (target, propertyKey) => {
|
|
17
11
|
if (typeof propertyKey !== 'string')
|
|
@@ -33,7 +27,19 @@ const UPLOAD_WIDGETS = ['file', 'image', 'richtext'];
|
|
|
33
27
|
* Boot-time checks of a resource class's actions and of its `@AdminCan` names; returns the actions ready to run.
|
|
34
28
|
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over.
|
|
35
29
|
*/
|
|
36
|
-
|
|
30
|
+
/** A class the method's parameter was declared as (emitted with `emitDecoratorMetadata`); not `Object` (an interface, `any`) or a built-in. */
|
|
31
|
+
const BUILT_INS = [Object, String, Number, Boolean, Array, Promise, Function, Date, Map, Set];
|
|
32
|
+
const declaredClass = (type) => (typeof type === 'function' && !BUILT_INS.includes(type) ? type : undefined);
|
|
33
|
+
const related = (a, b) => a === b || a.prototype instanceof b || b.prototype instanceof a;
|
|
34
|
+
/**
|
|
35
|
+
* Boot-time checks of a resource class's actions and of its `@AdminCan` names; returns the actions ready to run.
|
|
36
|
+
* `reserved` are the method names of `AdminResourceBase`, which an action must not take over; `row` is the class of
|
|
37
|
+
* the records (the entity, or a source's row), checked against a record action's first parameter.
|
|
38
|
+
*
|
|
39
|
+
* The method's parameter types (when the build emits them: tsc, SWC, Bun; not esbuild or Vite) are checked against the
|
|
40
|
+
* action: `input` must be the class of its input parameter, and an action without `input` takes it from that parameter.
|
|
41
|
+
*/
|
|
42
|
+
export function resolveActions(resourceClass, reserved, fail, row) {
|
|
37
43
|
const actions = new Map();
|
|
38
44
|
for (const definition of getActions(resourceClass).values()) {
|
|
39
45
|
const { name } = definition;
|
|
@@ -56,7 +62,30 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
56
62
|
fail(`${where}: \`bulk\` and \`atomic\` are for record actions`);
|
|
57
63
|
if (atomic && !bulk)
|
|
58
64
|
fail(`${where}: \`atomic\` needs \`bulk: true\``);
|
|
59
|
-
const { confirm,
|
|
65
|
+
const { confirm, icon, label } = definition;
|
|
66
|
+
const noInput = definition.input === false;
|
|
67
|
+
let input = definition.input === false ? undefined : definition.input;
|
|
68
|
+
const params = Reflect.getMetadata('design:paramtypes', resourceClass.prototype, name);
|
|
69
|
+
const method = resourceClass.prototype[name];
|
|
70
|
+
const takesInput = typeof method === 'function' && method.length > (target === 'record' ? 1 : 0);
|
|
71
|
+
if (params === undefined && input === undefined && !noInput && takesInput) {
|
|
72
|
+
fail(`${where}: the method takes an input parameter, but its type cannot be read (emitDecoratorMetadata is off, or the build drops it: esbuild, Vite, tsx); set \`input\` to its DTO class, or \`input: false\` if it takes none`);
|
|
73
|
+
}
|
|
74
|
+
const recordParam = target === 'record' ? declaredClass(params?.[0]) : undefined;
|
|
75
|
+
if (recordParam && row && !related(recordParam, row))
|
|
76
|
+
fail(`${where}: the method's first parameter is ${recordParam.name}, but the action runs on ${row.name} records`);
|
|
77
|
+
const inputParam = declaredClass(params?.[target === 'record' ? 1 : 0]);
|
|
78
|
+
const inputLike = inputParam !== undefined && inputParam !== row && dtoPropertyNames(inputParam).length > 0;
|
|
79
|
+
if (input !== undefined && typeof input === 'function' && inputParam && inputParam !== input && !(input.prototype instanceof inputParam)) {
|
|
80
|
+
fail(`${where}: \`input\` is ${input.name} but the method's input parameter is ${inputParam.name}; use the same class (or leave \`input\` out to take the parameter's)`);
|
|
81
|
+
}
|
|
82
|
+
if (noInput && inputLike)
|
|
83
|
+
fail(`${where}: \`input: false\`, but the method's input parameter is ${inputParam.name}`);
|
|
84
|
+
if (input === undefined && !noInput && inputLike) {
|
|
85
|
+
if (definition.primary === true)
|
|
86
|
+
fail(`${where}: a primary action runs in one click and takes no input, but the method's input parameter is ${inputParam.name}`);
|
|
87
|
+
input = inputParam;
|
|
88
|
+
}
|
|
60
89
|
if (confirm !== undefined && typeof confirm !== 'boolean' && !isText(confirm))
|
|
61
90
|
fail(`${where}: confirm must be true, false or a text`);
|
|
62
91
|
const perRecord = typeof label === 'object' && label !== null && 'for' in label;
|
|
@@ -77,6 +106,7 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
77
106
|
if (icon !== undefined && typeof icon !== 'string')
|
|
78
107
|
fail(`${where}: icon must be an icon name`);
|
|
79
108
|
let form;
|
|
109
|
+
let choices;
|
|
80
110
|
if (input !== undefined) {
|
|
81
111
|
if (typeof input !== 'function')
|
|
82
112
|
fail(`${where}: input must be a DTO class`);
|
|
@@ -87,10 +117,28 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
87
117
|
fail(`${where}: input field "${field}" uses the "${options.widget}" widget; action inputs cannot take files or rich text`);
|
|
88
118
|
}
|
|
89
119
|
}
|
|
120
|
+
if (definition.choices !== undefined) {
|
|
121
|
+
if (typeof definition.choices !== 'object' || definition.choices === null || Array.isArray(definition.choices))
|
|
122
|
+
fail(`${where}: choices must be { field: 'methodName' }`);
|
|
123
|
+
if (!form)
|
|
124
|
+
fail(`${where}: choices need an input form`);
|
|
125
|
+
choices = new Map();
|
|
126
|
+
for (const [field, method] of Object.entries(definition.choices)) {
|
|
127
|
+
const schema = form.fields.find((candidate) => candidate.name === field);
|
|
128
|
+
if (!schema)
|
|
129
|
+
fail(`${where}: choices: unknown input field "${field}"${didYouMean(field, form.fields.map((candidate) => candidate.name))}`);
|
|
130
|
+
if (schema.type !== 'string' && schema.type !== 'number' && schema.type !== 'enum')
|
|
131
|
+
fail(`${where}: choices: "${field}" is a ${schema.type} field; choices are for text and number fields`);
|
|
132
|
+
if (typeof method !== 'string' || typeof resourceClass.prototype[method] !== 'function') {
|
|
133
|
+
fail(`${where}: choices: "${field}" names ${typeof method === 'string' ? `"${method}", which is not a method of ${resourceClass.name}` : 'no method'}; give the name of a method (ctx) => choices`);
|
|
134
|
+
}
|
|
135
|
+
choices.set(field, method);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
90
138
|
actions.set(name, {
|
|
91
139
|
name,
|
|
92
140
|
label: perRecord ? label.static : (label ?? humanize(name)),
|
|
93
|
-
...(perRecord ? { labelFor: label.for } : {}),
|
|
141
|
+
...(perRecord ? { labelFor: checkedLabelFor(`${resourceClass.name} @AdminAction "${name}" label.for`, label.for) } : {}),
|
|
94
142
|
primary,
|
|
95
143
|
target,
|
|
96
144
|
bulk,
|
|
@@ -99,6 +147,7 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
99
147
|
variant,
|
|
100
148
|
...(icon ? { icon } : {}),
|
|
101
149
|
...(input ? { input, form } : {}),
|
|
150
|
+
...(choices ? { choices } : {}),
|
|
102
151
|
});
|
|
103
152
|
}
|
|
104
153
|
const primaries = [...actions.values()].filter((action) => action.primary);
|
|
@@ -118,9 +167,7 @@ export function resolveActions(resourceClass, reserved, fail) {
|
|
|
118
167
|
return actions;
|
|
119
168
|
}
|
|
120
169
|
function isText(value) {
|
|
121
|
-
|
|
122
|
-
return true;
|
|
123
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.values(value).every((text) => typeof text === 'string');
|
|
170
|
+
return isLocalizedText(value);
|
|
124
171
|
}
|
|
125
172
|
/** The action as one request gets it, texts through `text` (keys `actions.<name>.…` of the resource). */
|
|
126
173
|
export function toActionSchema(action, text) {
|
|
@@ -136,7 +183,22 @@ export function toActionSchema(action, text) {
|
|
|
136
183
|
variant: action.variant,
|
|
137
184
|
...(action.primary ? { primary: true } : {}),
|
|
138
185
|
...(action.icon ? { icon: action.icon } : {}),
|
|
139
|
-
...(action.form ? { input: localizeDtoForm(action.form, (value, path) => text(value, `${at}.fields.${path}`)) } : {}),
|
|
186
|
+
...(action.form ? { input: withChoices(localizeDtoForm(action.form, (value, path) => text(value, `${at}.fields.${path}`)), action.choices) } : {}),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/** Marks the fields whose options come from `GET …/actions/:action/choices/:field`. */
|
|
190
|
+
function withChoices(form, choices) {
|
|
191
|
+
if (!choices)
|
|
192
|
+
return form;
|
|
193
|
+
return { ...form, fields: form.fields.map((field) => (choices.has(field.name) ? { ...field, choices: true } : field)) };
|
|
194
|
+
}
|
|
195
|
+
/** `label.for` as called: a text, or `null` (not on this record); anything else (a Promise of an `async` one) fails loudly. */
|
|
196
|
+
function checkedLabelFor(where, labelFor) {
|
|
197
|
+
return (record) => {
|
|
198
|
+
const value = labelFor(record);
|
|
199
|
+
if (value !== null && !isLocalizedText(value))
|
|
200
|
+
throw new HostContractError(`${where} returned ${describeValue(value)}; it answers at once with a text, or null where the action does not apply (it cannot be async)`);
|
|
201
|
+
return value;
|
|
140
202
|
};
|
|
141
203
|
}
|
|
142
204
|
//# sourceMappingURL=admin-action.js.map
|
|
@@ -2,6 +2,9 @@ import 'reflect-metadata';
|
|
|
2
2
|
import type { PrintSchema } from '../contract.js';
|
|
3
3
|
import { type LocalizedText } from '../i18n/localized-text.js';
|
|
4
4
|
import type { ScopedText } from '../i18n/texts.js';
|
|
5
|
+
import type { HtmlString } from '../print/html.js';
|
|
6
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
7
|
+
import type { Awaitable, RowOf } from './typed.js';
|
|
5
8
|
/** Paper sizes by name; any other string is used as the CSS `@page { size }` value. */
|
|
6
9
|
export declare const PAPERS: Record<string, string>;
|
|
7
10
|
export interface AdminPrintOptions {
|
|
@@ -28,7 +31,7 @@ export interface RegisteredPrint {
|
|
|
28
31
|
* wraps it in a page sized for `paper` that prints itself. Printing needs `{resource}.view`, the user's row scopes and
|
|
29
32
|
* `{resource}.print.{name}`; each printed record is written to the audit log. Throw an `HttpException` to refuse.
|
|
30
33
|
*/
|
|
31
|
-
export declare function AdminPrint(options?: AdminPrintOptions):
|
|
34
|
+
export declare function AdminPrint(options?: AdminPrintOptions): <P extends object, T extends (records: Array<RowOf<P>>, ctx: AdminContext) => Awaitable<HtmlString>>(target: P, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => void;
|
|
32
35
|
/** Boot checks of a resource class's print templates; `taken` are names already in use (base methods, actions). */
|
|
33
36
|
export declare function resolvePrints(resourceClass: Function, taken: readonly string[], fail: (message: string) => never): Map<string, RegisteredPrint>;
|
|
34
37
|
/** The permission code of a print template. */
|
|
@@ -3,12 +3,6 @@ import { ADMIN_PRINTS_METADATA } from '../constants.js';
|
|
|
3
3
|
import { humanize } from '../schema/humanize.js';
|
|
4
4
|
/** Paper sizes by name; any other string is used as the CSS `@page { size }` value. */
|
|
5
5
|
export const PAPERS = { A4: 'A4', A5: 'A5', label: '100mm 150mm' };
|
|
6
|
-
/**
|
|
7
|
-
* A print template of a resource (an invoice, a shipping label): the method `(records, ctx)` returns the body HTML of
|
|
8
|
-
* the printed page, one or more records (`bulk`). Build it with the `html` tag, which escapes every value. The admin
|
|
9
|
-
* wraps it in a page sized for `paper` that prints itself. Printing needs `{resource}.view`, the user's row scopes and
|
|
10
|
-
* `{resource}.print.{name}`; each printed record is written to the audit log. Throw an `HttpException` to refuse.
|
|
11
|
-
*/
|
|
12
6
|
export function AdminPrint(options = {}) {
|
|
13
7
|
return (target, propertyKey) => {
|
|
14
8
|
if (typeof propertyKey !== 'string')
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
|
+
import type { ObjectLiteral } from 'typeorm';
|
|
3
|
+
import type { AdminResourceBase } from '../resource/admin-resource-base.js';
|
|
4
|
+
import type { AdminSourceBase } from '../resource/admin-source-base.js';
|
|
5
|
+
import type { TypedClassDecorator } from './typed.js';
|
|
2
6
|
import type { LocalizedText } from '../i18n/localized-text.js';
|
|
3
7
|
import type { TitleDefinition } from '../schema/titles.js';
|
|
4
8
|
export interface AdminResourceOptions {
|
|
@@ -55,7 +59,7 @@ export interface AdminSourceOptions extends Omit<AdminResourceOptions, 'dataSour
|
|
|
55
59
|
* extends AdminSourceBase and answers `findMany`/`findOne` (and `create`/`update`/`delete` when it allows them).
|
|
56
60
|
* `row` is a class whose class-validator decorators describe a row's fields, like an action's input DTO.
|
|
57
61
|
*/
|
|
58
|
-
export declare function AdminSource(row:
|
|
62
|
+
export declare function AdminSource<R extends ObjectLiteral>(row: abstract new (...args: any[]) => R, options?: AdminSourceOptions): TypedClassDecorator<AdminSourceBase<R, any>>;
|
|
59
63
|
/** Marks a provider as an admin resource for `entity`. The class must extend AdminResourceBase. */
|
|
60
|
-
export declare function AdminResource(entity:
|
|
64
|
+
export declare function AdminResource<E extends ObjectLiteral>(entity: abstract new (...args: any[]) => E, options?: AdminResourceOptions): TypedClassDecorator<AdminResourceBase<E, any>>;
|
|
61
65
|
export declare function getAdminResourceDefinition(target: Function): AdminResourceDefinition | undefined;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
import type { WhereExpressionBuilder } from 'typeorm';
|
|
3
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
4
|
+
import type { RecordMethodDecorator, TypedMethodDecorator } from './typed.js';
|
|
3
5
|
/**
|
|
4
6
|
* What a scope returns: a column map (`{ ownerId: ctx.user.id }`; an array means IN, null means IS NULL), or a
|
|
5
7
|
* callback that adds conditions for anything else (`(where, alias) => where.where(`${alias}.total > 0`)`).
|
|
@@ -9,7 +11,7 @@ export type ScopeCondition = Record<string, unknown> | ((where: WhereExpressionB
|
|
|
9
11
|
* A named row scope (spec §6.4): `@AdminScope('own') own(ctx) { return { ownerId: ctx.user.id }; }`. Roles assign
|
|
10
12
|
* scopes per resource and operation; the method runs per request and must not throw for a normal user.
|
|
11
13
|
*/
|
|
12
|
-
export declare function AdminScope(name: string):
|
|
14
|
+
export declare function AdminScope(name: string): TypedMethodDecorator<(ctx: AdminContext) => ScopeCondition>;
|
|
13
15
|
export declare function getScopes(target: Function): Record<string, string | symbol>;
|
|
14
16
|
export type RecordOperation = 'update' | 'delete';
|
|
15
17
|
/**
|
|
@@ -18,7 +20,8 @@ export type RecordOperation = 'update' | 'delete';
|
|
|
18
20
|
* (`@AdminCan('ship')`) rules that action the same way: `_perm.actions` lists it only where the rule agrees, and
|
|
19
21
|
* running it elsewhere is a 403. Any other name fails at boot.
|
|
20
22
|
*/
|
|
21
|
-
export declare function AdminCan(operation:
|
|
23
|
+
export declare function AdminCan(operation: 'create'): TypedMethodDecorator<(parent: any, ctx: AdminContext) => boolean>;
|
|
24
|
+
export declare function AdminCan(operation: RecordOperation | (string & {})): RecordMethodDecorator<[ctx: AdminContext], boolean>;
|
|
22
25
|
/** The rule methods for an operation (`update`, `delete`) or a record action's name. */
|
|
23
26
|
export declare function getCanRules(target: Function, operation: string): Array<string | symbol>;
|
|
24
27
|
/** Every name the class has `@AdminCan` rules for. */
|
|
@@ -14,12 +14,6 @@ export function AdminScope(name) {
|
|
|
14
14
|
export function getScopes(target) {
|
|
15
15
|
return Reflect.getMetadata(ADMIN_SCOPES_METADATA, target) ?? {};
|
|
16
16
|
}
|
|
17
|
-
/**
|
|
18
|
-
* A per-record rule (spec §6.3): `@AdminCan('update') canEdit(record, ctx) { return record.status === 'draft'; }`.
|
|
19
|
-
* Records carry the answer in `_perm`; PATCH and DELETE re-check it (403). The name of a record `@AdminAction`
|
|
20
|
-
* (`@AdminCan('ship')`) rules that action the same way: `_perm.actions` lists it only where the rule agrees, and
|
|
21
|
-
* running it elsewhere is a 403. Any other name fails at boot.
|
|
22
|
-
*/
|
|
23
17
|
export function AdminCan(operation) {
|
|
24
18
|
return (target, propertyKey) => {
|
|
25
19
|
const owner = target.constructor;
|
|
@@ -3,6 +3,7 @@ import type { LocalizedText } from '../i18n/localized-text.js';
|
|
|
3
3
|
import type { AdminContext } from '../resource/admin-context.js';
|
|
4
4
|
import type { LayoutConfig } from '../schema/field-config.js';
|
|
5
5
|
import type { AdminFieldOptions } from './admin-field.js';
|
|
6
|
+
import type { TypedClassDecorator } from './typed.js';
|
|
6
7
|
export interface AdminSettingsPageOptions<T extends object = any> {
|
|
7
8
|
/** `'Payments'` or `{ en: 'Payments', fa: 'پرداخت' }`. Defaults to the humanized page name. */
|
|
8
9
|
label?: LocalizedText;
|
|
@@ -63,5 +64,5 @@ export interface AdminSettingsPageDefinition extends AdminSettingsPageOptions {
|
|
|
63
64
|
* `save` (`AdminSettingsSource`). Viewing it needs `page.<name>`, saving `page.<name>.update`. The name is letters,
|
|
64
65
|
* digits, `-` and `_`, and not the name of a resource.
|
|
65
66
|
*/
|
|
66
|
-
export declare function AdminSettingsPage<T extends object>(name: string, options: AdminSettingsPageOptions<T>):
|
|
67
|
+
export declare function AdminSettingsPage<T extends object>(name: string, options: AdminSettingsPageOptions<T>): TypedClassDecorator<AdminSettingsSource<T>>;
|
|
67
68
|
export declare function getAdminSettingsPageDefinition(target: Function): AdminSettingsPageDefinition | undefined;
|
|
@@ -2,6 +2,7 @@ import 'reflect-metadata';
|
|
|
2
2
|
import type { WidgetData, WidgetParams, WidgetType } from '../contract.js';
|
|
3
3
|
import type { LocalizedText } from '../i18n/localized-text.js';
|
|
4
4
|
import type { AdminContext } from '../resource/admin-context.js';
|
|
5
|
+
import type { TypedClassDecorator } from './typed.js';
|
|
5
6
|
export interface AdminWidgetOptions {
|
|
6
7
|
type: WidgetType;
|
|
7
8
|
title: LocalizedText;
|
|
@@ -23,5 +24,5 @@ export interface AdminWidgetDefinition extends AdminWidgetOptions {
|
|
|
23
24
|
name: string;
|
|
24
25
|
}
|
|
25
26
|
/** A dashboard widget: a provider whose `load` answers its data. The dashboard replaces the home page once one exists. */
|
|
26
|
-
export declare function AdminWidget(name: string, options: AdminWidgetOptions):
|
|
27
|
+
export declare function AdminWidget(name: string, options: AdminWidgetOptions): TypedClassDecorator<AdminWidgetSource>;
|
|
27
28
|
export declare function getAdminWidgetDefinition(target: Function): AdminWidgetDefinition | undefined;
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
3
|
+
import type { ReturnsNothing, RowOf } from './typed.js';
|
|
2
4
|
export type HookKind = 'beforeSave' | 'afterSave' | 'beforeDelete';
|
|
3
5
|
export type SaveMode = 'create' | 'update';
|
|
4
6
|
/** `soft`: moved to the trash (@DeleteDateColumn); `hard`: the row is removed (no trash, or a purge). */
|
|
5
7
|
export type DeleteMode = 'soft' | 'hard';
|
|
6
|
-
/** `(
|
|
7
|
-
|
|
8
|
-
/** `(
|
|
9
|
-
export declare const
|
|
10
|
-
/** `(entity, ctx, mode
|
|
11
|
-
export declare const
|
|
8
|
+
/** A hook decorator: the method takes `(first, ctx, mode)` and returns nothing (sync or async). */
|
|
9
|
+
type HookDecorator<First, Mode> = <P extends object, T extends (first: First extends 'row' ? RowOf<P> : any, ctx: AdminContext, mode: Mode) => unknown>(target: P, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T> & ReturnsNothing<T>) => void;
|
|
10
|
+
/** `(dto, ctx, mode)` — runs before the default create/update saves; may mutate `dto`. Returns nothing. */
|
|
11
|
+
export declare const BeforeSave: () => HookDecorator<'dto', SaveMode>;
|
|
12
|
+
/** `(entity, ctx, mode)` — runs after the default create/update saved. Returns nothing. */
|
|
13
|
+
export declare const AfterSave: () => HookDecorator<'row', SaveMode>;
|
|
14
|
+
/** `(entity, ctx, mode: DeleteMode)` — runs before the default delete and purge; throw to refuse. Returns nothing. */
|
|
15
|
+
export declare const BeforeDelete: () => HookDecorator<'row', DeleteMode>;
|
|
12
16
|
export declare function getHooks(target: Function, kind: HookKind): Array<string | symbol>;
|
|
17
|
+
export {};
|
package/dist/decorators/hooks.js
CHANGED
|
@@ -15,11 +15,11 @@ function hook(kind) {
|
|
|
15
15
|
Reflect.defineMetadata(ADMIN_HOOKS_METADATA, table, owner);
|
|
16
16
|
};
|
|
17
17
|
}
|
|
18
|
-
/** `(dto, ctx, mode)` — runs before the default create/update saves; may mutate `dto`. */
|
|
18
|
+
/** `(dto, ctx, mode)` — runs before the default create/update saves; may mutate `dto`. Returns nothing. */
|
|
19
19
|
export const BeforeSave = () => hook('beforeSave');
|
|
20
|
-
/** `(entity, ctx, mode)` — runs after the default create/update saved. */
|
|
20
|
+
/** `(entity, ctx, mode)` — runs after the default create/update saved. Returns nothing. */
|
|
21
21
|
export const AfterSave = () => hook('afterSave');
|
|
22
|
-
/** `(entity, ctx, mode: DeleteMode)` — runs before the default delete and purge; throw to refuse. */
|
|
22
|
+
/** `(entity, ctx, mode: DeleteMode)` — runs before the default delete and purge; throw to refuse. Returns nothing. */
|
|
23
23
|
export const BeforeDelete = () => hook('beforeDelete');
|
|
24
24
|
export function getHooks(target, kind) {
|
|
25
25
|
return Reflect.getMetadata(ADMIN_HOOKS_METADATA, target)?.[kind] ?? [];
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { AdminContext } from '../resource/admin-context.js';
|
|
2
|
+
import type { AdminResourceBase } from '../resource/admin-resource-base.js';
|
|
3
|
+
/** A value or a Promise of it. */
|
|
4
|
+
export type Awaitable<T> = T | Promise<T>;
|
|
5
|
+
/**
|
|
6
|
+
* A method decorator that only accepts methods of the signature `M`: decorating a method that takes or returns
|
|
7
|
+
* something else is a compile error, at the decorator.
|
|
8
|
+
*/
|
|
9
|
+
export type TypedMethodDecorator<M> = <T extends M>(target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => void;
|
|
10
|
+
/** A class decorator that only accepts classes whose instances are `I`. */
|
|
11
|
+
export type TypedClassDecorator<I> = <C extends abstract new (...args: any[]) => I>(target: C) => void;
|
|
12
|
+
/** The row type of a resource class (`AdminResourceBase<Order>` → `Order`); `any` outside one. */
|
|
13
|
+
export type RowOf<P> = P extends AdminResourceBase<infer T, any> ? T : any;
|
|
14
|
+
/** Refuses (at compile time) a method that returns a value where nothing is read. */
|
|
15
|
+
export type ReturnsNothing<M> = M extends (...args: any[]) => infer R ? [Awaited<R>] extends [void | undefined] ? unknown : {
|
|
16
|
+
'nest-my-admin: this method must return nothing (its value would be ignored)': never;
|
|
17
|
+
} : unknown;
|
|
18
|
+
/** A method of a resource whose first parameter is one of its rows. */
|
|
19
|
+
export type RecordMethodDecorator<Rest extends unknown[], R> = <P extends object, T extends (record: RowOf<P>, ...rest: Rest) => R>(target: P, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => void;
|
|
20
|
+
export type { AdminContext };
|
package/dist/files/file-owner.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { parseRecordId, recordIdOf } from '../crud/record-id.js';
|
|
2
2
|
import { AdminBadRequestError, AdminForbiddenError, AdminNotFoundError, AdminValidationError } from '../errors.js';
|
|
3
|
+
import { checkFoundRecord } from '../host-contract.js';
|
|
3
4
|
/** A resource as the owner of its records' files: permissions, field levels and row scopes decide. */
|
|
4
5
|
export function resourceFileOwner(entry, policy) {
|
|
5
6
|
const { name } = entry.schema;
|
|
@@ -30,7 +31,7 @@ export function resourceFileOwner(entry, policy) {
|
|
|
30
31
|
return undefined;
|
|
31
32
|
try {
|
|
32
33
|
const id = parseRecordId(recordId, entry.schema);
|
|
33
|
-
const entity = await entry.resource.findOne(id, ctx);
|
|
34
|
+
const entity = checkFoundRecord(await entry.resource.findOne(id, ctx), `${entry.resource.constructor.name}.findOne()`);
|
|
34
35
|
if (!entity)
|
|
35
36
|
return undefined;
|
|
36
37
|
await policy.requireInScope(entry, id, recordId, 'view', ctx); // a findOne override may ignore scopes
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime checks of what host code returns where the admin needs a particular shape (spec: «fail loudly»): a wrong
|
|
3
|
+
* value is a programming error, so it fails the request with a sentence naming the method and what it returned,
|
|
4
|
+
* instead of being misread (an `async` scope read as «no restriction»).
|
|
5
|
+
*/
|
|
6
|
+
/** A Promise or any other thenable. */
|
|
7
|
+
export declare const isThenable: (value: unknown) => value is PromiseLike<unknown>;
|
|
8
|
+
/** A short description of a value for an error message: `a Promise`, `an array`, `the string "x"`, `undefined`. */
|
|
9
|
+
export declare function describeValue(value: unknown): string;
|
|
10
|
+
/** Host code broke its contract: a 500 whose message (logged with the correlation id) says what to fix. */
|
|
11
|
+
export declare class HostContractError extends Error {
|
|
12
|
+
constructor(message: string);
|
|
13
|
+
}
|
|
14
|
+
export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
|
|
15
|
+
/** What `findMany` must answer: `{ items: [...], total: number | null }` (and the optional paging fields). */
|
|
16
|
+
export declare function checkFindMany<T>(found: T, where: string): T;
|
|
17
|
+
/** A text: a string, or a plain object of strings by locale (`{ en, fa }`), never a Promise or a class instance. */
|
|
18
|
+
export declare const isLocalizedText: (value: unknown) => boolean;
|
|
19
|
+
/** What `query()` and `relationOptions()` hand back: the query builder, never a Promise of it or nothing. */
|
|
20
|
+
export declare function checkQueryBuilder<Q>(value: Q, where: string): Q;
|
|
21
|
+
/** A list of strings (`resolveRoles`), or nothing. */
|
|
22
|
+
export declare function checkStringList(value: unknown, where: string): string[];
|
|
23
|
+
/** A record a write method answered: an object, or nothing (the admin then reloads it). */
|
|
24
|
+
export declare function checkWriteResult(value: unknown, where: string): unknown;
|
|
25
|
+
/** A record `findOne`/`getUser` answered: an object, or null. */
|
|
26
|
+
export declare function checkFoundRecord<T>(value: T, where: string): T;
|
|
27
|
+
/** A yes/no answer given at once. */
|
|
28
|
+
export declare function checkBoolean(value: unknown, where: string): boolean;
|
|
29
|
+
/** An object of values: a plain object or a class instance, never an array or a Promise. */
|
|
30
|
+
export declare const isRecordObject: (value: unknown) => value is Record<string, unknown>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime checks of what host code returns where the admin needs a particular shape (spec: «fail loudly»): a wrong
|
|
3
|
+
* value is a programming error, so it fails the request with a sentence naming the method and what it returned,
|
|
4
|
+
* instead of being misread (an `async` scope read as «no restriction»).
|
|
5
|
+
*/
|
|
6
|
+
/** A Promise or any other thenable. */
|
|
7
|
+
export const isThenable = (value) => (typeof value === 'object' || typeof value === 'function') && value !== null && typeof value.then === 'function';
|
|
8
|
+
/** A short description of a value for an error message: `a Promise`, `an array`, `the string "x"`, `undefined`. */
|
|
9
|
+
export function describeValue(value) {
|
|
10
|
+
if (value === undefined)
|
|
11
|
+
return 'undefined';
|
|
12
|
+
if (value === null)
|
|
13
|
+
return 'null';
|
|
14
|
+
if (isThenable(value))
|
|
15
|
+
return 'a Promise (is the method async?)';
|
|
16
|
+
if (Array.isArray(value))
|
|
17
|
+
return 'an array';
|
|
18
|
+
if (typeof value === 'string')
|
|
19
|
+
return `the string ${JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value)}`;
|
|
20
|
+
if (typeof value === 'function')
|
|
21
|
+
return 'a function';
|
|
22
|
+
if (typeof value === 'object') {
|
|
23
|
+
const name = value.constructor?.name;
|
|
24
|
+
return name && name !== 'Object' ? `a ${name}` : 'an object';
|
|
25
|
+
}
|
|
26
|
+
return `the ${typeof value} ${String(value)}`;
|
|
27
|
+
}
|
|
28
|
+
/** Host code broke its contract: a 500 whose message (logged with the correlation id) says what to fix. */
|
|
29
|
+
export class HostContractError extends Error {
|
|
30
|
+
constructor(message) {
|
|
31
|
+
super(`nest-my-admin: ${message}`);
|
|
32
|
+
this.name = 'HostContractError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export const isPlainObject = (value) => typeof value === 'object' && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
36
|
+
/** What `findMany` must answer: `{ items: [...], total: number | null }` (and the optional paging fields). */
|
|
37
|
+
export function checkFindMany(found, where) {
|
|
38
|
+
const value = found;
|
|
39
|
+
const fail = (what) => {
|
|
40
|
+
throw new HostContractError(`${where}.findMany() returned ${what}; it answers { items: [...], total: number | null } (inMemoryList(rows, params) builds that from an array)`);
|
|
41
|
+
};
|
|
42
|
+
if (!isPlainObject(value))
|
|
43
|
+
fail(describeValue(found));
|
|
44
|
+
if (!Array.isArray(value.items))
|
|
45
|
+
fail(`items that are ${describeValue(value.items)}`);
|
|
46
|
+
const total = value.total;
|
|
47
|
+
if (total !== null && total !== undefined && (typeof total !== 'number' || !Number.isFinite(total) || total < 0))
|
|
48
|
+
fail(`a total of ${describeValue(total)}`);
|
|
49
|
+
if (value.items.some((item) => typeof item !== "object" || item === null))
|
|
50
|
+
fail('items that are not all records (objects)');
|
|
51
|
+
return found;
|
|
52
|
+
}
|
|
53
|
+
/** A text: a string, or a plain object of strings by locale (`{ en, fa }`), never a Promise or a class instance. */
|
|
54
|
+
export const isLocalizedText = (value) => typeof value === 'string' || (isPlainObject(value) && Object.values(value).every((text) => typeof text === 'string'));
|
|
55
|
+
/** What `query()` and `relationOptions()` hand back: the query builder, never a Promise of it or nothing. */
|
|
56
|
+
export function checkQueryBuilder(value, where) {
|
|
57
|
+
// By shape, not instanceof: a host may resolve its own copy of typeorm.
|
|
58
|
+
const qb = value;
|
|
59
|
+
if (typeof qb === 'object' && qb !== null && typeof qb.andWhere === 'function' && typeof qb.getQuery === 'function')
|
|
60
|
+
return value;
|
|
61
|
+
throw new HostContractError(`${where} must return the query builder (add to the one it was given and return it), but it returned ${describeValue(value)}`);
|
|
62
|
+
}
|
|
63
|
+
/** A list of strings (`resolveRoles`), or nothing. */
|
|
64
|
+
export function checkStringList(value, where) {
|
|
65
|
+
if (value === undefined || value === null)
|
|
66
|
+
return [];
|
|
67
|
+
if (Array.isArray(value) && value.every((item) => typeof item === 'string'))
|
|
68
|
+
return value;
|
|
69
|
+
throw new HostContractError(`${where} must return an array of role names, but it returned ${describeValue(value)}`);
|
|
70
|
+
}
|
|
71
|
+
/** A record a write method answered: an object, or nothing (the admin then reloads it). */
|
|
72
|
+
export function checkWriteResult(value, where) {
|
|
73
|
+
if (value === undefined || value === null || (typeof value === 'object' && !Array.isArray(value) && !isThenable(value)))
|
|
74
|
+
return value;
|
|
75
|
+
throw new HostContractError(`${where} must return the saved record (or nothing, to have it reloaded), but it returned ${describeValue(value)}`);
|
|
76
|
+
}
|
|
77
|
+
/** A record `findOne`/`getUser` answered: an object, or null. */
|
|
78
|
+
export function checkFoundRecord(value, where) {
|
|
79
|
+
if (value === undefined || value === null || (typeof value === 'object' && !Array.isArray(value)))
|
|
80
|
+
return value;
|
|
81
|
+
throw new HostContractError(`${where} must return the record or null, but it returned ${describeValue(value)}`);
|
|
82
|
+
}
|
|
83
|
+
/** A yes/no answer given at once. */
|
|
84
|
+
export function checkBoolean(value, where) {
|
|
85
|
+
if (typeof value === 'boolean')
|
|
86
|
+
return value;
|
|
87
|
+
throw new HostContractError(`${where} must return true or false, but it returned ${describeValue(value)}`);
|
|
88
|
+
}
|
|
89
|
+
/** An object of values: a plain object or a class instance, never an array or a Promise. */
|
|
90
|
+
export const isRecordObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) && !isThenable(value);
|
|
91
|
+
//# sourceMappingURL=host-contract.js.map
|
|
@@ -263,6 +263,7 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
263
263
|
.add('POST', '/api/resources/:resource/bulk-delete', async ({ req, res, ctx }, p) => sendJson(res, 200, await this.api.bulkDelete(p.resource, await readJsonBody(req), ctx)))
|
|
264
264
|
.add('POST', '/api/resources/:resource/:id/restore', async ({ res, ctx }, p) => sendJson(res, 200, await this.api.restore(p.resource, p.id, ctx)))
|
|
265
265
|
// After the restore route: `restore` is not an action name, and a record whose id is "actions" stays restorable.
|
|
266
|
+
.add('GET', '/api/resources/:resource/actions/:action/choices/:field', async ({ res, ctx }, p) => sendJson(res, 200, await this.api.actionChoices(p.resource, p.action, p.field, ctx)))
|
|
266
267
|
.add('POST', '/api/resources/:resource/actions/:action', async ({ req, res, ctx }, p) => sendJson(res, 200, await this.api.runAction(p.resource, p.action, await readJsonBody(req), ctx)))
|
|
267
268
|
.add('DELETE', '/api/resources/:resource/:id', async ({ req, res, url, ctx }, p) => {
|
|
268
269
|
const purge = url.searchParams.get('purge');
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { BadRequestException, HttpException } from '@nestjs/common';
|
|
2
2
|
import { QueryFailedError } from 'typeorm';
|
|
3
3
|
import { AdminConflictError, AdminError } from '../errors.js';
|
|
4
|
+
import { describeValue } from '../host-contract.js';
|
|
4
5
|
/** Maps any thrown value to the admin error contract. Never leaks messages of 5xx/unknown errors. */
|
|
5
6
|
export function toErrorResponse(error, correlationId, logger, context = {}) {
|
|
6
7
|
const { errorMapper } = context;
|
|
@@ -13,6 +14,9 @@ export function toErrorResponse(error, correlationId, logger, context = {}) {
|
|
|
13
14
|
}
|
|
14
15
|
error = mapped;
|
|
15
16
|
}
|
|
17
|
+
else if (mapped !== undefined) {
|
|
18
|
+
logger.error(`[${correlationId}] nest-my-admin: errorMapper must return an AdminError (AdminFieldError, AdminConflictError…) or undefined, but it returned ${describeValue(mapped)}; the error is answered as unmapped`);
|
|
19
|
+
}
|
|
16
20
|
}
|
|
17
21
|
catch (mapperError) {
|
|
18
22
|
logger.error(`[${correlationId}] errorMapper threw: ${mapperError instanceof Error ? (mapperError.stack ?? mapperError.message) : String(mapperError)}`);
|