nest-my-admin 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,12 +14,17 @@ The package is ESM; CommonJS apps load it through Node's `require(esm)`. A Commo
14
14
  `"module": "nodenext"` (the `nest new` default since Nest 11) needs TypeScript 5.8+; with `"module": "commonjs"` any 5.x works.
15
15
 
16
16
  ```bash
17
- npm install @nest-my-admin/core # the admin (brings the prebuilt UI with it)
18
- npm install @nest-my-admin/auth # optional: the built-in sign-in
19
- npm install -D @nest-my-admin/testing # optional: test helpers
17
+ npm install nest-my-admin # the admin, its UI, the built-in sign-in and the test helpers, at one version
18
+ npm install -D @nestjs/testing # only if you use the test helpers
20
19
  ```
21
20
 
22
- `nest-my-admin` (no scope) is the same package as `@nest-my-admin/core` under a shorter name: it re-exports it, at the same version.
21
+ ```ts
22
+ import { AdminModule, AdminResource } from 'nest-my-admin';
23
+ import { builtinAuth } from 'nest-my-admin/auth'; // the built-in sign-in
24
+ import { createAdminTestingModule } from 'nest-my-admin/testing'; // in your tests
25
+ ```
26
+
27
+ `nest-my-admin`, `nest-my-admin/auth` and `nest-my-admin/testing` are `@nest-my-admin/core`, `@nest-my-admin/auth` and `@nest-my-admin/testing` under one name: the same objects, always at one version, so they cannot drift apart. The scoped packages still work on their own (`npm install @nest-my-admin/core @nest-my-admin/auth`, then keep them at one exact version); the examples below use the scoped names, and either import works.
23
28
 
24
29
  ```ts
25
30
  @AdminResource(Product, { icon: 'package' })
@@ -69,6 +74,26 @@ export class SettingsModule {}
69
74
  - **One module per key.** When two modules configure the same key with a different label, icon or order, the first one Nest discovers (import order) wins and a warning is logged at boot. The same options twice are fine.
70
75
  - **`order` inside a group.** `@AdminResource(Entity, { order })` and `@AdminSettingsPage(name, { order })`: lower comes first, then the label in the reader's language; the default is 100, as for groups. A group lists its resources first and its settings pages after them, so `order` sorts resources among resources and pages among pages. The sidebar, the group's page, the home page and the command palette all show this order. `order` must be a finite number, or boot fails.
71
76
 
77
+ #### The menu
78
+
79
+ `forRoot({ menu })` replaces the module groups in the sidebar, the home page, group pages, breadcrumbs and the palette with your own sections; whatever is visible and placed nowhere goes into a last «Advanced» section, collapsed.
80
+
81
+ ```ts
82
+ AdminModule.forRoot({
83
+ menu: {
84
+ sections: [
85
+ { key: 'sales', label: { en: 'Sales', fa: 'فروش' }, icon: 'shopping-cart', items: [{ resource: OrderAdmin, badge: { 'filter[status][eq]': 'paid' } }, { page: 'shop' }, { href: 'https://shop.example', label: 'Shop' }] },
86
+ { group: 'settings' }, // an @AdminGroup: its label, icon and members
87
+ { group: 'catalog', items: [{ resource: 'product' }] }, // its label and icon, your items
88
+ ],
89
+ },
90
+ });
91
+ ```
92
+
93
+ - **Items** name a resource or a settings page, or give its class (`{ resource: OrderAdmin }`, `{ page: ShopSettingsPage }`); a class that is not registered fails boot. A `badge` is a list query whose count shows next to the item, for each user through the list's scoped count.
94
+ - **`{ group: '<key>' }`** takes the label and icon from that `@AdminGroup` (and the section key from its key); whatever you give yourself wins. Without `items` the section lists the group's resources and then its settings pages, in the group's order, as each user may see them. An unknown group fails boot.
95
+ - A section left with nothing the user may see is not shown.
96
+
72
97
  ### Customising lists
73
98
 
74
99
  Put row restrictions in `query(qb, ctx)`. It applies to every read path: the list, GET, PATCH, DELETE, restore and
@@ -163,6 +188,12 @@ relationOptions(field: string, qb: SelectQueryBuilder<any>, ctx: AdminContext, v
163
188
  }
164
189
  ```
