@nest-my-admin/core 0.9.0 → 0.10.3
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 +28 -1
- package/dist/api/action.service.d.ts +9 -1
- package/dist/api/action.service.js +50 -2
- package/dist/api/admin-api.service.d.ts +3 -1
- package/dist/api/admin-api.service.js +7 -1
- package/dist/contract.d.ts +13 -0
- package/dist/decorators/admin-action.d.ts +14 -0
- package/dist/decorators/admin-action.js +27 -1
- package/dist/decorators/admin-resource.d.ts +2 -0
- package/dist/http/admin-http.server.js +1 -0
- package/dist/inlines/inline-config.js +1 -0
- package/dist/inlines/inline-writer.js +24 -3
- package/dist/resource/admin-resource-base.d.ts +7 -0
- package/dist/resource/admin-resource-base.js +5 -0
- package/dist/schema/build-resource-schema.js +2 -1
- package/dist/schema/field-config.d.ts +2 -0
- package/dist/schema/field-config.js +2 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -537,6 +537,13 @@ export class OrderAdmin extends AdminResourceBase<Order> {
|
|
|
537
537
|
- **Selections.** A bulk action runs on up to 100 records.
|
|
538
538
|
- By default each record gets its own transaction: the answer is `{ ok, failed: [{ id, code, message }], message? }`, and one failure does not stop the others. The list shows how many ran and why the others did not.
|
|
539
539
|
- `atomic: true` runs them all in one transaction: every record is checked first, and one failure is the answer, with nothing applied. It needs the admin's transactions (boot fails with `transactions: false`). The confirmation says "all or nothing".
|
|
540
|
+
- **A dropdown from live data.** `choices: { field: 'methodName' }` turns an input field into a dropdown whose options a method of the resource gives when the dialog opens: the branches of a repository, the services a provider offers today.
|
|
541
|
+
```ts
|
|
542
|
+
@AdminAction({ target: 'resource', input: DeployDto, choices: { backendRef: 'backendBranches' } })
|
|
543
|
+
async deploy(input: DeployDto) { … }
|
|
544
|
+
async backendBranches(ctx: AdminContext) { return this.github.branches('api'); } // strings, or { value, label }
|
|
545
|
+
```
|
|
546
|
+
The method runs for whoever may run the action (`GET …/actions/:action/choices/:field`), sync or async. A run reads the choices again and refuses a value that is not one of them (422 on the field). The field keeps its `default` while the list loads. Field names are checked against `input` by the types and at boot, and the method must exist.
|
|
540
547
|
- **Picking a record.** `@AdminField({ pickFrom: 'categoryId' })` on an input property shows the same picker as the resource's own relation field `categoryId`; the property receives the chosen id (validate it with `@IsInt()`, and check it exists in the method).
|
|
541
548
|
- **Refusing.** Throw from the method:
|
|
542
549
|
- an `HttpException` below 500 answers with its status and message (409 is `CONFLICT`, 400 is `BUSINESS_RULE`), and the UI shows the message;
|
|
@@ -761,7 +768,7 @@ AdminModule.forRoot({
|
|
|
761
768
|
- Five wrong passwords lock an account for 15 minutes. Sign-in attempts are limited to 20 per minute per IP, with 429 and `Retry-After`.
|
|
762
769
|
- Unknown users, wrong passwords and locked accounts get the same answer.
|
|
763
770
|
- The account page changes the password (which signs out every other session), lists signed-in devices, and signs out one or all others.
|
|
764
|
-
- **Two-factor sign-in** (TOTP, any authenticator app). A user turns it on from the account page by scanning a QR code and confirming a code, and gets 10 one-time recovery codes. After the password, sign-in answers 401 `TWO_FACTOR_REQUIRED` until the request also carries `otp` (a code or a recovery code). Each code works once, wrong codes count toward the lockout, and turning it on signs out every other session. Turning it off or issuing new recovery codes needs the password; an admin can reset a lost second factor from the Users page. Set `secretKey` (32 bytes, base64: `openssl rand -base64 32`) to encrypt the keys at rest with AES-256-GCM. `issuer` names the app in authenticators. Upgrading from 0.0.x adds four nullable columns to `nma_user` (`totpSecret`, `totpPending`, `totpLastStep`, `recoveryCodes`).
|
|
771
|
+
- **Two-factor sign-in** (TOTP, any authenticator app). A user turns it on from the account page by scanning a QR code and confirming a code, and gets 10 one-time recovery codes. After the password, sign-in answers 401 `TWO_FACTOR_REQUIRED` until the request also carries `otp` (a code or a recovery code). Each code works once, wrong codes count toward the lockout, and turning it on signs out every other session. Turning it off or issuing new recovery codes needs the password; an admin can reset a lost second factor from the Users page. Set `secretKey` (32 bytes, base64: `openssl rand -base64 32`) to encrypt the keys at rest with AES-256-GCM. `issuer` names the app in authenticators. `issuerImage` (an http(s) URL) adds `image=` to the QR code for the apps that read it; others, Ente Auth among them, show their own icons, matched on `issuer`. Upgrading from 0.0.x adds four nullable columns to `nma_user` (`totpSecret`, `totpPending`, `totpLastStep`, `recoveryCodes`).
|
|
765
772
|
- `bootstrapSuperuser` creates the first user when `nma_user` is empty (it runs in module init, so call `app.init()` before seeding other users). `createAdminUser(dataSource, { … })` adds more.
|
|
766
773
|
- **CSRF.** Every POST, PATCH and DELETE of a cookie session must send the session's token as `X-CSRF-Token` (the UI does). The API also accepts only `application/json` bodies.
|
|
767
774
|
- **Your own users:**
|
|
@@ -969,6 +976,26 @@ Things hosts tend to write by hand that the admin already does:
|
|
|
969
976
|
- **Inline children stay out of the sidebar** by default (`nav: false` unless they set `nav`): no extra group to hide them in.
|
|
970
977
|
- **Labels in one language** are plain strings; other languages can come from `translate` (see Languages, theme and branding).
|
|
971
978
|
|
|
979
|
+
## Upgrading to 0.10.3
|
|
980
|
+
|
|
981
|
+
Nothing to change. What you may notice:
|
|
982
|
+
|
|
983
|
+
- A save with inline rows now answers with every refused row at once: each row runs in a savepoint, and the save still fails as a whole. One refused row keeps its own status and message; several are one 422 with every row's `fields`.
|
|
984
|
+
- Filter chips are no longer dashed «+» buttons (they read as "add"): a funnel and an arrow, after a «Filter:» caption, and a title in the popover. A yes/no filter is a switch on the chip (one click on, one click off); «No» is behind its arrow. An editable yes/no list cell is a switch that saves on click.
|
|
985
|
+
- Money inputs group digits as they are typed, and a `money` widget also fits a string DTO property.
|
|
986
|
+
- Calendars are always six rows, the column menu scrolls inside the window, a field's `warnIf` no longer remounts its input (the input lost its focus after the first letter), and native controls follow the dark theme (`color-scheme`).
|
|
987
|
+
- In Persian, the server's own texts are translated by the UI, class-validator's default messages included («must not be greater than 5»), without the property's name. English shows them exactly as sent, and a host's own words are never touched. A field the form does not show gives its message without its name.
|
|
988
|
+
|
|
989
|
+
New: `@AdminResource({ creatable: false })` (no «New», a create is refused, records can still be edited), `{ inline, existingOnly: true }` (rows only on an existing parent), `form.afterCreate: 'edit'` (saving a new record opens it), and `afterInlines(record, dto, ctx)` on a resource (a rule about a record and its rows, after both are written, inside the transaction).
|
|
990
|
+
|
|
991
|
+
## Upgrading to 0.10.2
|
|
992
|
+
|
|
993
|
+
Nothing to change. New: `builtinAuth({ issuerImage })`, an http(s) URL of your logo, sent as `image=` in the two-factor QR code. Only some authenticator apps read it; others, Ente Auth among them, show their own icons, matched on `issuer`. A value that is not an absolute http(s) URL fails at boot.
|
|
994
|
+
|
|
995
|
+
## Upgrading to 0.9.1
|
|
996
|
+
|
|
997
|
+
Nothing to change. New: `@AdminAction({ choices })` (see Actions): an input field whose dropdown a resource method fills when the dialog opens, re-checked when the action runs. Every dropdown in the dashboard (forms, filters, sort, page size, inline cell edits, language, roles, audit, debugger, the editor's heading level) is now the dashboard's own list, styled like the rest and right to left in Persian, instead of the browser's native `<select>`. Tests that drove a native select (`selectOption`) click the field, then the option (`getByRole('option', { name })`).
|
|
998
|
+
|
|
972
999
|
## Upgrading to 0.9.0
|
|
973
1000
|
|
|
974
1001
|
The contracts between the admin and your code are now enforced: the decorators' types refuse a method or class of the wrong shape at compile time, and the admin refuses a wrong value at run time (a 500 with `nest-my-admin: …` in the log, or a boot error) instead of reading it as something else. Code that already followed the docs keeps working; code that compiled only through `any` or plain JavaScript may now fail. What to check:
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Logger } from '@nestjs/common';
|
|
2
|
-
import type { ActionResult, AdminRecord } from '../contract.js';
|
|
2
|
+
import type { ActionChoicesResponse, ActionResult, AdminRecord } from '../contract.js';
|
|
3
3
|
import type { ResolvedAdminOptions } from '../options.js';
|
|
4
4
|
import type { AdminPolicy } from '../policy/admin-policy.service.js';
|
|
5
5
|
import type { RegisteredResource } from '../registry/resource-registry.js';
|
|
@@ -23,6 +23,14 @@ export declare class ActionService {
|
|
|
23
23
|
private readonly host;
|
|
24
24
|
constructor(host: ActionHost);
|
|
25
25
|
run(entry: RegisteredResource, name: string, body: unknown, ctx: AdminContext): Promise<ActionResult>;
|
|
26
|
+
/**
|
|
27
|
+
* `GET …/actions/:action/choices/:field`: the dropdown of an input field, for whoever may run the action. The
|
|
28
|
+
* method is the resource's (`@AdminAction({ choices })`), called with the request's context.
|
|
29
|
+
*/
|
|
30
|
+
choices(entry: RegisteredResource, name: string, field: string, ctx: AdminContext): Promise<ActionChoicesResponse>;
|
|
31
|
+
private readChoices;
|
|
32
|
+
/** A choice field's value must still be one of its choices when the action runs. */
|
|
33
|
+
private checkChoices;
|
|
26
34
|
private runOnResource;
|
|
27
35
|
private runOnOne;
|
|
28
36
|
/** Each record in its own transaction: a failure is reported for its id (as the single run would answer) and undoes nothing else. */
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { MAX_BULK } from '../constants.js';
|
|
2
2
|
import { parseRecordId, recordIdOf } from '../crud/record-id.js';
|
|
3
3
|
import { validateWrite } from '../crud/validate-write.js';
|
|
4
|
-
import { describeValue, HostContractError, isLocalizedText,
|
|
5
|
-
import { AdminBadRequestError, AdminForbiddenError, AdminNotFoundError, AdminValidationError } from '../errors.js';
|
|
4
|
+
import { checkFoundRecord, describeValue, HostContractError, isLocalizedText, isRecordObject } from '../host-contract.js';
|
|
5
|
+
import { AdminBadRequestError, AdminFieldError, AdminForbiddenError, AdminNotFoundError, AdminValidationError } from '../errors.js';
|
|
6
6
|
import { toErrorResponse } from '../http/error-response.js';
|
|
7
7
|
/**
|
|
8
8
|
* Runs `@AdminAction` methods (spec §5.2, §11): permission, input validation, then the method inside
|
|
@@ -28,6 +28,7 @@ export class ActionService {
|
|
|
28
28
|
// Validated once up front (a 422 before anything runs); every run then gets an instance of its own, and the
|
|
29
29
|
// first one, which no method ever sees, is what the participants of the write are told was sent.
|
|
30
30
|
const input = { sent: await validateInput(action, request.input), fresh: () => validateInput(action, request.input) };
|
|
31
|
+
await this.checkChoices(entry, action, input.sent, ctx);
|
|
31
32
|
if (action.target === 'resource') {
|
|
32
33
|
if (request.ids !== undefined)
|
|
33
34
|
throw new AdminBadRequestError(`"${label}" runs on the resource, not on records: send no ids`);
|
|
@@ -40,6 +41,53 @@ export class ActionService {
|
|
|
40
41
|
throw new AdminBadRequestError(`"${label}" runs on one record at a time`);
|
|
41
42
|
return action.atomic ? this.runTogether(entry, action, label, ids, input, ctx) : this.runEach(entry, action, label, ids, input, ctx);
|
|
42
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* `GET …/actions/:action/choices/:field`: the dropdown of an input field, for whoever may run the action. The
|
|
46
|
+
* method is the resource's (`@AdminAction({ choices })`), called with the request's context.
|
|
47
|
+
*/
|
|
48
|
+
async choices(entry, name, field, ctx) {
|
|
49
|
+
const { policy, options } = this.host;
|
|
50
|
+
policy.requireReach(entry, ctx);
|
|
51
|
+
const action = entry.actions.get(name);
|
|
52
|
+
if (!action)
|
|
53
|
+
throw new AdminNotFoundError(`${entry.schema.label} has no action "${name}"`);
|
|
54
|
+
policy.requireAction(entry, action, options.texts(action.label, ctx.locale ?? options.locale, `resource.${entry.schema.name}.actions.${action.name}.label`), ctx);
|
|
55
|
+
if (!action.choices?.has(field))
|
|
56
|
+
throw new AdminNotFoundError(`"${name}" has no choices for "${field}"`);
|
|
57
|
+
const locale = ctx.locale ?? options.locale;
|
|
58
|
+
return { items: (await this.readChoices(entry, action, field, ctx)).map((choice) => ({ value: choice.value, label: options.texts(choice.label, locale) })) };
|
|
59
|
+
}
|
|
60
|
+
async readChoices(entry, action, field, ctx) {
|
|
61
|
+
const method = action.choices.get(field);
|
|
62
|
+
const where = `${entry.className}.${method}() (choices of @AdminAction "${action.name}" field "${field}")`;
|
|
63
|
+
const answer = await entry.resource[method](ctx);
|
|
64
|
+
if (!Array.isArray(answer))
|
|
65
|
+
throw new HostContractError(`${where} must return an array of choices, but it returned ${describeValue(answer)}`);
|
|
66
|
+
return answer.map((choice) => {
|
|
67
|
+
if (typeof choice === 'string' || typeof choice === 'number')
|
|
68
|
+
return { value: String(choice), label: String(choice) };
|
|
69
|
+
if (isRecordObject(choice) && (typeof choice.value === 'string' || typeof choice.value === 'number') && (choice.label === undefined || isLocalizedText(choice.label))) {
|
|
70
|
+
return { value: String(choice.value), label: choice.label ?? String(choice.value) };
|
|
71
|
+
}
|
|
72
|
+
throw new HostContractError(`${where}: a choice is a string or { value, label }, but one is ${describeValue(choice)}`);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/** A choice field's value must still be one of its choices when the action runs. */
|
|
76
|
+
async checkChoices(entry, action, sent, ctx) {
|
|
77
|
+
if (!action.choices)
|
|
78
|
+
return;
|
|
79
|
+
const errors = {};
|
|
80
|
+
for (const field of action.choices.keys()) {
|
|
81
|
+
const value = sent[field];
|
|
82
|
+
if (value === undefined || value === null || value === '')
|
|
83
|
+
continue;
|
|
84
|
+
const choices = await this.readChoices(entry, action, field, ctx);
|
|
85
|
+
if (!choices.some((choice) => choice.value === String(value)))
|
|
86
|
+
errors[field] = ['is not one of the choices'];
|
|
87
|
+
}
|
|
88
|
+
if (Object.keys(errors).length > 0)
|
|
89
|
+
throw new AdminFieldError(errors);
|
|
90
|
+
}
|
|
43
91
|
async runOnResource(entry, action, input, ctx) {
|
|
44
92
|
const outcome = await this.host.writes.run(entry, ctx, (tx) => this.host.writes.change({ kind: 'action', target: entry, action: { definition: action, input: input.sent } }, tx, async () => checkOutcome(await methodOf(entry, action).call(entry.resource, await input.fresh(), tx), entry, action), () => undefined));
|
|
45
93
|
return withMessage({}, messageOf(outcome, ctx, this.host.options));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ActionResult, AdminRecord, BulkResult, ListResponse, MenuBadges, TabCounts, MetaPageSummary, MetaResponse, OptionsResponse, PageResponse, ResourceSchema, SearchResponse } from '../contract.js';
|
|
1
|
+
import type { ActionChoicesResponse, ActionResult, AdminRecord, BulkResult, ListResponse, MenuBadges, TabCounts, MetaPageSummary, MetaResponse, OptionsResponse, PageResponse, ResourceSchema, SearchResponse } from '../contract.js';
|
|
2
2
|
import { type ResolvedMenu } from './menu.js';
|
|
3
3
|
import { DashboardService } from '../dashboard/dashboard.service.js';
|
|
4
4
|
import { WidgetRegistry } from '../dashboard/widget-registry.js';
|
|
@@ -140,6 +140,8 @@ export declare class AdminApiService {
|
|
|
140
140
|
* One record answers `{ message?, record }`, several `{ ok, failed, message? }`, a resource action `{ message? }`.
|
|
141
141
|
*/
|
|
142
142
|
runAction(name: string, action: string, body: unknown, ctx: AdminContext): Promise<ActionResult>;
|
|
143
|
+
/** `GET /resources/:name/actions/:action/choices/:field`: an action input's dropdown (`@AdminAction({ choices })`). */
|
|
144
|
+
actionChoices(name: string, action: string, field: string, ctx: AdminContext): Promise<ActionChoicesResponse>;
|
|
143
145
|
/**
|
|
144
146
|
* `GET /resources/:name/print/:print?id=…`: an `@AdminPrint` template's page for one record (or up to 100 with
|
|
145
147
|
* `bulk`). Each record is read like `GET /resources/:name/:id` (view permission, scopes) and its printing is audited.
|
|
@@ -525,7 +525,7 @@ let AdminApiService = class AdminApiService {
|
|
|
525
525
|
.list()
|
|
526
526
|
.filter((candidate) => entry.metadata.childEntityMetadatas.some((child) => child.target === candidate.entity))
|
|
527
527
|
.map((candidate) => candidate.schema.label);
|
|
528
|
-
throw new AdminBadRequestError(`${schema.label} records are created as one of their kinds
|
|
528
|
+
throw new AdminBadRequestError(children.length > 0 ? `${schema.label} records are created as one of their kinds: ${children.join(', ')}` : `${schema.label} records are not created here`);
|
|
529
529
|
}
|
|
530
530
|
const { own, inlines } = splitInlines(entry, body);
|
|
531
531
|
this.policy.checkWriteFields(entry, own, entry.schema.form.create, ctx);
|
|
@@ -545,6 +545,7 @@ let AdminApiService = class AdminApiService {
|
|
|
545
545
|
});
|
|
546
546
|
if (plan)
|
|
547
547
|
await this.inlineWriter.apply(plan, checked, created, tx);
|
|
548
|
+
await resource.afterInlines(created, dto, tx);
|
|
548
549
|
return this.withInlineRows(entry, created, tx);
|
|
549
550
|
});
|
|
550
551
|
}
|
|
@@ -622,6 +623,7 @@ let AdminApiService = class AdminApiService {
|
|
|
622
623
|
});
|
|
623
624
|
if (plan)
|
|
624
625
|
await this.inlineWriter.apply(plan, checked, updated, tx);
|
|
626
|
+
await resource.afterInlines(updated, dto, tx);
|
|
625
627
|
return this.withInlineRows(entry, updated, tx);
|
|
626
628
|
});
|
|
627
629
|
}
|
|
@@ -853,6 +855,10 @@ let AdminApiService = class AdminApiService {
|
|
|
853
855
|
runAction(name, action, body, ctx) {
|
|
854
856
|
return this.actions.run(this.registry.get(name), action, body, ctx);
|
|
855
857
|
}
|
|
858
|
+
/** `GET /resources/:name/actions/:action/choices/:field`: an action input's dropdown (`@AdminAction({ choices })`). */
|
|
859
|
+
actionChoices(name, action, field, ctx) {
|
|
860
|
+
return this.actions.choices(this.registry.get(name), action, field, ctx);
|
|
861
|
+
}
|
|
856
862
|
/**
|
|
857
863
|
* `GET /resources/:name/print/:print?id=…`: an `@AdminPrint` template's page for one record (or up to 100 with
|
|
858
864
|
* `bulk`). Each record is read like `GET /resources/:name/:id` (view permission, scopes) and its printing is audited.
|
package/dist/contract.d.ts
CHANGED
|
@@ -30,6 +30,8 @@ export interface FieldSchema {
|
|
|
30
30
|
integer?: boolean;
|
|
31
31
|
/** An action input picked like this relation field of the resource (`@AdminField({ pickFrom })`): its options endpoint. */
|
|
32
32
|
optionsField?: string;
|
|
33
|
+
/** An action input with a dropdown whose options come from `GET /resources/:name/actions/:action/choices/:field` (`@AdminAction({ choices })`). */
|
|
34
|
+
choices?: true;
|
|
33
35
|
/** Set when `type` is `relation`. */
|
|
34
36
|
relation?: RelationSchema;
|
|
35
37
|
/** Set when `type` is `object`: the group's fields, named relative to it (`city` in `address`). */
|
|
@@ -151,6 +153,8 @@ export interface FormLayoutInline {
|
|
|
151
153
|
computed?: string[];
|
|
152
154
|
/** A marker on the first card by `order` («Main picture»). */
|
|
153
155
|
markFirst?: string;
|
|
156
|
+
/** Not on the form of a new record (rows are added once the parent exists). */
|
|
157
|
+
existingOnly?: true;
|
|
154
158
|
}
|
|
155
159
|
/** Label and value rows in a card (an order's totals): a field of the record, or one of its computed columns (`_computed`). */
|
|
156
160
|
export interface FormLayoutSummary {
|
|
@@ -522,6 +526,8 @@ export interface ResourceSchema {
|
|
|
522
526
|
aside?: AsideCardSchema[];
|
|
523
527
|
/** `view`: an existing record opens as text until «Edit». */
|
|
524
528
|
mode?: 'view';
|
|
529
|
+
/** `edit`: saving a new record opens it instead of going back to the list. */
|
|
530
|
+
afterCreate?: 'edit';
|
|
525
531
|
/** The record's header: badge fields, and a subtitle of field values and computed columns (`_computed`). */
|
|
526
532
|
header?: {
|
|
527
533
|
badges?: string[];
|
|
@@ -1118,3 +1124,10 @@ export interface AdminRuntimeConfig {
|
|
|
1118
1124
|
/** UI texts the host rewords through `translate` (`ui.<key>`), per locale; only the overridden keys. */
|
|
1119
1125
|
messages?: Record<string, Record<string, string>>;
|
|
1120
1126
|
}
|
|
1127
|
+
/** `GET /resources/:name/actions/:action/choices/:field`: the options of an action input's dropdown. */
|
|
1128
|
+
export interface ActionChoicesResponse {
|
|
1129
|
+
items: Array<{
|
|
1130
|
+
value: string;
|
|
1131
|
+
label: string;
|
|
1132
|
+
}>;
|
|
1133
|
+
}
|
|
@@ -44,6 +44,12 @@ export interface AdminActionOptions {
|
|
|
44
44
|
* the action takes no input, where the parameter types cannot be read.
|
|
45
45
|
*/
|
|
46
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>;
|
|
47
53
|
icon?: string;
|
|
48
54
|
}
|
|
49
55
|
/** What an action method may return: a message for the person who ran it. */
|
|
@@ -71,6 +77,8 @@ export interface RegisteredAction {
|
|
|
71
77
|
icon?: string;
|
|
72
78
|
input?: DtoClass;
|
|
73
79
|
form?: DtoForm;
|
|
80
|
+
/** Input fields whose choices a resource method gives: field → method name. */
|
|
81
|
+
choices?: Map<string, string>;
|
|
74
82
|
}
|
|
75
83
|
/**
|
|
76
84
|
* A custom action of a resource (spec §5.2): a button on a record, on a list selection (`bulk`) or on the list
|
|
@@ -83,6 +91,9 @@ export interface RegisteredAction {
|
|
|
83
91
|
export declare function AdminAction<I extends object>(options: AdminActionOptions & {
|
|
84
92
|
target: 'resource';
|
|
85
93
|
input: new (...args: any[]) => I;
|
|
94
|
+
choices?: {
|
|
95
|
+
[K in keyof I & string]?: string;
|
|
96
|
+
};
|
|
86
97
|
}): TypedMethodDecorator<(input: I, ctx: AdminContext) => Awaitable<ActionReturn>>;
|
|
87
98
|
export declare function AdminAction(options: AdminActionOptions & {
|
|
88
99
|
target: 'resource';
|
|
@@ -90,6 +101,9 @@ export declare function AdminAction(options: AdminActionOptions & {
|
|
|
90
101
|
export declare function AdminAction<I extends object>(options: AdminActionOptions & {
|
|
91
102
|
target?: 'record';
|
|
92
103
|
input: new (...args: any[]) => I;
|
|
104
|
+
choices?: {
|
|
105
|
+
[K in keyof I & string]?: string;
|
|
106
|
+
};
|
|
93
107
|
}): RecordMethodDecorator<[input: I, ctx: AdminContext], Awaitable<ActionReturn>>;
|
|
94
108
|
export declare function AdminAction(options?: AdminActionOptions & {
|
|
95
109
|
target?: 'record';
|
|
@@ -106,6 +106,7 @@ export function resolveActions(resourceClass, reserved, fail, row) {
|
|
|
106
106
|
if (icon !== undefined && typeof icon !== 'string')
|
|
107
107
|
fail(`${where}: icon must be an icon name`);
|
|
108
108
|
let form;
|
|
109
|
+
let choices;
|
|
109
110
|
if (input !== undefined) {
|
|
110
111
|
if (typeof input !== 'function')
|
|
111
112
|
fail(`${where}: input must be a DTO class`);
|
|
@@ -116,6 +117,24 @@ export function resolveActions(resourceClass, reserved, fail, row) {
|
|
|
116
117
|
fail(`${where}: input field "${field}" uses the "${options.widget}" widget; action inputs cannot take files or rich text`);
|
|
117
118
|
}
|
|
118
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
|
+
}
|
|
119
138
|
actions.set(name, {
|
|
120
139
|
name,
|
|
121
140
|
label: perRecord ? label.static : (label ?? humanize(name)),
|
|
@@ -128,6 +147,7 @@ export function resolveActions(resourceClass, reserved, fail, row) {
|
|
|
128
147
|
variant,
|
|
129
148
|
...(icon ? { icon } : {}),
|
|
130
149
|
...(input ? { input, form } : {}),
|
|
150
|
+
...(choices ? { choices } : {}),
|
|
131
151
|
});
|
|
132
152
|
}
|
|
133
153
|
const primaries = [...actions.values()].filter((action) => action.primary);
|
|
@@ -163,9 +183,15 @@ export function toActionSchema(action, text) {
|
|
|
163
183
|
variant: action.variant,
|
|
164
184
|
...(action.primary ? { primary: true } : {}),
|
|
165
185
|
...(action.icon ? { icon: action.icon } : {}),
|
|
166
|
-
...(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) } : {}),
|
|
167
187
|
};
|
|
168
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
|
+
}
|
|
169
195
|
/** `label.for` as called: a text, or `null` (not on this record); anything else (a Promise of an `async` one) fails loudly. */
|
|
170
196
|
function checkedLabelFor(where, labelFor) {
|
|
171
197
|
return (record) => {
|
|
@@ -40,6 +40,8 @@ export interface AdminResourceOptions {
|
|
|
40
40
|
* records only the host's own code writes.
|
|
41
41
|
*/
|
|
42
42
|
readonly?: boolean;
|
|
43
|
+
/** `false`: records of this resource come from elsewhere (no «New», a create is refused); they can still be edited. */
|
|
44
|
+
creatable?: boolean;
|
|
43
45
|
/** Custom permission codes of this resource: `['view_all']` declares `<name>.view_all` for roles and `ctx.can()`. */
|
|
44
46
|
permissions?: string[];
|
|
45
47
|
}
|
|
@@ -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');
|
|
@@ -50,6 +50,7 @@ export function toLayoutInline(inline, label, text, childLabel) {
|
|
|
50
50
|
link: inline.link,
|
|
51
51
|
...(inline.readonly ? { readonly: true } : {}),
|
|
52
52
|
...(inline.computed.length > 0 ? { computed: [...inline.computed] } : {}),
|
|
53
|
+
...(inline.node.existingOnly ? { existingOnly: true } : {}),
|
|
53
54
|
...(inline.node.cards?.markFirst !== undefined ? { markFirst: text(inline.node.cards.markFirst, inline.node.key === undefined ? undefined : `form.${inline.node.key}.markFirst`) } : {}),
|
|
54
55
|
};
|
|
55
56
|
}
|
|
@@ -41,11 +41,13 @@ export class InlineWriter {
|
|
|
41
41
|
// An inline the user cannot view is not there for them (as in the schema).
|
|
42
42
|
if (!viewable.some((inline) => inline.name === name))
|
|
43
43
|
shape[`_inlines.${name}`] = [`is not an inline of ${parent.schema.label}`];
|
|
44
|
+
if (creating && viewable.find((inline) => inline.name === name)?.node.existingOnly)
|
|
45
|
+
shape[`_inlines.${name}`] = ['can be added once the record exists'];
|
|
44
46
|
}
|
|
45
47
|
if (Object.keys(shape).length > 0)
|
|
46
48
|
throw new AdminValidationError(shape);
|
|
47
49
|
// A new parent checks every inline it shows (`min` counts rows that will exist); an update only those it changes.
|
|
48
|
-
const inlines = viewable.filter((inline) => creating
|
|
50
|
+
const inlines = viewable.filter((inline) => (creating ? !inline.node.existingOnly : Object.hasOwn(sent, inline.name)));
|
|
49
51
|
const parsed = inlines.map((inline) => parseChanges(inline, sent[inline.name] ?? {}, shape));
|
|
50
52
|
if (Object.keys(shape).length > 0)
|
|
51
53
|
throw new AdminValidationError(shape, 'The inline changes are malformed');
|
|
@@ -309,6 +311,7 @@ export class InlineWriter {
|
|
|
309
311
|
// The parent's values as the user sees them, body over stored (`values._parent` of relationOptions()).
|
|
310
312
|
const withParent = async (values) => ({ ...values, _parent: (parentValues ??= { _resource: parent.schema.name, ...(await this.deps.values(parent, parentEntity, tx)) }) });
|
|
311
313
|
const hasIds = (ids) => [...ids.values()].some((list) => list.length > 0);
|
|
314
|
+
const refusals = [];
|
|
312
315
|
for (const { planned, rows, moves, positions } of checked) {
|
|
313
316
|
const { inline, creates, updates, deletes } = planned;
|
|
314
317
|
const { child } = inline;
|
|
@@ -318,12 +321,21 @@ export class InlineWriter {
|
|
|
318
321
|
// transaction, so a refusal here undoes the parent too.
|
|
319
322
|
if (creates.length > 0 && !this.deps.policy.createRule(child, parentEntity, tx))
|
|
320
323
|
throw new AdminForbiddenError(`You may not add ${child.schema.label} rows here`);
|
|
324
|
+
// Each row in a savepoint, so one refused row (a unique violation included) does not end the others' checks: the
|
|
325
|
+
// user sees what is wrong with all of them at once. Any failure still fails the whole save, below.
|
|
321
326
|
const run = async (path, change, method) => {
|
|
327
|
+
const runner = tx.manager?.queryRunner;
|
|
328
|
+
await runner?.startTransaction();
|
|
322
329
|
try {
|
|
323
|
-
|
|
330
|
+
await this.deps.change({ ...change, parent: parentRef }, tx, method);
|
|
331
|
+
await runner?.commitTransaction();
|
|
324
332
|
}
|
|
325
333
|
catch (error) {
|
|
326
|
-
|
|
334
|
+
await runner?.rollbackTransaction();
|
|
335
|
+
const placed = atRow(error, path, child, this.deps.errorMapper);
|
|
336
|
+
if (!isRowRefusal(placed))
|
|
337
|
+
throw placed;
|
|
338
|
+
refusals.push(placed);
|
|
327
339
|
}
|
|
328
340
|
};
|
|
329
341
|
for (const entry of deletes) {
|
|
@@ -363,8 +375,17 @@ export class InlineWriter {
|
|
|
363
375
|
});
|
|
364
376
|
}
|
|
365
377
|
}
|
|
378
|
+
// One refusal keeps its own status and message; several are one answer with every row's fields.
|
|
379
|
+
if (refusals.length === 1)
|
|
380
|
+
throw refusals[0];
|
|
381
|
+
if (refusals.length > 1)
|
|
382
|
+
throw new AdminValidationError(Object.assign({}, ...refusals.map((refusal) => refusal.fields)));
|
|
366
383
|
}
|
|
367
384
|
}
|
|
385
|
+
/** A row the host or the database refused for its values: worth telling together with the other rows' problems. */
|
|
386
|
+
function isRowRefusal(error) {
|
|
387
|
+
return error instanceof AdminError && (error.status === 422 || error.status === 409 || error.status === 400) && Object.keys(error.fields ?? {}).length > 0;
|
|
388
|
+
}
|
|
368
389
|
/** The shape of one inline's changes; problems go to `errors` by path. Invalid `_id`s are 404s, as on the child's own routes. */
|
|
369
390
|
function parseChanges(inline, raw, errors) {
|
|
370
391
|
const { child } = inline;
|
|
@@ -176,6 +176,8 @@ export interface FormConfig {
|
|
|
176
176
|
};
|
|
177
177
|
/** `view`: an existing record opens as text, and «Edit» turns its editable fields into inputs. Default `edit`. */
|
|
178
178
|
mode?: 'edit' | 'view';
|
|
179
|
+
/** `edit`: saving a new record opens it, for what can only be added once it exists. Default: back to the list. */
|
|
180
|
+
afterCreate?: 'list' | 'edit';
|
|
179
181
|
/**
|
|
180
182
|
* The record's header: `badges` (fields shown as badges next to the title; default: every badge-widget field) and a
|
|
181
183
|
* `subtitle` line of field values and computed list columns (`{ computed: '<list.computed key>' }`), joined by «·».
|
|
@@ -286,6 +288,11 @@ export declare abstract class AdminResourceBase<T extends ObjectLiteral = Object
|
|
|
286
288
|
* so a write's check sees its own transaction. Default: all records.
|
|
287
289
|
*/
|
|
288
290
|
relationOptions(_field: string, qb: SelectQueryBuilder<any>, _ctx: AdminContext, _values: Record<string, unknown>): SelectQueryBuilder<any> | Promise<SelectQueryBuilder<any>>;
|
|
291
|
+
/**
|
|
292
|
+
* After a create or update and its inline rows, inside the same transaction: for a rule about the record and its
|
|
293
|
+
* rows together (a product may be published only with its required values). A throw undoes the whole save.
|
|
294
|
+
*/
|
|
295
|
+
afterInlines(_record: T, _dto: Record<string, unknown>, _ctx: AdminContext): Promise<void>;
|
|
289
296
|
/**
|
|
290
297
|
* Overriding this skips the @BeforeSave/@AfterSave hooks; call `this.runHooks(...)` yourself to keep them.
|
|
291
298
|
* Relation fields arrive as ids (`customer: 3`, `tags: ['a', 'b']`), already checked to exist; the default
|
|
@@ -160,6 +160,11 @@ export class AdminResourceBase {
|
|
|
160
160
|
relationOptions(_field, qb, _ctx, _values) {
|
|
161
161
|
return qb;
|
|
162
162
|
}
|
|
163
|
+
/**
|
|
164
|
+
* After a create or update and its inline rows, inside the same transaction: for a rule about the record and its
|
|
165
|
+
* rows together (a product may be published only with its required values). A throw undoes the whole save.
|
|
166
|
+
*/
|
|
167
|
+
async afterInlines(_record, _dto, _ctx) { }
|
|
163
168
|
/**
|
|
164
169
|
* Overriding this skips the @BeforeSave/@AfterSave hooks; call `this.runHooks(...)` yourself to keep them.
|
|
165
170
|
* Relation fields arrive as ids (`customer: 3`, `tags: ['a', 'b']`), already checked to exist; the default
|
|
@@ -349,7 +349,7 @@ export function buildResourceSchema(input) {
|
|
|
349
349
|
group: definition.group ?? moduleGroup,
|
|
350
350
|
...(definition.icon ? { icon: definition.icon } : {}),
|
|
351
351
|
primaryKeys,
|
|
352
|
-
creatable: children.length === 0 && !definition.readonly,
|
|
352
|
+
creatable: children.length === 0 && !definition.readonly && definition.creatable !== false,
|
|
353
353
|
...(definition.readonly ? { readonly: true } : {}),
|
|
354
354
|
related: [], // filled in by the registry once every resource is known
|
|
355
355
|
actions: [], // filled in by the registry from the resource's @AdminAction methods
|
|
@@ -408,6 +408,7 @@ export function buildResourceSchema(input) {
|
|
|
408
408
|
...(layout ? { layout: localizeLayout(layout, bootLayoutText) } : {}),
|
|
409
409
|
...(aside ? { aside } : {}),
|
|
410
410
|
...(mode === 'view' ? { mode: 'view' } : {}),
|
|
411
|
+
...(resource.form?.afterCreate === 'edit' ? { afterCreate: 'edit' } : {}),
|
|
411
412
|
...(headerConfig
|
|
412
413
|
? {
|
|
413
414
|
header: {
|
|
@@ -50,6 +50,8 @@ export interface LayoutInlineConfig {
|
|
|
50
50
|
max?: number;
|
|
51
51
|
/** Shown, never edited here (a write to it is refused with 422): an order's lines once it is placed. */
|
|
52
52
|
readonly?: boolean;
|
|
53
|
+
/** Only on an existing parent: a new record's form leaves it out and a create refuses its rows (422). */
|
|
54
|
+
existingOnly?: boolean;
|
|
53
55
|
/** Computed columns of the child (`list.computed` keys) shown in the table, before its fields (a line's product thumbnail). */
|
|
54
56
|
computed?: string[];
|
|
55
57
|
/** Cards: a marker on the first card in `order` (the product's «main picture»). */
|
|
@@ -24,7 +24,8 @@ const WIDGET_TYPES = {
|
|
|
24
24
|
text: ['string', 'text', 'uuid', 'other'],
|
|
25
25
|
textarea: ['string', 'text'],
|
|
26
26
|
number: ['number'],
|
|
27
|
-
|
|
27
|
+
// A string too: a DTO property holding an amount as text (toman as a bigint string).
|
|
28
|
+
money: ['decimal', 'number', 'bigint', 'string'],
|
|
28
29
|
switch: ['boolean'],
|
|
29
30
|
checkbox: ['boolean'],
|
|
30
31
|
select: ['enum'],
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nest-my-admin/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.3",
|
|
4
4
|
"description": "Django-admin-class admin panel for NestJS + TypeORM",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@nest-my-admin/ui": "0.
|
|
38
|
+
"@nest-my-admin/ui": "0.10.3"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"@nestjs/common": "^11.0.0 || ^12.0.0",
|