@nest-my-admin/core 0.9.1 → 0.10.4
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 +311 -189
- package/dist/api/admin-api.service.js +3 -1
- package/dist/contract.d.ts +4 -0
- package/dist/decorators/admin-resource.d.ts +2 -0
- package/dist/http/admin-http.server.d.ts +11 -0
- package/dist/http/admin-http.server.js +27 -0
- package/dist/inlines/inline-config.js +1 -0
- package/dist/inlines/inline-writer.js +24 -3
- package/dist/options.d.ts +7 -0
- package/dist/options.js +4 -0
- 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
|
@@ -1,49 +1,197 @@
|
|
|
1
|
-
|
|
1
|
+
<h1 align="center">nest-my-admin</h1>
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
admin
|
|
3
|
+
<p align="center">
|
|
4
|
+
An admin panel for <b>NestJS + TypeORM</b>, in the spirit of Django admin.<br>
|
|
5
|
+
Describe your entities once; get lists, forms, permissions, an audit log and a polished UI, served by your own Nest app.
|
|
6
|
+
</p>
|
|
5
7
|
|
|
6
|
-
>
|
|
7
|
-
>
|
|
8
|
-
|
|
9
|
-
>
|
|
10
|
-
|
|
8
|
+
<p align="center">
|
|
9
|
+
<a href="https://www.npmjs.com/package/nest-my-admin"><img alt="npm" src="https://img.shields.io/npm/v/nest-my-admin?color=0f766e"></a>
|
|
10
|
+
<a href="https://github.com/phantomboy0/nest-my-admin/blob/main/LICENSE"><img alt="MIT license" src="https://img.shields.io/npm/l/nest-my-admin?color=0f766e"></a>
|
|
11
|
+
<img alt="NestJS 11 and 12" src="https://img.shields.io/badge/NestJS-11%20%7C%2012-0f766e">
|
|
12
|
+
<img alt="TypeORM 0.3.20+ and 1.x" src="https://img.shields.io/badge/TypeORM-0.3.20%2B%20%7C%201.x-0f766e">
|
|
13
|
+
</p>
|
|
11
14
|
|
|
12
|
-
|
|
13
|
-
The
|
|
14
|
-
|
|
15
|
+
<p align="center">
|
|
16
|
+
<img alt="The dashboard of a demo shop: sales, orders, low stock, a sales goal, sales by day and the latest orders" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/dashboard.png" width="900">
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
@AdminResource(Product, { icon: 'package' })
|
|
21
|
+
export class ProductAdmin extends AdminResourceBase<Product> {
|
|
22
|
+
list: ListConfig<Product> = { columns: ['name', 'price', 'stock'], search: ['name'], filters: ['stock'] };
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
That class is a working admin page for `Product`: a searchable, filterable list, a create and edit form built from the
|
|
27
|
+
entity's columns, and the REST API behind them. Everything else is opt-in, and every write can go through your own
|
|
28
|
+
services, so the rules your app already enforces still apply.
|
|
29
|
+
|
|
30
|
+
- **No frontend to build.** The UI (React, shadcn) ships prebuilt inside the package and is served by Nest at the path
|
|
31
|
+
you choose. Your app stays a plain Nest app.
|
|
32
|
+
- **Your code stays in charge.** Override `create`, `update` or `delete` to call your services; the admin validates
|
|
33
|
+
with your class-validator DTOs and runs inside a transaction you can join.
|
|
34
|
+
- **Built for real operators.** Roles with field- and row-level rules, a permission debugger, two-factor sign-in, an
|
|
35
|
+
audit log with per-record history, a command palette, a phone layout, dark mode, and right-to-left Persian with the
|
|
36
|
+
Jalali calendar.
|
|
37
|
+
|
|
38
|
+
**Status.** Version 0.10. Before 1.0 a minor version may change an API; each release says what to change in
|
|
39
|
+
[UPGRADING.md](https://github.com/phantomboy0/nest-my-admin/blob/main/UPGRADING.md).
|
|
40
|
+
|
|
41
|
+
## A closer look
|
|
42
|
+
|
|
43
|
+
Every screenshot is the demo app in this repository ([run it yourself](#try-the-demo)).
|
|
44
|
+
|
|
45
|
+
<table>
|
|
46
|
+
<tr>
|
|
47
|
+
<td width="50%"><img alt="The product list with pictures, tabs, filter chips, price and stock badges" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/products.png"><br><b>Lists.</b> Tabs with live counts, filter chips, computed columns (pictures, badges, a price over the old one, on/off switches) and cells you edit in place.</td>
|
|
48
|
+
<td width="50%"><img alt="An order page with a fulfilment stepper, order lines, a payment card and record actions" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/order.png"><br><b>Record pages.</b> Sections and side cards, a stepper with the time of each step, child rows edited inline, and your own actions in the header.</td>
|
|
49
|
+
</tr>
|
|
50
|
+
<tr>
|
|
51
|
+
<td><img alt="The status filter open over a product list filtered by category" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/filters.png"><br><b>Filters that live in the URL.</b> Share a link and the other person sees the same list.</td>
|
|
52
|
+
<td><img alt="The quick view sheet of a product over the list" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/quick-view.png"><br><b>Quick view.</b> Click a row to read a record without leaving the list.</td>
|
|
53
|
+
</tr>
|
|
54
|
+
<tr>
|
|
55
|
+
<td><img alt="The command palette finding three lamps" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/command-palette.png"><br><b>Command palette.</b> <kbd>⌘K</kbd> goes to any page, creates a record or finds one by its title.</td>
|
|
56
|
+
<td><img alt="The permission debugger explaining what the catalog editor may do with products" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/debugger.png"><br><b>Permission debugger.</b> Why a user can or cannot view, change or delete something, field by field.</td>
|
|
57
|
+
</tr>
|
|
58
|
+
<tr>
|
|
59
|
+
<td><img alt="A role's permissions as a grid of resources and operations" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/permissions.png"><br><b>Roles, groups and users.</b> Define roles in code, or let administrators manage them in the admin.</td>
|
|
60
|
+
<td><img alt="The dashboard in Persian, right to left, with Persian digits and Jalali dates" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/rtl.png"><br><b>English and Persian.</b> Right to left, Persian digits, the Jalali calendar; any other language through your own translations.</td>
|
|
61
|
+
</tr>
|
|
62
|
+
<tr>
|
|
63
|
+
<td><img alt="The product list in dark mode" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/products-dark.png"><br><b>Dark mode</b>, and an accent colour each person or the whole team can choose.</td>
|
|
64
|
+
<td><img alt="The product form with its sections, a locked SKU and a floating save bar" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/product-form.png"><br><b>Forms from your DTOs.</b> Sections, tabs, widgets, read-only rules and a save bar that follows you (<kbd>⌘S</kbd>).</td>
|
|
65
|
+
</tr>
|
|
66
|
+
<tr>
|
|
67
|
+
<td align="center"><img alt="The product list on a phone, as cards" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/mobile-list.png" width="260"> <img alt="An order page on a phone" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/mobile-order.png" width="260"><br><b>Phones.</b> Lists turn into cards; filters and sorting move to a drawer.</td>
|
|
68
|
+
<td><img alt="A settings page with sections, a switch, an image field and a secret" src="https://raw.githubusercontent.com/phantomboy0/nest-my-admin/main/docs/images/settings.png"><br><b>Settings pages</b> for the values that are not rows: the shop's name, a logo, an API key that is never shown again.</td>
|
|
69
|
+
</tr>
|
|
70
|
+
</table>
|
|
71
|
+
|
|
72
|
+
## Quick start
|
|
73
|
+
|
|
74
|
+
Requirements: NestJS 11 or 12, TypeORM 0.3.20+ or 1.x, Node 20.19+ (or Bun), and Postgres, MySQL 8 or SQLite.
|
|
15
75
|
|
|
16
76
|
```bash
|
|
17
|
-
npm install nest-my-admin
|
|
18
|
-
npm install -D @nestjs/testing # only if you use the test helpers
|
|
77
|
+
npm install nest-my-admin
|
|
19
78
|
```
|
|
20
79
|
|
|
80
|
+
**1. An entity** (you probably have one already):
|
|
81
|
+
|
|
21
82
|
```ts
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
83
|
+
@Entity()
|
|
84
|
+
export class Product {
|
|
85
|
+
@PrimaryGeneratedColumn() id: number;
|
|
86
|
+
@Column() name: string;
|
|
87
|
+
@Column({ type: 'decimal', precision: 10, scale: 2 }) price: string;
|
|
88
|
+
@Column({ default: 0 }) stock: number;
|
|
89
|
+
}
|
|
25
90
|
```
|
|
26
91
|
|
|
27
|
-
|
|
92
|
+
**2. A resource** that says how the admin shows it:
|
|
28
93
|
|
|
29
94
|
```ts
|
|
95
|
+
import { AdminResource, AdminResourceBase, type ListConfig } from 'nest-my-admin';
|
|
96
|
+
|
|
30
97
|
@AdminResource(Product, { icon: 'package' })
|
|
31
98
|
export class ProductAdmin extends AdminResourceBase<Product> {
|
|
32
|
-
|
|
33
|
-
list: ListConfig<Product> = { columns: ['id', 'name', 'sku', 'price'] };
|
|
34
|
-
form: FormConfig = { create: CreateProductDto, update: UpdateProductDto };
|
|
35
|
-
create(dto: CreateProductDto) { return this.products.create(dto); } // your business rules run
|
|
99
|
+
list: ListConfig<Product> = { columns: ['name', 'price', 'stock'], search: ['name'], filters: ['stock'] };
|
|
36
100
|
}
|
|
101
|
+
```
|
|
37
102
|
|
|
38
|
-
|
|
39
|
-
@Module({ providers: [ProductsService, ProductAdmin] })
|
|
40
|
-
export class CatalogModule {}
|
|
103
|
+
**3. The module**, with the built-in sign-in. Its tables come from `ADMIN_AUTH_ENTITIES`:
|
|
41
104
|
|
|
42
|
-
|
|
105
|
+
```ts
|
|
106
|
+
import { AdminModule } from 'nest-my-admin';
|
|
107
|
+
import { ADMIN_AUTH_ENTITIES, builtinAuth } from 'nest-my-admin/auth';
|
|
108
|
+
|
|
109
|
+
@Module({
|
|
110
|
+
imports: [
|
|
111
|
+
TypeOrmModule.forRoot({ type: 'postgres', url: process.env.DATABASE_URL, entities: [Product, ...ADMIN_AUTH_ENTITIES], synchronize: true }),
|
|
112
|
+
AdminModule.forRoot({
|
|
113
|
+
title: 'My shop',
|
|
114
|
+
auth: builtinAuth({ bootstrapSuperuser: { username: 'admin', password: process.env.ADMIN_PASSWORD! } }),
|
|
115
|
+
}),
|
|
116
|
+
],
|
|
117
|
+
providers: [ProductAdmin],
|
|
118
|
+
})
|
|
43
119
|
export class AppModule {}
|
|
44
120
|
```
|
|
45
121
|
|
|
46
|
-
|
|
122
|
+
**4. Start your app** and open `http://localhost:3000/admin`. Sign in as `admin` with `ADMIN_PASSWORD`; the user is
|
|
123
|
+
created on the first boot, when the users table is empty.
|
|
124
|
+
|
|
125
|
+
From here, the usual next steps:
|
|
126
|
+
|
|
127
|
+
- Put a resource in a module of its own: the module becomes its sidebar group ([Sidebar groups and order](#sidebar-groups-and-order)).
|
|
128
|
+
- Give it a create and an update DTO, and override `create`/`update` to call your service ([Fields and forms](#fields-and-forms)).
|
|
129
|
+
- Add roles for people who are not superusers ([Permissions](#permissions)).
|
|
130
|
+
|
|
131
|
+
`synchronize: true` is for trying it out. In production, generate migrations as usual: the admin's tables are
|
|
132
|
+
ordinary entities.
|
|
133
|
+
|
|
134
|
+
### One package or four
|
|
135
|
+
|
|
136
|
+
`nest-my-admin` is the admin, its UI, the built-in sign-in and the test helpers at one version, so they cannot drift
|
|
137
|
+
apart:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
import { AdminModule, AdminResource } from 'nest-my-admin';
|
|
141
|
+
import { builtinAuth } from 'nest-my-admin/auth'; // the built-in sign-in
|
|
142
|
+
import { createAdminTestingModule } from 'nest-my-admin/testing'; // in your tests (npm install -D @nestjs/testing)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
They are `@nest-my-admin/core`, `@nest-my-admin/auth` and `@nest-my-admin/testing` under one name: the same objects.
|
|
146
|
+
The scoped packages still work on their own (keep them at one exact version). The rest of this page uses the scoped
|
|
147
|
+
names; either import works.
|
|
148
|
+
|
|
149
|
+
The package is ESM. CommonJS apps load it through Node's `require(esm)`; one compiled with `"module": "nodenext"`
|
|
150
|
+
(the `nest new` default since Nest 11) needs TypeScript 5.8+, and with `"module": "commonjs"` any 5.x works.
|
|
151
|
+
|
|
152
|
+
## Try the demo
|
|
153
|
+
|
|
154
|
+
The screenshots above come from `examples/demo-api`, a small shop with two months of orders:
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
git clone https://github.com/phantomboy0/nest-my-admin && cd nest-my-admin
|
|
158
|
+
bun install && bun run build
|
|
159
|
+
cd examples/demo-api && NMA_DEMO_SHOWCASE=1 bun src/main.ts
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Open `http://localhost:3000/admin` and sign in as `admin` / `admin-demo-pass` (a superuser) or `editor` /
|
|
163
|
+
`editor-demo-pass` (the catalog editor role: a good way to see permissions at work). The data lives in memory and
|
|
164
|
+
starts fresh on every run. Without `NMA_DEMO_SHOWCASE` the demo starts with the small data set the end-to-end tests
|
|
165
|
+
use.
|
|
166
|
+
|
|
167
|
+
## How it fits into your app
|
|
168
|
+
|
|
169
|
+
- **Resources.** `@AdminResource(Entity)` on a provider registers one page. The admin reads the entity's TypeORM
|
|
170
|
+
metadata and your DTOs' class-validator rules, and builds the list, the form and the API from them.
|
|
171
|
+
- **Writes go through you.** The base class creates, updates and deletes through the repository. Override any of them
|
|
172
|
+
to call your service instead: the DTO is already validated and you get a transactional `ctx.manager`.
|
|
173
|
+
- **Its own HTTP surface.** The admin is mounted as one handler on Nest's Express adapter at `path` (default
|
|
174
|
+
`/admin`). Your global guards, interceptors, pipes, filters and `setGlobalPrefix` do not touch it, and it does not
|
|
175
|
+
touch your routes.
|
|
176
|
+
- **Its own tables, only when you ask.** Sign-in, roles, files, the audit log and admin-wide settings each come with
|
|
177
|
+
entities you add to your DataSource (`ADMIN_AUTH_ENTITIES`, `ADMIN_RBAC_ENTITIES`, `ADMIN_FILE_ENTITIES`,
|
|
178
|
+
`ADMIN_AUDIT_ENTITIES`, `ADMIN_SETTING_ENTITIES`).
|
|
179
|
+
|
|
180
|
+
## Contents
|
|
181
|
+
|
|
182
|
+
- [Resources, lists and forms](#resources-lists-and-forms): [querying lists](#querying-lists), [sidebar and menu](#sidebar-groups-and-order), [list page](#the-list-page), [tabs and computed columns](#tabs-and-computed-columns), [lists at scale](#lists-at-scale), [relations](#relations-and-record-titles), [entity shapes](#entity-shapes), [languages and branding](#languages-theme-and-branding), [Persian](#persian-dates-and-phones), [fields and forms](#fields-and-forms), [files and rich text](#files-images-and-rich-text), [actions](#actions), [printing](#printing-records), [Excel](#exporting-a-list-to-excel), [settings pages](#settings-pages), [source resources](#source-resources), [inlines](#inlines), [the record page](#the-record-page)
|
|
183
|
+
- [Dashboard](#dashboard)
|
|
184
|
+
- [Transactions, context and errors](#transactions-context-and-errors)
|
|
185
|
+
- [Sign-in](#sign-in)
|
|
186
|
+
- [Permissions](#permissions)
|
|
187
|
+
- [Audit log](#audit-log)
|
|
188
|
+
- [Writing less](#writing-less)
|
|
189
|
+
- [Upgrading](#upgrading)
|
|
190
|
+
- [Develop](#develop)
|
|
191
|
+
|
|
192
|
+
## Resources, lists and forms
|
|
193
|
+
|
|
194
|
+
### Querying lists
|
|
47
195
|
|
|
48
196
|
Lists support filters and search with a URL syntax you can bookmark:
|
|
49
197
|
|
|
@@ -130,6 +278,34 @@ For joins or aggregates, override `findMany` and start from `this.buildListQuery
|
|
|
130
278
|
list: ListConfig<Product> = { columns: ['name', 'status', 'stock'], editable: ['status', 'stock'] };
|
|
131
279
|
```
|
|
132
280
|
|
|
281
|
+
### Tabs and computed columns
|
|
282
|
+
|
|
283
|
+
```ts
|
|
284
|
+
list: ListConfig<Product> = {
|
|
285
|
+
columns: ['picture', 'product', 'money', 'stockBadge', 'specCount', 'active'],
|
|
286
|
+
tabs: [
|
|
287
|
+
{ key: 'all', label: 'All' },
|
|
288
|
+
{ key: 'active', label: 'Active', filter: { 'filter[status][eq]': 'active' } },
|
|
289
|
+
{ key: 'out', label: 'Out of stock', where: (qb) => void qb.andWhere(`${qb.alias}.stock = 0`) },
|
|
290
|
+
],
|
|
291
|
+
computed: {
|
|
292
|
+
picture: { label: 'Picture', kind: 'image', source: { first: 'media', field: 'image', by: 'sort' } },
|
|
293
|
+
product: { label: 'Product', kind: 'title', source: 'name', subline: 'sku' },
|
|
294
|
+
money: { label: 'Price', kind: 'money', source: 'price', previous: 'compareAtPrice' },
|
|
295
|
+
stockBadge: { label: 'Stock', kind: 'badge', source: 'stock', map: (stock) => (Number(stock) === 0 ? { label: 'Out of stock', tone: 'bad' } : { label: `In stock · ${stock}`, tone: 'ok' }) },
|
|
296
|
+
specCount: { label: 'Specs', kind: 'count', source: { aggregate: 'count', relation: 'specs' }, sortable: true },
|
|
297
|
+
active: { label: 'Active', kind: 'toggle', source: { toggle: 'status', on: 'active', off: 'archived' } },
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
- **Tabs** sit above the list, at most six, each with its count for the person looking (`GET /api/resources/:r/tab-counts`). A tab is a set of filters (`filter`, the URL syntax) or a condition of your own (`where`), for what the filter bar does not offer.
|
|
303
|
+
- **Computed columns** are named in `list.columns` like fields.
|
|
304
|
+
- Kinds: `image`, `title` (with a `subline`), `money` (with the `previous` price struck through), `badge` (with `map` returning a label and a tone: `ok`, `warn`, `bad`, `info`, `neutral` or `primary`), `count`, `toggle` (an on/off switch over an enum).
|
|
305
|
+
- Sources: a field or a path (`category.name`), an aggregate (`count`, `sum`, `min`, `max`) or the first row of a one-to-many relation, an enum toggle, or `{ compute: (rows, ctx) => …, fields }`, called once per page.
|
|
306
|
+
- Aggregates and first rows count only the rows the viewer may see, and a column that reads something the viewer cannot see is left out.
|
|
307
|
+
- **Phones** show each row as a card: `list.mobile: { title, subtitle, badge, meta: [...] }` chooses what goes where.
|
|
308
|
+
|
|
133
309
|
### Lists at scale
|
|
134
310
|
|
|
135
311
|
- **`list.count`:**
|
|
@@ -265,6 +441,12 @@ AdminModule.forRoot({
|
|
|
265
441
|
- **Theme.** Light, dark or system, from the header. It is applied before the page renders, so nothing flashes.
|
|
266
442
|
- **Icons** for groups and resources: bell, book, box, boxes, briefcase, building, calendar, cart, chart, clock, credit-card, database, dollar, file, file-text, folder, globe, heart, history, home, image, inbox, key, layers, link, list, lock, mail, map, map-pin, message, package, phone, printer, receipt, server, settings, shield, shopping-bag, shopping-cart, star, store, tag, tags, ticket, truck, user, users, video, wallet, wrench, zap.
|
|
267
443
|
|
|
444
|
+
#### The accent colour, in the admin
|
|
445
|
+
|
|
446
|
+
`forRoot({ appearance: {} })` (add `ADMIN_SETTING_ENTITIES` to the DataSource) lets people choose the accent colour
|
|
447
|
+
in their account menu (Display). Each person's choice is kept in their browser; people with `appearance.manage` can
|
|
448
|
+
also set it for everyone. What applies: the person's own, then the admin-wide one, then `branding.primaryColor`.
|
|
449
|
+
|
|
268
450
|
### Persian, dates and phones
|
|
269
451
|
|
|
270
452
|
- **Search in Persian.**
|
|
@@ -708,6 +890,92 @@ The parent's records carry `_perm.inlines.<child>.create`, and the inline hides
|
|
|
708
890
|
|
|
709
891
|
**Duplicate** copies the parent only, not its children (the copied form says so).
|
|
710
892
|
|
|
893
|
+
### The record page
|
|
894
|
+
|
|
895
|
+
The order page in the screenshots, from `examples/demo-api/src/sales/order.admin.ts`:
|
|
896
|
+
|
|
897
|
+
```ts
|
|
898
|
+
form: FormConfig = {
|
|
899
|
+
create: CreateOrderDto,
|
|
900
|
+
update: UpdateOrderDto,
|
|
901
|
+
mode: 'view', // opens as text; «Edit» turns it into the form
|
|
902
|
+
header: { badges: ['status'], subtitle: ['customer', 'createdAt', { computed: 'lineCount' }], stepper: 'fulfillment' },
|
|
903
|
+
layout: {
|
|
904
|
+
main: [
|
|
905
|
+
{ section: 'Order', fields: ['number', 'customer', 'total', 'tracking'], columns: 2 },
|
|
906
|
+
{ section: 'Lines', inline: OrderLineAdmin, display: 'table', order: 'position', max: 50, readonly: true },
|
|
907
|
+
{ section: 'Totals', summary: [{ label: 'Items', value: { computed: 'lineCount' } }, { label: 'Total', value: 'total' }] },
|
|
908
|
+
],
|
|
909
|
+
aside: [
|
|
910
|
+
{ title: 'Payment', icon: 'credit-card', fields: ['status', 'total', 'tracking'] },
|
|
911
|
+
{ title: 'Handled by', icon: 'user', fields: { relation: 'handledById', fields: ['position'] }, link: true },
|
|
912
|
+
],
|
|
913
|
+
},
|
|
914
|
+
};
|
|
915
|
+
|
|
916
|
+
fields: FieldsConfig<Order> = {
|
|
917
|
+
fulfillment: {
|
|
918
|
+
widget: 'stepper',
|
|
919
|
+
exclude: ['cancelled'],
|
|
920
|
+
history: { inline: OrderStatusLogAdmin, value: 'value', at: 'at', where: { field: 'fulfillment' } },
|
|
921
|
+
},
|
|
922
|
+
};
|
|
923
|
+
```
|
|
924
|
+
|
|
925
|
+
- **`layout.main`** is the form's sections; **`layout.aside`** puts cards beside them, with the record's own fields or a related record's (`relation`), linked to it with `link: true`.
|
|
926
|
+
- **`header`**: badges next to the title, a subtitle of fields and computed values, and a `stepper` across the page.
|
|
927
|
+
- **A stepper** shows an ordered enum as steps. With `history` it reads when each step was reached from a log of the record (a child resource), and `exclude` leaves out values that are not steps.
|
|
928
|
+
- **`summary`** is a section of label and value lines (totals), from fields or the list's computed columns (`list.computed`), like `lineCount` here.
|
|
929
|
+
- **`mode: 'view'`** opens records as text; people who may edit get «Edit».
|
|
930
|
+
- **A primary action** is the filled button last in the header, with a label per record, or hidden on records where it does not apply (`null`):
|
|
931
|
+
|
|
932
|
+
```ts
|
|
933
|
+
@AdminAction({
|
|
934
|
+
primary: true,
|
|
935
|
+
label: { static: 'Next step', for: (order: Order) => (order.status === 'draft' ? 'Move to «paid»' : order.status === 'paid' ? 'Move to «shipped»' : null) },
|
|
936
|
+
})
|
|
937
|
+
async advance(order: Order, _input: unknown, ctx: AdminContext) { /* … */ }
|
|
938
|
+
```
|
|
939
|
+
|
|
940
|
+
- **A soft warning** on a field never blocks a save: `fields: { caption: { warnIf: { empty: true, message: 'No alt text: screen readers will not know what the picture shows.' } } }`.
|
|
941
|
+
|
|
942
|
+
## Dashboard
|
|
943
|
+
|
|
944
|
+
A widget is a provider with `@AdminWidget` and a `load` method. With at least one widget the person may see, the
|
|
945
|
+
dashboard replaces the home page.
|
|
946
|
+
|
|
947
|
+
```ts
|
|
948
|
+
@AdminWidget('sales', { type: 'stat', title: 'Sales', order: 10 })
|
|
949
|
+
export class SalesWidget implements AdminWidgetSource {
|
|
950
|
+
constructor(@InjectRepository(Order) private readonly orders: Repository<Order>) {}
|
|
951
|
+
|
|
952
|
+
async load(params: { from: string; to: string; previousFrom: string; previousTo: string }) {
|
|
953
|
+
const now = await this.total(params.from, params.to);
|
|
954
|
+
const before = await this.total(params.previousFrom, params.previousTo);
|
|
955
|
+
return { value: now.toLocaleString('en-US'), unit: 'USD', change: before ? Math.round(((now - before) / before) * 100) : 0, previousLabel: 'vs the previous period' };
|
|
956
|
+
}
|
|
957
|
+
// …
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
@Module({ imports: [TypeOrmModule.forFeature([Order])], providers: [SalesWidget] })
|
|
961
|
+
export class DashboardModule {}
|
|
962
|
+
```
|
|
963
|
+
|
|
964
|
+
- **The period** (today, this week, this month, this year, or a range from the calendar, Jalali in Persian) is chosen on the page. The UI sends `from`, `to` and the period before it (`previousFrom`, `previousTo`); the server checks them (in order, at most 366 days).
|
|
965
|
+
- **Types** and what `load` returns:
|
|
966
|
+
|
|
967
|
+
| `type` | Returns |
|
|
968
|
+
| --- | --- |
|
|
969
|
+
| `stat` | `{ value, unit?, change?, previousLabel? }`: `value` is text you format; `change` is a percent against the previous period |
|
|
970
|
+
| `progress` | `{ percent, value, caption }`: a ring |
|
|
971
|
+
| `chart` | `{ kind: 'line' \| 'bar', labels, series: [{ label, values, dashed? }], total?, subtitle? }`: one or two series, the second often the previous period, dashed |
|
|
972
|
+
| `table` | `{ columns: [{ key, label }], rows, link? }`: a cell may be `{ label, tone }` (a badge); `link: { resource }` adds «View all» |
|
|
973
|
+
| `list` | `{ items: [{ text, icon?, status?, link? }] }`: `status` is a coloured dot (a tone: `ok`, `warn`, `bad`, …) |
|
|
974
|
+
|
|
975
|
+
- **Layout.** `order` sorts widgets; `size` (1 to 4) is how many of the four desktop columns one takes. Phones show one column. Each widget loads on its own, with its own placeholder and error.
|
|
976
|
+
- **Permissions.** A widget needs `dashboard.<name>`, or the code in its `permission` option; `dashboard.*` grants them all. Superusers see every widget.
|
|
977
|
+
- `examples/demo-api/src/dashboard/dashboard.module.ts` has one widget of each type.
|
|
978
|
+
|
|
711
979
|
## Transactions, context and errors
|
|
712
980
|
|
|
713
981
|
Every create, update and delete runs in one database transaction. Pass `ctx.manager` to your services so their writes
|
|
@@ -768,7 +1036,7 @@ AdminModule.forRoot({
|
|
|
768
1036
|
- 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`.
|
|
769
1037
|
- Unknown users, wrong passwords and locked accounts get the same answer.
|
|
770
1038
|
- The account page changes the password (which signs out every other session), lists signed-in devices, and signs out one or all others.
|
|
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. Upgrading from 0.0.x adds four nullable columns to `nma_user` (`totpSecret`, `totpPending`, `totpLastStep`, `recoveryCodes`).
|
|
1039
|
+
- **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`).
|
|
772
1040
|
- `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.
|
|
773
1041
|
- **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.
|
|
774
1042
|
- **Your own users:**
|
|
@@ -976,169 +1244,9 @@ Things hosts tend to write by hand that the admin already does:
|
|
|
976
1244
|
- **Inline children stay out of the sidebar** by default (`nav: false` unless they set `nav`): no extra group to hide them in.
|
|
977
1245
|
- **Labels in one language** are plain strings; other languages can come from `translate` (see Languages, theme and branding).
|
|
978
1246
|
|
|
979
|
-
## Upgrading
|
|
980
|
-
|
|
981
|
-
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 })`).
|
|
982
|
-
|
|
983
|
-
## Upgrading to 0.9.0
|
|
984
|
-
|
|
985
|
-
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:
|
|
986
|
-
|
|
987
|
-
- **Resource classes.** `@AdminResource(Entity)` needs a class that extends `AdminResourceBase<Entity>`, and `@AdminSource(Row)` one that extends `AdminSourceBase<Row>` (compile errors now, as well as the boot errors before).
|
|
988
|
-
- **Actions.** A method returns nothing or `{ message }` (`ActionOutcome`), sync or async. Anything else (the record, a string, `{ mesage }`) fails the run and its writes are rolled back. The first parameter of a record action is one of the resource's rows (typed: `extend(inst: Instance, …)` on an `AdminResourceBase<Instance>`). The next parameter is the input: give it the type of `input`, or leave `input` out and the parameter's class becomes the form. `input` that is not the parameter's class (or a parent of it), and a record parameter of another class, fail at boot. `label.for` returns a text or `null`, never a Promise.
|
|
989
|
-
- **Parameter types need `emitDecoratorMetadata`** (as Nest's own injection does; tsc, SWC and Bun emit it, esbuild, Vite and tsx do not). Without it, an action whose method takes an input parameter and sets no `input` fails at boot: set `input: SomeDto`, or `input: false` for an action that takes none.
|
|
990
|
-
- **`@AdminScope`** returns a column map or a callback at once, never a Promise: an async scope used to mean «no restriction»; now it is an error.
|
|
991
|
-
- **`@AdminCan`** returns `true` or `false` at once. A Promise or another value is an error (a rule that throws still means «no», with a warning).
|
|
992
|
-
- **`@AdminPrint`** returns `` html`…` `` (or a Promise of it). A plain string is refused: it was not escaped.
|
|
993
|
-
- **`readonlyIf`** returns a boolean, and `readonlyFields()` an array of names.
|
|
994
|
-
- **`findMany`** of a resource, a source or an inline child returns `{ items, total }` (`total` may be left out); an array is refused.
|
|
995
|
-
- **Computed columns:** `compute()` returns an object of values by id, and a badge's `map()` a `{ label, tone }` with a known tone.
|
|
996
|
-
- **Widgets** return the data of their `type` (a stat's `value` is text); `@AdminWidget` needs a class with `load()` and `@AdminSettingsPage` one with `load()` and `save()`.
|
|
997
|
-
- **Hooks:** `@BeforeSave`/`@AfterSave` take `(dto | entity, ctx, mode: 'create' | 'update')`, `@BeforeDelete` `(entity, ctx, mode: 'soft' | 'hard')`, and return nothing: a hook that returns a value (`return dto` in a `@BeforeSave` that meant to change it) is a compile error and fails the save. Change `dto` in place.
|
|
998
|
-
- **Resource methods:** `query()` returns the query builder it was given, at once (an `async query()` is an error); a list tab's `where(qb, ctx)` adds to `qb` at once; `relationOptions()` returns the query builder (or a Promise of it); `findOne()` a record or `null`; `create()`/`update()`/`restore()` the record or nothing (then it is reloaded); `links()` an array of `{ label, href }` (a link that is not http(s) or relative is still left out, now with a warning).
|
|
999
|
-
- **Module options and adapters:** `resolveRoles` (option or adapter) returns an array of role names (a string used to be read letter by letter); a thrown error still means «no roles». `authenticate()` returns `{ user }` or `null`; `getUser()` a user or `null`; a global scope's `appliesTo()` a boolean; `translate` a string or `undefined` at once (an async `translate` used to show the declared texts silently; a throw still falls back). An `errorMapper` that returns something other than an `AdminError` or `undefined` is logged as an error. `files.storage.publicUrl()` returns a URL or `undefined` at once, and `get()` `{ body, contentType, size }` or `null`.
|
|
1000
|
-
- **What the types cannot see:** two DTO classes with the same properties are the same type to TypeScript; the boot check (with the parameter types) tells them apart.
|
|
1001
|
-
|
|
1002
|
-
New types: `ActionReturn` (what an action may return), `Awaitable<T>`, `RowOf<P>`, `TypedMethodDecorator<M>` and `TypedClassDecorator<I>` (for your own wrappers around the decorators).
|
|
1003
|
-
|
|
1004
|
-
## Upgrading to 0.8.1
|
|
1005
|
-
|
|
1006
|
-
Nothing to change. New: with `appearance` on, whoever holds `appearance.manage` uploads the **logo** (sidebar and sign-in page) and the **tab icon** (favicon) from the account menu, for everyone (PNG, JPEG, GIF, WebP, ICO or SVG, up to 512 KB; stored in `nma_setting`, served at `<path>/appearance/logo` and `/appearance/favicon`). An uploaded logo wins over `branding.logo`. Without a logo the sidebar shows the admin's own mark instead of the first letter of the title, and it is the default tab icon.
|
|
1007
|
-
|
|
1008
|
-
## Upgrading to 0.8.0
|
|
1009
|
-
|
|
1010
|
-
Nothing to change. New: [source resources](#source-resources): `@AdminSource(RowClass, …)` and `AdminSourceBase` give rows that are not database rows (an HTTP API, files, live state) the list, record page, forms and actions of a table; `inMemoryList` searches, filters, sorts and pages rows fetched whole.
|
|
1011
|
-
|
|
1012
|
-
## Upgrading to 0.7.4
|
|
1013
|
-
|
|
1014
|
-
Nothing to change. New: `@AdminField({ default })` starts action input forms and create forms at a value (checked at boot to fit the field), and `@AdminField({ fillFrom: '{crm}.example.com' })` fills a text field from other fields of the same form until someone types in it, in action dialogs too (see Field config).
|
|
1015
|
-
|
|
1016
|
-
## Upgrading to 0.7.3
|
|
1017
|
-
|
|
1018
|
-
Nothing to change. Smaller packages: `@nest-my-admin/core`, `/auth` and `/testing` no longer ship source maps (they pointed at sources the packages do not include), so core is about 1.2 MB instead of 1.9 MB; core no longer asks for `rxjs` and `@nest-my-admin/testing` no longer asks for `@nestjs/core`, neither of which they import.
|
|
1019
|
-
|
|
1020
|
-
## Upgrading to 0.7.2
|
|
1021
|
-
|
|
1022
|
-
Nothing to change. Fixed: 0.7 typed the context of `AdminSettingsSource.save` as `AdminWriteContext`, so code that calls a page's `save()` with an `AdminContext` stopped compiling; it takes an `AdminContext` again. Your own `save` may still declare `ctx: AdminWriteContext` to use `ctx.manager` without `!`.
|
|
1023
|
-
|
|
1024
|
-
## Upgrading to 0.7.1
|
|
1025
|
-
|
|
1026
|
-
Nothing to change. New: install `nest-my-admin` alone and import `nest-my-admin/auth` and `nest-my-admin/testing` (see the top of this page). To move to it, replace `@nest-my-admin/core`, `@nest-my-admin/auth` and `@nest-my-admin/testing` in your dependencies with `nest-my-admin`, keep `@nestjs/testing` among your dev dependencies, and change the imports (`@nest-my-admin/core` → `nest-my-admin`, `@nest-my-admin/auth` → `nest-my-admin/auth`, `@nest-my-admin/testing` → `nest-my-admin/testing`). `@nest-my-admin/testing` now marks `@nestjs/testing` an optional peer.
|
|
1027
|
-
|
|
1028
|
-
## Upgrading to 0.7
|
|
1029
|
-
|
|
1030
|
-
Nothing needs changing in an app on 0.6, except two type-only cases:
|
|
1031
|
-
|
|
1032
|
-
- an override that returns `super.relationOptions(...)` under an explicit `: SelectQueryBuilder<any>` return type: drop the annotation (`relationOptions` may now be async);
|
|
1033
|
-
- code that names `AdminMenuSection['items']` as a type: wrap it in `NonNullable<…>` (a `{ group }` section's items are optional);
|
|
1034
|
-
- code that reads `item.resource` or `item.page` of its own menu items as a string: they may now be classes too (`string | Function`), so narrow with `typeof item.resource === 'string'`.
|
|
1035
|
-
|
|
1036
|
-
New:
|
|
1037
|
-
|
|
1038
|
-
- `translate` (Languages, theme and branding): your own i18n for every text you declare and for the UI's own texts, by key; UI languages the admin does not ship.
|
|
1039
|
-
- `readonlyFields(record, ctx)` and `this.updateFields` (Fields and forms): lock a record's fields from one place.
|
|
1040
|
-
- `AdminWriteContext` and `AdminResourceBase<T, Id>` (Transactions, context and errors); with `transactions: false` writes now get the DataSource's own `ctx.manager`.
|
|
1041
|
-
- `relationOptions` may be async, and relation ids in its `values` (and `values._parent`) have the key's type.
|
|
1042
|
-
- `@AdminCan('create')` on an inline child (Inlines): whether rows may be added under a parent; `_perm.inlines` on the parent's records.
|
|
1043
|
-
- Menu sections from groups (`{ group: 'settings' }`) and menu items by class (The menu).
|
|
1044
|
-
- Layout nodes and aside cards take an optional `key`, for `translate`.
|
|
1045
|
-
|
|
1046
|
-
## Upgrading to 0.4
|
|
1047
|
-
|
|
1048
|
-
0.4 gives the admin a new look (the owner-admin design) and the features a shop owner's panel needs. All five packages are 0.4.0; upgrade them together. Every new feature is an option: an app that sets none of them gets the new look and today's behaviour, except for the points under "What a 0.3 app will notice".
|
|
1247
|
+
## Upgrading
|
|
1049
1248
|
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
- **The look.** New design tokens: the Vazirmatn font for every language (bundled), 12px cards, pill badges, a 256px sidebar with sections, a floating save bar with ⌘S, filter chips over lists, cards on phones. The default accent is `#5B5BD6`; to keep the old neutral one, set it back: `branding: { primaryColor: 'oklch(0.205 0 0)' }`.
|
|
1053
|
-
- **Persian digits by default in `fa`** (۱۲۳ and ٬ thousands separators). People switch back to Latin digits in their account menu (Display); the choice is kept per browser.
|
|
1054
|
-
- **Inline children leave navigation.** A resource another resource edits inline (`{ inline: ChildAdmin }`) is no longer in the sidebar, home, group pages, palette or global search; it keeps its URLs, permissions, history and audit entries. To keep it listed: `@AdminResource(Child, { nav: true })`.
|
|
1055
|
-
- **Contract changes** for code that reads the JSON API itself: `FieldSchema.currency` is `{ unit, position }` (a `currency: 'USD'` option still works), and a record's `_perm.actions` maps each record action to its label on that record, or `false` where it may not run (it was a list of names).
|
|
1056
|
-
- **The e2e/screenshot baselines of your own app**, if you keep any, change with the look.
|
|
1057
|
-
|
|
1058
|
-
**New options**
|
|
1059
|
-
|
|
1060
|
-
- **Currency**: `forRoot({ currency: { unit: { en: 'Toman', fa: 'تومان' } } })` labels every `money` field without a unit of its own; a field's `currency` (a code, or `{ unit, position }`) wins.
|
|
1061
|
-
- **A curated menu**: `forRoot({ menu: { sections: [{ key: 'sales', label: { fa: 'فروش' }, icon: 'shopping-cart', items: [{ resource: 'order', badge: { 'filter[status][eq]': 'paid' } }, { page: 'shop' }, { href: 'https://shop.example', label: 'Shop' }] }] } })`. Sections replace module groups in the sidebar, home, group pages, breadcrumbs and the palette; everything not placed goes into «Advanced», collapsed. Badges are counted for each user through the list's scoped count (`GET /api/menu/badges`, refreshed every minute).
|
|
1062
|
-
- **`nav: false`** on `@AdminResource` takes any resource out of navigation.
|
|
1063
|
-
- **Computed list columns**: `list.computed: { picture: { label, kind: 'image', source: { first: 'media', field: 'image', by: 'sort' } }, stock: { label, kind: 'badge', source: 'stock', map: (value, row) => ({ label, tone }) }, variants: { label, kind: 'count', source: { aggregate: 'count', relation: 'variants' }, sortable: true }, active: { label, kind: 'toggle', source: { toggle: 'status', on: 'active', off: 'archived' } } }`, named in `list.columns`. Kinds: image, title (with `subline`), money (with `previous`), badge, count, toggle; sources: a field or path, an aggregate or first row of a one-to-many relation (only the rows the viewer sees), an enum toggle, or `{ compute: (rows, ctx) => …, fields }` called once per page. A column reading something the viewer cannot see is cut.
|
|
1064
|
-
- **List tabs**: `list.tabs: [{ key: 'all', label }, { key: 'active', label, filter: { 'filter[status][eq]': 'active' } }, { key: 'out', label, where: (qb) => qb.andWhere(qb.alias + '.stock = 0') }]` (at most six), counted per user (`GET /api/resources/:r/tab-counts`).
|
|
1065
|
-
- **Primary record actions with per-record labels**: `@AdminAction({ primary: true, label: { static: 'Next step', for: (order) => (order.status === 'draft' ? 'Mark paid' : null) } })`: a filled button last in the record's header; `null` hides it on that record (and a run is refused).
|
|
1066
|
-
- **The record page**: `form.layout: { main: [...sections], aside: [{ title, fields: ['status', 'total'] }, { title, fields: { relation: 'customerId', fields: ['phone'] }, link: true }] }`, `form.mode: 'view'` (opens as text until «Edit»), `form.header: { badges, subtitle: ['customer', { computed: 'items' }], stepper: 'fulfillment' }`.
|
|
1067
|
-
- **Inline presentation**: an inline's `readonly`, `computed` (child computed columns as table columns) and `cards: { markFirst }`; a `{ summary: [{ label, value: 'total' | { computed } }] }` layout node; a field's `warnIf: { empty: true, message }` (a soft warning that never blocks a save).
|
|
1068
|
-
- **A stepper**: `fields: { fulfillment: { widget: 'stepper', exclude: ['cancelled'], history: { inline: StatusLogAdmin, value: 'value', at: 'at', where: { field: 'fulfillment' } } } }` shows an ordered enum as steps with the time each was reached.
|
|
1069
|
-
- **The accent colour, in the admin**: `forRoot({ appearance: {} })` (add `ADMIN_SETTING_ENTITIES` to the DataSource) lets people with `appearance.manage` set the accent for everyone (account menu → Display → «Use for everyone»); everyone may pick their own, kept in their browser. Order: their own, the admin-wide one, `branding.primaryColor`.
|
|
1070
|
-
- **A dashboard**: `@AdminWidget('sales', { type: 'stat' | 'chart' | 'table' | 'progress' | 'list', title, order, size, permission })` providers with `load(params, ctx)`; the period (today, week, month, year, a range; Jalali-aware) is computed by the UI and checked by the server. Codes `dashboard.<name>` (or the widget's `permission`); `dashboard.*` grants every widget. With a widget to show, the dashboard replaces the home page.
|
|
1071
|
-
- **`@nest-my-admin/testing`**: `expectNoLeaks` also crawls menu badges, tab counts, computed cells and the dashboard.
|
|
1072
|
-
|
|
1073
|
-
Still missing (planned): printing a record (an invoice, a shipping label) and exporting a list to Excel.
|
|
1074
|
-
|
|
1075
|
-
## Upgrading to 0.3.2
|
|
1076
|
-
|
|
1077
|
-
Nothing to change in an app on 0.3.1. New: `@AdminResource(Entity, { readonly: true })` for records only your own code writes (logs, orders, snapshots): the admin offers no New, Save, Delete, editable cell or inline add and remove, and its API answers 403 to every write, whatever the roles say; the resource's `@AdminAction`s still run with their usual permissions. The schema says `readonly: true`. Before, the way to get this was to throw from `create`/`update`/`delete`, and a superuser still saw the buttons.
|
|
1078
|
-
|
|
1079
|
-
## Upgrading to 0.3.1
|
|
1080
|
-
|
|
1081
|
-
A fix, nothing to change in an app on 0.3.0. A property of a create DTO that is not a column (a value your `create()` uses, such as the price of a first variant) is no longer shown on the edit form as an empty read-only field; a create-only column (a number fixed once saved) still is. `form.readonly` in the schema changes accordingly.
|
|
1082
|
-
|
|
1083
|
-
## Upgrading to 0.3.0
|
|
1084
|
-
|
|
1085
|
-
Nothing in 0.3.0 breaks an app that runs on 0.2.1: no option or export was removed or changed, no table or stored key changed, and a resource without inlines answers exactly as before (responses only gain fields). All five packages are 0.3.0; upgrade them together, as before.
|
|
1086
|
-
|
|
1087
|
-
**New**
|
|
1088
|
-
|
|
1089
|
-
- **Inlines**: child resources edited in the parent's form and saved with it in one transaction. See [Inlines](#inlines).
|
|
1090
|
-
- **`AdminFiles.register()` and `release()`**: files a host stored itself become files of a record's field. See "Registering files yourself" under [Files](#files-images-and-rich-text).
|
|
1091
|
-
- **A key column named `id` without a label is "شناسه" in Persian** (still "Id" in English).
|
|
1092
|
-
|
|
1093
|
-
**What a 0.2.1 app may notice**
|
|
1094
|
-
|
|
1095
|
-
- `relationOptions(field, qb, ctx, values)`: a key named `_parent` in `values` now has a meaning when the picker belongs to an inline (`?parent=` on the options route); without `?parent=` it is passed through as before.
|
|
1096
|
-
- The UI's lists, sidebar and header: the sidebar and the header stay in place while the page scrolls, and in right-to-left languages table headers start on the right like their cells.
|
|
1097
|
-
|
|
1098
|
-
## Upgrading to 0.2.1
|
|
1099
|
-
|
|
1100
|
-
Nothing in 0.2.1 breaks an app that runs on 0.2.0: no option or export was removed or changed, no table or stored key changed, and permissions decide as before. All five packages (`@nest-my-admin/core`, `ui`, `auth`, `testing` and `nest-my-admin`) are 0.2.1. Upgrade them together: `@nest-my-admin/auth` and `@nest-my-admin/testing` peer on the exact core version (0.2.1 of either does not install next to core 0.2.0), and core brings the UI of its own version.
|
|
1101
|
-
|
|
1102
|
-
**New**
|
|
1103
|
-
|
|
1104
|
-
- **`@AdminGroup` by key, for any members.** A module's `@AdminGroup` now configures the group of its key whoever the members are, also when they are only settings pages that say `group: '<key>'`, and also when the module provides nothing. See [Sidebar groups and order](#sidebar-groups-and-order).
|
|
1105
|
-
- **`order`** on `@AdminResource` and `@AdminSettingsPage`: the place inside the group (lower first, default 100, then by label).
|
|
1106
|
-
- **`AdminFiles`** (`publicFile(key)`, `openPublic(key)`): which keys are public files, for a host that serves them itself. See "Serving public files yourself" under [Files](#files-images-and-rich-text).
|
|
1107
|
-
- **The page is in the admin's language**: `GET <path>/` answers `<html lang dir>`, `<title>` and `Content-Language` for the default `locale` and your `title`.
|
|
1108
|
-
- **Documented:** the storage key of a settings page's file, `page/<name>/<field>/<yyyy>/<mm>/<uuid><ext>` (unchanged; it was only in the source).
|
|
1109
|
-
|
|
1110
|
-
**What a 0.2.0 app may notice**
|
|
1111
|
-
|
|
1112
|
-
- **A sidebar group can change its label, icon and place.** In 0.2.0 an `@AdminGroup` was read only when its module provided a resource, or a page without `group`. A group reached only through `group: '<key>'` therefore showed the key as its label ("Settings"), with no icon and order 100, even though a module carried `@AdminGroup({ key: '<key>', … })` (or was named like the key and carried `@AdminGroup` without a `key`). In 0.2.1 that module's label, icon and order apply. Group keys, URLs (`/g/<key>`) and permissions are unchanged. If you worked around it by leaving `group` off some pages, both spellings now give the same group.
|
|
1113
|
-
- A module that carries `@AdminGroup` now also wins over a module without the decorator whose name gives the same key, whichever is imported first (in 0.2.0, the one whose resource was registered first).
|
|
1114
|
-
- Two modules that configure one key differently: the first in import order wins (in 0.2.0, the first that had a resource or a page registered, which is nearly always the same), and 0.2.1 logs a warning at boot that names both.
|
|
1115
|
-
- **The served HTML.** `GET <path>/` used to answer `<html lang="en" dir="ltr">` and `<title>Admin</title>` whatever the admin's language. It now answers with the default `locale` (`lang`, `dir`, `Content-Language`) and your `title` in it. The page is still one page for every request (it does not vary by `Accept-Language`, and there is no `Vary` header), and `Cache-Control` is still `no-cache`. An admin with `locale: 'en'` and no `title` gets byte-for-byte what it got before, plus `Content-Language: en`. The UI behaves as before once it runs. If you serve your own UI build (`uiDistPath`), the `lang` and `dir` of its `<html>` and the `<title>` of its `<head>` are replaced the same way.
|
|
1116
|
-
- **Boot fails for `order` that is not a finite number** on a resource or a settings page. TypeScript did not accept the option in 0.2.0, so only untyped code that already passed one can be hit.
|
|
1117
|
-
|
|
1118
|
-
## Upgrading to 0.2
|
|
1119
|
-
|
|
1120
|
-
**Boot can now fail.** Each of these stops the app at start, with a message that names the class:
|
|
1121
|
-
|
|
1122
|
-
- An app that ran on 0.1 can be hit by one of them without using anything new: `widget: 'password'` (and the new `sensitive` and `secret`) on a property inside a group, that is a nested DTO or an embedded entity. Nothing applied those options there. Move the field to the top level.
|
|
1123
|
-
- The others come with the features of 0.2, as you adopt them:
|
|
1124
|
-
- a settings page whose name is reserved (`view`, `create`, `update`, `delete`, `purge`, `field`, `action`), a resource's name, or a custom permission of a resource (`order.export` and a page named `export`); a `permissions` entry that is a page's code (`page.<name>`, `page.<name>.update`); a resource named `page`, or whose name starts with `page:`, in an admin that has settings pages;
|
|
1125
|
-
- an action's input DTO with a `file`, `image` or `richtext` widget;
|
|
1126
|
-
- `atomic` on an action without `bulk: true`, on a resource action, or with `transactions: false`;
|
|
1127
|
-
- an action method named like a built-in operation (`view`, `create`, `update`, `delete`, `restore`, `purge`) or like a method of `AdminResourceBase`;
|
|
1128
|
-
- `@AdminCan('<name>')` whose name is not `update`, `delete` or a record action of that resource (a typo, or the name of a resource action);
|
|
1129
|
-
- `files` without `ADMIN_FILE_ENTITIES`, or `audit` without `ADMIN_AUDIT_ENTITIES`, in the entities of the DataSource they name.
|
|
1130
|
-
|
|
1131
|
-
**Behaviour that changed**
|
|
1132
|
-
|
|
1133
|
-
- **Core and UI go together.** `@nest-my-admin/ui` 0.2.0 is installed with `@nest-my-admin/core` 0.2.0; if you pin or override either, keep both on 0.2.0. `GET /api/session` now always carries `audit: { enabled, view }` (`SessionResponse.audit`), which the 0.2 UI reads.
|
|
1134
|
-
- **A 401 thrown by your code inside a write or a settings page's `load()` is answered as 400** with your message. The UI reads every 401 as "signed out"; the admin's own 401 is unchanged.
|
|
1135
|
-
- **Deleting a record releases its files only when the row is really gone** (read again inside the write). A `delete()` override that keeps the row keeps the files; a purge always releases them. A row that goes where the write cannot see it (MySQL and a service that ignores `ctx.manager`, or a delete queued for later) leaves its files as orphans. See [Files, images and rich text](#files-images-and-rich-text).
|
|
1136
|
-
- **With `audit` on:**
|
|
1137
|
-
- every admin write reads the stored row before and after your method, and inserts one row into `nma_audit` in the same transaction. If that insert fails, the write fails (500);
|
|
1138
|
-
- entry ids are 32-bit integers on Postgres and MySQL (2.1 billion entries); set `retentionDays` on a busy admin;
|
|
1139
|
-
- a purge always closes the record's history, even when your `purge()` keeps the row;
|
|
1140
|
-
- **not in the log:** changes made outside the admin, changes to `select: false` columns, and, on MySQL, a relation changed by a service that ignores `ctx.manager`;
|
|
1141
|
-
- **whatever is typed into the username box of a failed sign-in is stored** as typed, cut to 200 characters: a password typed there by mistake ends up in the log. Failed sign-ins are capped per address and username, per address, and per process.
|
|
1249
|
+
What to change, and what you may notice, for every release: [UPGRADING.md](https://github.com/phantomboy0/nest-my-admin/blob/main/UPGRADING.md).
|
|
1142
1250
|
|
|
1143
1251
|
## Develop
|
|
1144
1252
|
|
|
@@ -1153,4 +1261,18 @@ bun run e2e # Playwright (run `bunx playwright install
|
|
|
1153
1261
|
cd examples/demo-api && bun src/main.ts # DATABASE_URL=postgres://… or mysql://… to use a real database
|
|
1154
1262
|
```
|
|
1155
1263
|
|
|
1264
|
+
The README's screenshots are taken from the showcase shop in the Chrome installed on your machine (nothing is
|
|
1265
|
+
downloaded):
|
|
1266
|
+
|
|
1267
|
+
```bash
|
|
1268
|
+
cd examples/demo-api
|
|
1269
|
+
NMA_DEMO_SHOWCASE=1 NMA_UPLOAD_DIR=$(mktemp -d) PORT=3100 bun src/main.ts &
|
|
1270
|
+
bun scripts/showcase-shots.ts # all of docs/images, or name some: bun scripts/showcase-shots.ts order rtl
|
|
1271
|
+
bun scripts/render-product-images.ts # only after changing the catalog: redraws the product pictures
|
|
1272
|
+
```
|
|
1273
|
+
|
|
1156
1274
|
Design: `docs/superpowers/specs/2026-09-29-nest-my-admin-design.md`.
|
|
1275
|
+
|
|
1276
|
+
## License
|
|
1277
|
+
|
|
1278
|
+
MIT
|
|
@@ -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
|
}
|
package/dist/contract.d.ts
CHANGED
|
@@ -153,6 +153,8 @@ export interface FormLayoutInline {
|
|
|
153
153
|
computed?: string[];
|
|
154
154
|
/** A marker on the first card by `order` («Main picture»). */
|
|
155
155
|
markFirst?: string;
|
|
156
|
+
/** Not on the form of a new record (rows are added once the parent exists). */
|
|
157
|
+
existingOnly?: true;
|
|
156
158
|
}
|
|
157
159
|
/** Label and value rows in a card (an order's totals): a field of the record, or one of its computed columns (`_computed`). */
|
|
158
160
|
export interface FormLayoutSummary {
|
|
@@ -524,6 +526,8 @@ export interface ResourceSchema {
|
|
|
524
526
|
aside?: AsideCardSchema[];
|
|
525
527
|
/** `view`: an existing record opens as text until «Edit». */
|
|
526
528
|
mode?: 'view';
|
|
529
|
+
/** `edit`: saving a new record opens it instead of going back to the list. */
|
|
530
|
+
afterCreate?: 'edit';
|
|
527
531
|
/** The record's header: badge fields, and a subtitle of field values and computed columns (`_computed`). */
|
|
528
532
|
header?: {
|
|
529
533
|
badges?: string[];
|
|
@@ -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
|
}
|
|
@@ -11,6 +11,15 @@ import { AdminRbac } from '../rbac/rbac.service.js';
|
|
|
11
11
|
import type { ResolvedAdminOptions } from '../options.js';
|
|
12
12
|
import { ResourceRegistry } from '../registry/resource-registry.js';
|
|
13
13
|
import { AdminApiService } from '../api/admin-api.service.js';
|
|
14
|
+
/** Whether the Express application has a route of its own for `GET /` (`router` in Express 5, `_router` in 4). */
|
|
15
|
+
export declare function hasRootRoute(app: {
|
|
16
|
+
router?: {
|
|
17
|
+
stack?: unknown[];
|
|
18
|
+
};
|
|
19
|
+
_router?: {
|
|
20
|
+
stack?: unknown[];
|
|
21
|
+
};
|
|
22
|
+
}): boolean;
|
|
14
23
|
/**
|
|
15
24
|
* Mounts one handler on the host's HTTP adapter (spec D12). Registered during onModuleInit, which runs
|
|
16
25
|
* after host middleware added in main.ts and before Nest's 404 handler. Host guards, interceptors,
|
|
@@ -47,5 +56,7 @@ export declare class AdminHttpServer implements OnModuleInit {
|
|
|
47
56
|
private viewAs;
|
|
48
57
|
private sessionResponse;
|
|
49
58
|
onModuleInit(): void;
|
|
59
|
+
/** The bare address goes to the admin. Only GET and HEAD of exactly `/`: every other address keeps its own answer. */
|
|
60
|
+
private redirectRoot;
|
|
50
61
|
private handle;
|
|
51
62
|
}
|
|
@@ -62,6 +62,11 @@ function earlyError(error) {
|
|
|
62
62
|
}
|
|
63
63
|
return undefined;
|
|
64
64
|
}
|
|
65
|
+
/** Whether the Express application has a route of its own for `GET /` (`router` in Express 5, `_router` in 4). */
|
|
66
|
+
export function hasRootRoute(app) {
|
|
67
|
+
const stack = (app.router?.stack ?? app._router?.stack ?? []);
|
|
68
|
+
return stack.some(({ route }) => (route?.path === '/' || route?.path === '') && (route.methods?.get === true || route.methods?._all === true));
|
|
69
|
+
}
|
|
65
70
|
/**
|
|
66
71
|
* Mounts one handler on the host's HTTP adapter (spec D12). Registered during onModuleInit, which runs
|
|
67
72
|
* after host middleware added in main.ts and before Nest's 404 handler. Host guards, interceptors,
|
|
@@ -411,8 +416,30 @@ let AdminHttpServer = class AdminHttpServer {
|
|
|
411
416
|
const { status, body } = toErrorResponse(error, correlationId, this.logger, { errorMapper: this.options.errorMapper });
|
|
412
417
|
sendJson(res, status, body);
|
|
413
418
|
});
|
|
419
|
+
if (this.options.rootRedirect)
|
|
420
|
+
this.redirectRoot(adapter);
|
|
414
421
|
this.logger.log(`Admin mounted at ${this.options.path}`);
|
|
415
422
|
}
|
|
423
|
+
/** The bare address goes to the admin. Only GET and HEAD of exactly `/`: every other address keeps its own answer. */
|
|
424
|
+
redirectRoot(adapter) {
|
|
425
|
+
// Nest adds the host's routes after this hook, so whether one answers `/` is only known once a request comes.
|
|
426
|
+
let hostAnswers;
|
|
427
|
+
const target = `${this.options.path}/`;
|
|
428
|
+
adapter.use((req, res, next) => {
|
|
429
|
+
const isRoot = (req.method === 'GET' || req.method === 'HEAD') && (req.url ?? '').split('?')[0] === '/';
|
|
430
|
+
if (!isRoot) {
|
|
431
|
+
next();
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
hostAnswers ??= hasRootRoute(adapter.getInstance());
|
|
435
|
+
if (hostAnswers) {
|
|
436
|
+
next();
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
res.writeHead(302, { Location: target });
|
|
440
|
+
res.end();
|
|
441
|
+
});
|
|
442
|
+
}
|
|
416
443
|
async handle(req, res, next) {
|
|
417
444
|
let ctx;
|
|
418
445
|
let resourceName;
|
|
@@ -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;
|
package/dist/options.d.ts
CHANGED
|
@@ -109,6 +109,12 @@ export interface AdminAuditOptions {
|
|
|
109
109
|
export interface AdminModuleOptions {
|
|
110
110
|
/** Mount path of the admin UI and API. Default `/admin`. */
|
|
111
111
|
path?: string;
|
|
112
|
+
/**
|
|
113
|
+
* Send a browser that opens the bare address (`GET /`) to the admin, with a temporary redirect. Default `false`:
|
|
114
|
+
* the redirect would show anyone where the admin lives. A route of the host's own at `/` keeps answering; a file
|
|
115
|
+
* served at `/` by a middleware does not, because the admin's check sees routes only.
|
|
116
|
+
*/
|
|
117
|
+
rootRedirect?: boolean;
|
|
112
118
|
/** Title shown in the UI, in one or several languages. Default `Admin`. */
|
|
113
119
|
title?: LocalizedText;
|
|
114
120
|
/** Default UI language. Default `en`. */
|
|
@@ -183,6 +189,7 @@ export interface AdminModuleOptions {
|
|
|
183
189
|
}
|
|
184
190
|
export interface ResolvedAdminOptions {
|
|
185
191
|
path: string;
|
|
192
|
+
rootRedirect: boolean;
|
|
186
193
|
title: LocalizedText;
|
|
187
194
|
locale: string;
|
|
188
195
|
locales: string[];
|
package/dist/options.js
CHANGED
|
@@ -4,6 +4,9 @@ import { checkCurrency } from './schema/currency.js';
|
|
|
4
4
|
import { DEFAULT_MAX_FILE_BYTES, MAX_FILE_BYTES } from './schema/field-config.js';
|
|
5
5
|
import { describeValue, HostContractError } from './host-contract.js';
|
|
6
6
|
export function resolveAdminOptions(options = {}) {
|
|
7
|
+
if (options.rootRedirect !== undefined && typeof options.rootRedirect !== 'boolean') {
|
|
8
|
+
throw new Error('nest-my-admin: `rootRedirect` must be true or false');
|
|
9
|
+
}
|
|
7
10
|
const raw = (options.path ?? '/admin').trim();
|
|
8
11
|
const path = '/' + raw.replace(/^\/+|\/+$/g, '');
|
|
9
12
|
if (path === '/') {
|
|
@@ -21,6 +24,7 @@ export function resolveAdminOptions(options = {}) {
|
|
|
21
24
|
throw new Error(`nest-my-admin: locale "${locale}" must be one of locales (${locales.join(', ')})`);
|
|
22
25
|
return {
|
|
23
26
|
path,
|
|
27
|
+
rootRedirect: options.rootRedirect === true,
|
|
24
28
|
title: options.title ?? 'Admin',
|
|
25
29
|
locale,
|
|
26
30
|
locales,
|
|
@@ -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.4",
|
|
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.4"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"@nestjs/common": "^11.0.0 || ^12.0.0",
|