165
190
 
191
+ - It may be `async` when it needs to look something up first (use `ctx.manager` when it is set, so a check during a
192
+ write sees that write's transaction). An override that returns `super.relationOptions(...)` under an explicit
193
+ `: SelectQueryBuilder<any>` return type needs that annotation dropped (the base now answers either).
194
+ - Relation ids in `values` and in `values._parent` arrive in the target key's type (a number for an integer key), as
195
+ in write bodies; an id that cannot be one is left out.
196
+
166
197
  ### Entity shapes
167
198
 
168
199
  - **Record ids.** Every record carries `_id`, the id used in URLs: key values in primary-key order, joined by `,`,
@@ -208,6 +239,24 @@ AdminModule.forRoot({
208
239
  locale.
209
240
  - Resources and hooks see it as `ctx.locale`.
210
241
  - Field labels, help, placeholders and enum value labels take the same `{ en, fa }` form (see Fields and forms).
242
+ - A plain string (`label: 'سفارش‌ها'`) is one text for every language: write labels once in your own language when that is all you need.
243
+ - **Your own translations (`translate`).** Resolve every text you declare with your own i18n instead of writing each language inline:
244
+
245
+ ```ts
246
+ AdminModule.forRoot({
247
+ locale: 'fa',
248
+ locales: ['fa', 'en'],
249
+ translate: ({ key, text, locale }) => (locale === 'en' && key ? english[key] : undefined),
250
+ });
251
+ ```
252
+
253
+ - It is asked for every text of a request, before the declared one; `undefined` (or `''`) keeps the declared text, and a throw keeps it too (logged once per key). It runs per request: keep it cheap.
254
+ - `text` is what you declared, or the default (`Created at` for `createdAt`) when you declared nothing, so fields you never labelled can be translated too.
255
+ - `key` names the text: `title`, `group.<key>`, `menu.<section>` (a `{ group }` section without a label of its own is its group's text, `group.<key>`), `menu.advanced`, `resource.<r>`, `resource.<r>.fields.<f>.label` (and `.help`, `.placeholder`, `.enumLabels.<value>`; nested fields by their dotted path, `hours.*.day`), `resource.<r>.actions.<a>.label` (and `.confirm`, `.fields.<f>.label` of its input), `resource.<r>.prints.<p>.label`, `resource.<r>.list.tabs.<t>.label`, `resource.<r>.list.computed.<c>.label`, `resource.<r>.form.<key>` for a layout node (section, tab, summary, inline, aside card) you give a `key`, `page.<p>` and `page.<p>.fields.<f>.label`, `widget.<w>.title`.
256
+ - Texts without a stable name (layout nodes without a `key`, action messages, record links, badge labels) come with `text` only.
257
+ - Role labels are stored with the roles and shown as they are.
258
+ - **The UI's own texts** (Save, Delete, «Add {name}» …) go through the same function as `ui.<key>` (the keys of the UI's English texts, listed in `messages.json` of the built UI). They are asked once per locale at boot, so for `ui.` keys `translate` must give the same answer every time; `text` is the built-in text of that locale (English when the UI has none). An answer must keep the `{name}` placeholders of the original, or boot fails naming the key and the locale. Only the texts you change are sent to the browser.
259
+ - That also adds UI languages the admin does not ship: put `'de'` in `locales` and answer `ui.` keys for it; whatever you leave out is English.
211
260
  - **Branding.**
212
261
  - `primaryColor` may be hex, `rgb()`, `hsl()` or `oklch()`, and `radius` a length. Text on the primary colour is
213
262
  chosen from its lightness.
@@ -284,6 +333,13 @@ export class ProductAdmin extends AdminResourceBase<Product> {
284
333
  - `readonly: true` shows the field on edit forms as text with a lock and removes it from `form.update`.
285
334
  - `readonlyIf(record)` runs on the server for every record. Records carry `_readonly` (the fields it locks), and a PATCH that sends a locked field is a 422 `{ field: ['is read-only'] }` before your `update` runs. That covers inline cell edits too.
286
335
  - A `readonlyIf` that throws locks its field and is logged once.
336
+ - To lock a record from one place, override `readonlyFields(record, ctx)` on the resource and return the names to lock; they add to every `readonlyIf`, with the same effects (`_readonly`, the 422, inline rows). `this.updateFields` lists the update form, so "everything but these" is `this.updateFields.filter((name) => !KEEP.has(name))`. Unknown names are ignored (logged once); a throw locks the whole update form. It runs per record, so keep it synchronous and cheap.
337
+
338
+ ```ts
339
+ override readonlyFields(product: Product): readonly string[] {
340
+ return product.crmId ? this.updateFields.filter((name) => !SHOP_FIELDS.has(name)) : [];
341
+ }
342
+ ```
287
343
  - Create ignores it.
288
344
  - **`showIf`** hides a field while other fields do not hold the given value (or one of the values), evaluated live in the browser. A hidden field is not sent and not checked. It is presentation, not a permission: the server keeps the stored value.
289
345
  - **`slugFrom`** makes the slug widget fill itself from another field. It keeps the letters of every script and stops once someone types in it, or when it already holds a value.
@@ -589,6 +645,19 @@ export class OrderAdmin extends AdminResourceBase<Order> {
589
645
 
590
646
  **Permissions.** An inline never widens access: a user reads, adds, changes, removes or reorders a child through an inline only as they could through the child's own resource (`order-line.view`, `.create`, `.update`, `.delete`, its field levels and scopes, each row's `@AdminCan`), and only the children of this parent. A user without `<child>.view` does not see the inline at all; without `<child>.delete` there is no remove button, and a crafted delete is a 403 that saves nothing. Since children are saved with the parent, the save also needs `<parent>.create` (a new parent) or `<parent>.update`. View-as shows inlines read-only, like everything else.
591
647
 
648
+ **Adding rows, per parent.** `@AdminCan('create')` on the child decides whether rows may be added under a given parent: it gets the parent record (as the parent resource reads it) and answers `true` to allow.
649
+
650
+ ```ts
651
+ @AdminResource(OrderLine)
652
+ class OrderLineAdmin extends AdminResourceBase<OrderLine> {
653
+ @AdminCan('create') notShipped(order: Order) {
654
+ return order.status !== 'shipped';
655
+ }
656
+ }
657
+ ```
658
+
659
+ The parent's records carry `_perm.inlines.<child>.create`, and the inline hides «Add» when it is `false`. A save that adds rows anyway is a 403 that writes nothing; so is a `POST` to the child's own endpoint whose link field names such a parent, or a `PATCH` that moves a row to one. The rule sees the parent as the save leaves it: a parent created in the same save once it exists, and a parent changed in the same save with its changes (locking a parent and adding rows in one save is refused, unlocking and adding is allowed). A link to a parent the parent resource does not show the user is a 422, like a missing one. A rule that throws says no (logged once). It may only be declared on an inline child (boot error otherwise).
660
+
592
661
  **Saving.** The form sends, next to the parent's fields, `_inlines: { <child>: { create, update, delete, order } }` (`InlineChanges` in the contract): new rows with a `_key`, changed fields of changed rows with their `_id` (and `_version` for a child with a version column), the ids to delete, and the new order. Inside the parent's write the parent is saved first (a save with only inline changes does not update the parent), then each inline in layout order: deletes, updates, creates, each through the child resource's own `delete`/`update`/`create` and its write participants (files, audit). Any error rolls back everything; errors name the row (`_inlines.order-line.create.2.quantity`, `_inlines.order-line.update.17.unitPrice`) and the form shows them on that row. At most 500 entries per inline per request.
593
662
 
594
663
  **Options that depend on the parent.** A child's `relationOptions(field, qb, ctx, values)` receives `values._parent`: the parent form's values as the user sees them (unsaved, in the picker; body over stored, on save), with `_parent._resource` naming the parent. Use it to narrow a picker to what the parent allows, such as the attributes of the product's category.
@@ -603,11 +672,19 @@ Every create, update and delete runs in one database transaction. Pass `ctx.mana
603
672
  join it — a hook or service that throws afterwards rolls everything back:
604
673
 
605
674
  ```ts
606
- create(dto: CreateProductDto, ctx: AdminContext) {
607
- return this.products.create(dto, ctx.manager); // service: manager ? manager.getRepository(Product) : this.products
675
+ class ProductAdmin extends AdminResourceBase<Product, number> {
676
+ override create(dto: CreateProductDto, ctx: AdminWriteContext) {
677
+ return this.products.create(dto, ctx.manager); // service: manager ? manager.getRepository(Product) : this.products
678
+ }
679
+ override update(id: number, dto: UpdateProductDto, ctx: AdminWriteContext) {
680
+ return this.products.update(id, dto, ctx.manager);
681
+ }
608
682
  }
609
683
  ```
610
684
 
685
+ - **Typed parameters.** Your overrides may name their own types: the DTO class (`dto: CreateProductDto`, no cast), `AdminWriteContext` (a context whose `manager` is always set, so no `ctx.manager!`) and the id type through the second type parameter, `AdminResourceBase<Product, number>` (the admin already turns ids into the key's type: a number for an integer key, a string for bigint, uuid and text keys, `{ key: value }` for composite keys). `AdminContext` keeps working everywhere.
686
+ - **`transactions: false`**: writes still get `ctx.manager`, the DataSource's own (not a transaction).
687
+
611
688
  Services that keep using their own injected repository still work, but on Postgres/MySQL they write outside the
612
689
  transaction, on a separate pooled connection, and can block on the admin transaction's locks (writing the same row or
613
690
  the same unique key blocks until the admin transaction ends on both drivers; inserting a row with a foreign key to the
@@ -845,6 +922,40 @@ export class EmployeeAdmin extends AdminResourceBase<Employee> {
845
922
  - **Read replicas.** Reads outside a transaction (that check after commit; with `transactions: false` the before and after images too) go through `dataSource.manager`, which TypeORM replication may send to a replica. A lagging replica then still shows a deleted row (no stamp), or shows an update as unchanged (a smaller diff, or no entry).
846
923
  - **Scopes that depend on a field.** A record's history is open to whoever may open the record now. A reader whose scope depends on a field (`ownerId`, a status) reads the values the record had before it entered their scope, in the fields they may view.
847
924
 
925
+ ## Writing less
926
+
927
+ Things hosts tend to write by hand that the admin already does:
928
+
929
+ - **Your own errors.** One `forRoot({ errorMapper })` turns your services' exceptions into admin errors everywhere (resource methods, hooks, actions, bulk actions, settings pages): no `try`/`catch` around each call.
930
+ - **Records only your code writes** (orders, logs, snapshots): `@AdminResource(Entity, { readonly: true })`. No New, Save, Delete, editable cell or inline add and remove is offered and every write is a 403; actions still run. No need to throw from `create`/`update`/`delete` or declare empty forms.
931
+ - **One DTO for create and update.** Without `form.update`, the create DTO is used for updates too and a PATCH is always checked as a partial. Write an update DTO only when updates take other fields.
932
+ - **Typed overrides.** `override create(dto: CreateProductDto, ctx: AdminWriteContext)` and `AdminResourceBase<Product, number>`: no `dto as …`, no `ctx.manager!`, no `Number(id)` (see Transactions, context and errors).
933
+ - **A shared base class with services.** Inject them as properties (`@Inject(CatalogOwnership) protected readonly ownership: CatalogOwnership`): Nest injects properties of a base class into every subclass, so subclasses need no constructor of their own just to pass a service up.
934
+ - **Inline children stay out of the sidebar** by default (`nav: false` unless they set `nav`): no extra group to hide them in.
935
+ - **Labels in one language** are plain strings; other languages can come from `translate` (see Languages, theme and branding).
936
+
937
+ ## Upgrading to 0.7.1
938
+
939
+ 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.
940
+
941
+ ## Upgrading to 0.7
942
+
943
+ Nothing needs changing in an app on 0.6, except two type-only cases:
944
+
945
+ - an override that returns `super.relationOptions(...)` under an explicit `: SelectQueryBuilder<any>` return type: drop the annotation (`relationOptions` may now be async);
946
+ - code that names `AdminMenuSection['items']` as a type: wrap it in `NonNullable<…>` (a `{ group }` section's items are optional);
947
+ - 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'`.
948
+
949
+ New:
950
+
951
+ - `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.
952
+ - `readonlyFields(record, ctx)` and `this.updateFields` (Fields and forms): lock a record's fields from one place.
953
+ - `AdminWriteContext` and `AdminResourceBase<T, Id>` (Transactions, context and errors); with `transactions: false` writes now get the DataSource's own `ctx.manager`.
954
+ - `relationOptions` may be async, and relation ids in its `values` (and `values._parent`) have the key's type.
955
+ - `@AdminCan('create')` on an inline child (Inlines): whether rows may be added under a parent; `_perm.inlines` on the parent's records.
956
+ - Menu sections from groups (`{ group: 'settings' }`) and menu items by class (The menu).
957
+ - Layout nodes and aside cards take an optional `key`, for `translate`.
958
+
848
959
  ## Upgrading to 0.4
849
960
 
850
961
  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".
package/auth.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from '@nest-my-admin/auth';
package/auth.js ADDED
@@ -0,0 +1,2 @@
1
+ // `nest-my-admin/auth`: @nest-my-admin/auth under the unscoped name.
2
+ export * from '@nest-my-admin/auth';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nest-my-admin",
3
- "version": "0.6.0",
4
- "description": "Django-admin-class admin panel for NestJS + TypeORM (the same package as @nest-my-admin/core)",
3
+ "version": "0.7.1",
4
+ "description": "Django-admin-class admin panel for NestJS + TypeORM: @nest-my-admin/core, /auth and /testing under one name",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -18,9 +18,19 @@
18
18
  "import": "./index.js",
19
19
  "default": "./index.js"
20
20
  },
21
+ "./auth": {
22
+ "types": "./auth.d.ts",
23
+ "import": "./auth.js",
24
+ "default": "./auth.js"
25
+ },
26
+ "./testing": {
27
+ "types": "./testing.d.ts",
28
+ "import": "./testing.js",
29
+ "default": "./testing.js"
30
+ },
21
31
  "./package.json": "./package.json"
22
32
  },
23
- "files": ["index.js", "index.d.ts"],
33
+ "files": ["index.js", "index.d.ts", "auth.js", "auth.d.ts", "testing.js", "testing.d.ts"],
24
34
  "engines": {
25
35
  "node": ">=20.19.0"
26
36
  },
@@ -29,6 +39,8 @@
29
39
  "typecheck": "tsc -p tsconfig.json --noEmit"
30
40
  },
31
41
  "dependencies": {
32
- "@nest-my-admin/core": "0.6.0"
42
+ "@nest-my-admin/auth": "0.7.1",
43
+ "@nest-my-admin/core": "0.7.1",
44
+ "@nest-my-admin/testing": "0.7.1"
33
45
  }
34
46
  }
package/testing.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from '@nest-my-admin/testing';
package/testing.js ADDED
@@ -0,0 +1,2 @@
1
+ // `nest-my-admin/testing`: @nest-my-admin/testing under the unscoped name (needs @nestjs/testing, a dev dependency of yours).
2
+ export * from '@nest-my-admin/testing';