@nest-my-admin/core 0.7.4 → 0.8.0
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 +37 -0
- package/dist/api/admin-api.service.js +11 -6
- package/dist/api/write-runner.d.ts +1 -1
- package/dist/api/write-runner.js +13 -0
- package/dist/audit/audit-participant.js +1 -0
- package/dist/audit/audit-reader.js +1 -1
- package/dist/contract.d.ts +6 -0
- package/dist/decorators/admin-resource.d.ts +14 -0
- package/dist/decorators/admin-resource.js +14 -0
- package/dist/files/file-owner.js +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/inlines/inline-reader.js +1 -1
- package/dist/inlines/inline-writer.js +1 -1
- package/dist/policy/admin-policy.service.js +12 -5
- package/dist/policy/explain.js +2 -1
- package/dist/registry/resource-registry.d.ts +7 -3
- package/dist/registry/resource-registry.js +77 -14
- package/dist/resource/admin-source-base.d.ts +35 -0
- package/dist/resource/admin-source-base.js +115 -0
- package/dist/schema/source-metadata.d.ts +15 -0
- package/dist/schema/source-metadata.js +76 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -615,6 +615,39 @@ export class ShopSettingsPage implements AdminSettingsSource<ShopSettingsDto> {
|
|
|
615
615
|
- **Names.** Letters, digits, `-` and `_`; not the name of a resource, an operation (`view`, `update`, …) or a resource's custom permission. Because page codes start with `page.`, **a resource cannot be named `page` in an admin with settings pages**: boot fails and suggests `@AdminResource(Page, { name: 'content-page' })`.
|
|
616
616
|
- **API.** `GET /api/pages/:name` answers `{ schema, values, secrets, files }`, and `PATCH /api/pages/:name` takes the changed keys and answers the same.
|
|
617
617
|
|
|
618
|
+
### Source resources
|
|
619
|
+
|
|
620
|
+
Rows that are not database rows (DNS records behind an HTTP API, files on disk, live container status) get the same list, record page, forms and actions as a table: `@AdminSource(RowClass, options)` on a class that extends `AdminSourceBase`. The demo's couriers (`examples/demo-api/src/sales/courier.source.ts`) are one.
|
|
621
|
+
|
|
622
|
+
```ts
|
|
623
|
+
export class DnsRow {
|
|
624
|
+
@IsString() id: string;
|
|
625
|
+
@IsString() name: string;
|
|
626
|
+
@IsIn(['a', 'cname', 'txt']) type: string;
|
|
627
|
+
@IsString() value: string;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
@AdminSource(DnsRow, { name: 'dns', label: 'DNS records', title: 'name' }) // primaryKey: 'id' by default
|
|
631
|
+
export class DnsAdmin extends AdminSourceBase<DnsRow, string> {
|
|
632
|
+
list: ListConfig<DnsRow> = { columns: ['name', 'type', 'value'], search: ['name', 'value'], filters: ['type'], sort: 'name' };
|
|
633
|
+
form = { create: CreateDnsDto, update: UpdateDnsDto };
|
|
634
|
+
|
|
635
|
+
constructor(private readonly dns: DnsClient) { super(); }
|
|
636
|
+
|
|
637
|
+
async findMany(params: ListParams) { return inMemoryList(await this.dns.all(), params); }
|
|
638
|
+
async findOne(id: string) { return (await this.dns.all()).find((row) => row.id === id) ?? null; }
|
|
639
|
+
override async create(dto: object) { return this.dns.create(dto as CreateDnsDto); }
|
|
640
|
+
override async update(id: string, dto: object) { return this.dns.update(id, dto as UpdateDnsDto); }
|
|
641
|
+
override async delete(id: string) { await this.dns.delete(id); }
|
|
642
|
+
}
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
- **The row class** is the schema: one field per property with a class-validator decorator, typed like a DTO's (`@IsIn` is an enum, `@IsInt` an integer, `@IsDate` a date). `@AdminField` and `fields` set labels, help and widgets. `primaryKey` names the id property (or several); it defaults to `id`.
|
|
646
|
+
- **`findMany(params, ctx)`** answers a page: `{ items, total }`. `params` carries the search (`term` and the `list.search` fields), the filters, the sort and the page. `inMemoryList(rows, params)` does all of it for rows fetched whole; an API that searches and pages itself can be asked directly. **`findOne(id, ctx)`** answers one row, or `null` (a 404).
|
|
647
|
+
- **Writes are opt-in.** Override `create`, `update` and `delete` to allow them. A source that does not is offered no New, Save or Delete, and the API refuses them with 403 whatever the roles say. Throw `AdminFieldError` to refuse a value (422 on the field), as anywhere.
|
|
648
|
+
- **No DataSource.** `ctx.manager` is never set and writes run without a transaction: a source writes to its own system, which the admin cannot roll back. Actions (record, bulk and resource actions), permissions, global search and the command palette work as on a table. Row scopes do not apply, and writes to a source are not in the audit log. `@BeforeSave`, `@AfterSave` and `@BeforeDelete` run only if your `create`, `update` and `delete` call `this.runHooks(...)`, as for any override.
|
|
649
|
+
- **Refused at boot**, with a sentence: list tabs, computed columns, keyset paging, a `count` other than exact, export, inlines, relation cards, form history, file/image/rich-text widgets and atomic actions. They need a database.
|
|
650
|
+
|
|
618
651
|
### Inlines
|
|
619
652
|
|
|
620
653
|
A parent's form can edit its child records (a product's variants, specifications and pictures; an order's lines), and one Save writes the parent and every change to its children in **one transaction**. The child is an ordinary resource, with its own permissions, scopes, fields, DTOs, hooks and service overrides; the parent's layout places it:
|
|
@@ -936,6 +969,10 @@ Things hosts tend to write by hand that the admin already does:
|
|
|
936
969
|
- **Inline children stay out of the sidebar** by default (`nav: false` unless they set `nav`): no extra group to hide them in.
|
|
937
970
|
- **Labels in one language** are plain strings; other languages can come from `translate` (see Languages, theme and branding).
|
|
938
971
|
|
|
972
|
+
## Upgrading to 0.8.0
|
|
973
|
+
|
|
974
|
+
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.
|
|
975
|
+
|
|
939
976
|
## Upgrading to 0.7.4
|
|
940
977
|
|
|
941
978
|
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).
|
|
@@ -461,8 +461,9 @@ let AdminApiService = class AdminApiService {
|
|
|
461
461
|
fields = fields.filter((field) => visible.has(field.name));
|
|
462
462
|
const perms = await this.policy.recordPermissions(entry, entities, ctx);
|
|
463
463
|
const titled = this.policy.titleVisible(entry, ctx);
|
|
464
|
-
|
|
465
|
-
const
|
|
464
|
+
// A source has no relations or paths to load, and no DataSource to load them with.
|
|
465
|
+
const manager = ctx.manager ?? entry.dataSource?.manager;
|
|
466
|
+
const loaded = fields.length > 0 && manager ? await loadReferences(entry, entities, fields, { registry: this.registry, manager }) : undefined;
|
|
466
467
|
const discriminator = entry.metadata.discriminatorColumn?.propertyName;
|
|
467
468
|
const kindOf = (entity) => entry.metadata.childEntityMetadatas.find((child) => child.target === entity.constructor)?.discriminatorValue ?? entry.metadata.discriminatorValue;
|
|
468
469
|
const locale = ctx.locale ?? this.options.locale;
|
|
@@ -511,7 +512,8 @@ let AdminApiService = class AdminApiService {
|
|
|
511
512
|
const entry = this.registry.get(name);
|
|
512
513
|
const { resource } = entry;
|
|
513
514
|
// A read-only resource answers 403 (it refuses writes), not the 400 of a resource that cannot be created.
|
|
514
|
-
|
|
515
|
+
// A source that does not create says so (403) too.
|
|
516
|
+
if (entry.schema.creatable || entry.schema.readonly || entry.source)
|
|
515
517
|
this.policy.require(entry, 'create', ctx);
|
|
516
518
|
else
|
|
517
519
|
this.policy.requireReach(entry, ctx);
|
|
@@ -681,10 +683,11 @@ let AdminApiService = class AdminApiService {
|
|
|
681
683
|
*/
|
|
682
684
|
async checkVersion(entry, id, expected, ctx, withDeleted = false) {
|
|
683
685
|
const version = entry.schema.version;
|
|
684
|
-
|
|
686
|
+
const { dataSource } = entry;
|
|
687
|
+
if (expected === undefined || !version || !dataSource)
|
|
685
688
|
return;
|
|
686
|
-
const manager = ctx.manager ??
|
|
687
|
-
const lock = inAdminTransaction(ctx) && !SINGLE_CONNECTION_DRIVERS.has(
|
|
689
|
+
const manager = ctx.manager ?? dataSource.manager;
|
|
690
|
+
const lock = inAdminTransaction(ctx) && !SINGLE_CONNECTION_DRIVERS.has(dataSource.options.type) ? { mode: 'pessimistic_write' } : undefined;
|
|
688
691
|
const where = typeof id === 'object' ? id : { [entry.schema.primaryKeys[0]]: id };
|
|
689
692
|
const current = await manager.getRepository(entry.metadata.target).findOne({ where, withDeleted, ...(lock ? { lock } : {}) });
|
|
690
693
|
if (!current)
|
|
@@ -699,6 +702,8 @@ let AdminApiService = class AdminApiService {
|
|
|
699
702
|
*/
|
|
700
703
|
async optionsQuery(entry, field, ctx, values) {
|
|
701
704
|
const target = entry.relations.get(field).inverseEntityMetadata;
|
|
705
|
+
if (!entry.dataSource)
|
|
706
|
+
throw new AdminNotFoundError(`${entry.schema.label} has no relation fields`);
|
|
702
707
|
const manager = ctx.manager ?? entry.dataSource.manager;
|
|
703
708
|
const qb = manager.getRepository(target.target).createQueryBuilder('option');
|
|
704
709
|
// The target resource's query() restricts what may be picked, before this field's relationOptions().
|
|
@@ -20,7 +20,7 @@ export declare class WriteRunner {
|
|
|
20
20
|
* `onRollback` runs only when it fails. A failing one is logged, never thrown.
|
|
21
21
|
*/
|
|
22
22
|
run<T>(target: {
|
|
23
|
-
dataSource
|
|
23
|
+
dataSource?: DataSource;
|
|
24
24
|
}, ctx: AdminContext, work: (ctx: AdminWriteContext) => Promise<T>): Promise<T>;
|
|
25
25
|
/**
|
|
26
26
|
* One change inside the write `tx`: every participant's `before`, then the host `method`, then every `after` with
|
package/dist/api/write-runner.js
CHANGED
|
@@ -41,6 +41,13 @@ export class WriteRunner {
|
|
|
41
41
|
await this.settle(steps.filter((step) => step.done), 'onCommit', tx);
|
|
42
42
|
return result;
|
|
43
43
|
};
|
|
44
|
+
if (!target.dataSource) {
|
|
45
|
+
// An @AdminSource: no DataSource, so no transaction and no manager (`ctx.manager` stays unset in its methods).
|
|
46
|
+
if (this.open.has(ctx))
|
|
47
|
+
return work(ctx);
|
|
48
|
+
const plain = { ...ctx };
|
|
49
|
+
return committed(plain, () => runInAdminContext(plain, () => work(plain)));
|
|
50
|
+
}
|
|
44
51
|
if (!this.options.transactions) {
|
|
45
52
|
// Nothing to commit: the participants settle when the outermost write on this context is done.
|
|
46
53
|
// The write still gets a manager, the DataSource's own; it is not a transaction (`inAdminTransaction` says no).
|
|
@@ -78,6 +85,10 @@ export class WriteRunner {
|
|
|
78
85
|
const steps = this.open.get(tx);
|
|
79
86
|
if (!steps)
|
|
80
87
|
throw new Error('nest-my-admin: a change was made outside a write');
|
|
88
|
+
// A source's rows are not in a table: no file is attached to them and the audit log does not record them.
|
|
89
|
+
// (A settings page has a `source` too: its load/save provider. Only a resource's `source: true` marks an @AdminSource.)
|
|
90
|
+
if ('schema' in change.target && change.target.source === true)
|
|
91
|
+
return method();
|
|
81
92
|
const mine = [];
|
|
82
93
|
for (const participant of this.participants) {
|
|
83
94
|
const state = await participant.before(change, tx);
|
|
@@ -122,6 +133,8 @@ async function storedRow(change, saved, tx) {
|
|
|
122
133
|
const key = change.id ?? (change.existing ? keyOf(target, change.existing) : saved ? keyOf(target, saved) : undefined);
|
|
123
134
|
if (key === undefined)
|
|
124
135
|
return { gone: false };
|
|
136
|
+
if (!target.dataSource)
|
|
137
|
+
return { gone: false };
|
|
125
138
|
const stored = await loadStored(target, key, tx.manager ?? target.dataSource.manager);
|
|
126
139
|
return { key, ...(stored ? { stored } : {}), gone: !stored };
|
|
127
140
|
}
|
|
@@ -40,6 +40,7 @@ export function auditParticipant(audit) {
|
|
|
40
40
|
const { target } = change;
|
|
41
41
|
if (!('schema' in target))
|
|
42
42
|
return { before: pageValues(target, change.existing) };
|
|
43
|
+
// Sources never get here (WriteRunner.change skips the participants for them): a resource has its DataSource.
|
|
43
44
|
const manager = tx.manager ?? target.dataSource.manager;
|
|
44
45
|
// The stored row, read here: like "after", so the two compare column for column whatever the resource's
|
|
45
46
|
// `findOne` selected, and the entity the host method is handed (and may change) is never the one serialized.
|
|
@@ -329,7 +329,7 @@ let AuditReader = class AuditReader {
|
|
|
329
329
|
if (ids.size === 0)
|
|
330
330
|
return new Set();
|
|
331
331
|
let seen = new Set(ids.keys());
|
|
332
|
-
if (narrowed) {
|
|
332
|
+
if (narrowed && entry.dataSource) {
|
|
333
333
|
const qb = entry.dataSource.getRepository(entry.metadata.target).createQueryBuilder('entity').withDeleted();
|
|
334
334
|
// The ids go on last: a `query()` that starts its own `where()` must not leave the select unbounded.
|
|
335
335
|
const restricted = this.policy.applyScopes(entry.resource.query(qb, ctx), entry, 'view', ctx).andWhereInIds([...ids.values()]);
|
package/dist/contract.d.ts
CHANGED
|
@@ -504,6 +504,12 @@ export interface ResourceSchema {
|
|
|
504
504
|
* `POST …/:id/restore` brings one back and `DELETE …/:id?purge=true` removes it for good.
|
|
505
505
|
*/
|
|
506
506
|
softDelete: boolean;
|
|
507
|
+
/** Set for an `@AdminSource` (rows that are not database rows): which writes its class implements. */
|
|
508
|
+
source?: {
|
|
509
|
+
create: boolean;
|
|
510
|
+
update: boolean;
|
|
511
|
+
delete: boolean;
|
|
512
|
+
};
|
|
507
513
|
form: {
|
|
508
514
|
create: string[];
|
|
509
515
|
update: string[];
|
|
@@ -41,7 +41,21 @@ export interface AdminResourceOptions {
|
|
|
41
41
|
}
|
|
42
42
|
export interface AdminResourceDefinition extends AdminResourceOptions {
|
|
43
43
|
entity: Function;
|
|
44
|
+
/** Set by `@AdminSource`: the rows come from the class's own `findMany`/`findOne`, not from a table. */
|
|
45
|
+
source?: {
|
|
46
|
+
primaryKeys: string[];
|
|
47
|
+
};
|
|
44
48
|
}
|
|
49
|
+
export interface AdminSourceOptions extends Omit<AdminResourceOptions, 'dataSource'> {
|
|
50
|
+
/** The row property (or properties) that identify a row. Default `id`. */
|
|
51
|
+
primaryKey?: string | string[];
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Marks a provider as an admin resource whose rows are not database rows (an HTTP API, files, live state): the class
|
|
55
|
+
* extends AdminSourceBase and answers `findMany`/`findOne` (and `create`/`update`/`delete` when it allows them).
|
|
56
|
+
* `row` is a class whose class-validator decorators describe a row's fields, like an action's input DTO.
|
|
57
|
+
*/
|
|
58
|
+
export declare function AdminSource(row: Function, options?: AdminSourceOptions): ClassDecorator;
|
|
45
59
|
/** Marks a provider as an admin resource for `entity`. The class must extend AdminResourceBase. */
|
|
46
60
|
export declare function AdminResource(entity: Function, options?: AdminResourceOptions): ClassDecorator;
|
|
47
61
|
export declare function getAdminResourceDefinition(target: Function): AdminResourceDefinition | undefined;
|
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
import { Injectable } from '@nestjs/common';
|
|
3
3
|
import { ADMIN_RESOURCE_METADATA } from '../constants.js';
|
|
4
|
+
/**
|
|
5
|
+
* Marks a provider as an admin resource whose rows are not database rows (an HTTP API, files, live state): the class
|
|
6
|
+
* extends AdminSourceBase and answers `findMany`/`findOne` (and `create`/`update`/`delete` when it allows them).
|
|
7
|
+
* `row` is a class whose class-validator decorators describe a row's fields, like an action's input DTO.
|
|
8
|
+
*/
|
|
9
|
+
export function AdminSource(row, options = {}) {
|
|
10
|
+
return (target) => {
|
|
11
|
+
const { primaryKey, ...rest } = options;
|
|
12
|
+
const primaryKeys = primaryKey === undefined ? ['id'] : Array.isArray(primaryKey) ? [...primaryKey] : [primaryKey];
|
|
13
|
+
const definition = { ...rest, entity: row, source: { primaryKeys } };
|
|
14
|
+
Reflect.defineMetadata(ADMIN_RESOURCE_METADATA, definition, target);
|
|
15
|
+
Injectable()(target);
|
|
16
|
+
};
|
|
17
|
+
}
|
|
4
18
|
/** Marks a provider as an admin resource for `entity`. The class must extend AdminResourceBase. */
|
|
5
19
|
export function AdminResource(entity, options = {}) {
|
|
6
20
|
return (target) => {
|
package/dist/files/file-owner.js
CHANGED
|
@@ -10,6 +10,7 @@ export function resourceFileOwner(entry, policy) {
|
|
|
10
10
|
return {
|
|
11
11
|
name,
|
|
12
12
|
keyPrefix: name,
|
|
13
|
+
// File fields are refused on sources at boot: an owner of files always has a DataSource.
|
|
13
14
|
dataSource: entry.dataSource,
|
|
14
15
|
fieldConfig: entry.fieldConfig,
|
|
15
16
|
hasField: (field) => !field.includes('.') && entry.schema.fields.some((candidate) => candidate.name === field),
|
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,8 @@ export type { AdminTranslate } from './i18n/texts.js';
|
|
|
5
5
|
export { ResourceRegistry, type RegisteredGroup, type RegisteredResource } from './registry/resource-registry.js';
|
|
6
6
|
export type { DbNames } from './registry/db-names.js';
|
|
7
7
|
export { AdminGroup, type AdminGroupOptions } from './decorators/admin-group.js';
|
|
8
|
-
export { AdminResource, type AdminResourceOptions } from './decorators/admin-resource.js';
|
|
8
|
+
export { AdminResource, AdminSource, type AdminResourceOptions, type AdminSourceOptions } from './decorators/admin-resource.js';
|
|
9
|
+
export { AdminSourceBase, inMemoryList } from './resource/admin-source-base.js';
|
|
9
10
|
export { AdminResourceBase, type FilterCondition, type FilterValue, type FindManyResult, type CountMode, type FormConfig, type ComputedColumn, type ComputedSource, type ListConfig, type ListTab, type ListParams, type RecordId, type RecordLinkConfig, } from './resource/admin-resource-base.js';
|
|
10
11
|
export { AdminField, BADGE_COLORS, WIDGETS, type AdminFieldOptions, type FileFieldOptions, type BadgeColor, type WidgetName } from './decorators/admin-field.js';
|
|
11
12
|
export type { FieldConfig, FieldsConfig, LayoutConfig, LayoutInlineConfig, LayoutSectionConfig, LayoutTabConfig } from './schema/field-config.js';
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export { AdminModule } from './admin.module.js';
|
|
2
2
|
export { ResourceRegistry } from './registry/resource-registry.js';
|
|
3
3
|
export { AdminGroup } from './decorators/admin-group.js';
|
|
4
|
-
export { AdminResource } from './decorators/admin-resource.js';
|
|
4
|
+
export { AdminResource, AdminSource } from './decorators/admin-resource.js';
|
|
5
|
+
export { AdminSourceBase, inMemoryList } from './resource/admin-source-base.js';
|
|
5
6
|
export { AdminResourceBase, } from './resource/admin-resource-base.js';
|
|
6
7
|
export { AdminField, BADGE_COLORS, WIDGETS } from './decorators/admin-field.js';
|
|
7
8
|
export { AdminContext } from './resource/admin-context.js';
|
|
@@ -83,7 +83,7 @@ export class InlineReader {
|
|
|
83
83
|
/** This parent's children as the user may view them: the child's `query()`, the user's view scopes, the link. */
|
|
84
84
|
children(inline, value, ctx) {
|
|
85
85
|
const { child } = inline;
|
|
86
|
-
const manager = ctx.manager ?? child.dataSource.manager;
|
|
86
|
+
const manager = ctx.manager ?? child.dataSource.manager; // a source has no relation, so it is never an inline child
|
|
87
87
|
const qb = manager.getRepository(child.metadata.target).createQueryBuilder('nma_inline');
|
|
88
88
|
return this.deps.policy.applyScopes(child.resource.query(qb, ctx), child, 'view', ctx).andWhere(`nma_inline.${inline.link} = :nmaInlineParent`, { nmaInlineParent: value });
|
|
89
89
|
}
|
|
@@ -152,7 +152,7 @@ export class InlineWriter {
|
|
|
152
152
|
}
|
|
153
153
|
// Children of THIS parent that the user sees: the child's query() and the user's view scopes, as its findOne.
|
|
154
154
|
const children = () => {
|
|
155
|
-
const manager = tx.manager ?? child.dataSource.manager;
|
|
155
|
+
const manager = tx.manager ?? child.dataSource.manager; // a source has no relation, so it is never an inline child
|
|
156
156
|
const qb = manager.getRepository(child.metadata.target).createQueryBuilder('nma_child');
|
|
157
157
|
const restricted = policy.applyScopes(child.resource.query(qb, tx), child, 'view', tx);
|
|
158
158
|
return restricted.andWhere(`nma_child.${inline.link} = :nmaInlineParent`, { nmaInlineParent: linkValue });
|
|
@@ -145,6 +145,12 @@ let AdminPolicy = class AdminPolicy {
|
|
|
145
145
|
this.requireReach(entry, ctx);
|
|
146
146
|
if (operation !== 'view' && entry.schema.readonly)
|
|
147
147
|
throw new AdminForbiddenError(`${entry.schema.label} records are read-only`);
|
|
148
|
+
const source = entry.schema.source;
|
|
149
|
+
if (source && (operation === 'create' || operation === 'update' || operation === 'delete') && !source[operation]) {
|
|
150
|
+
throw new AdminForbiddenError(`${entry.schema.label}: this source does not ${operation} records`);
|
|
151
|
+
}
|
|
152
|
+
if (source && operation === 'purge')
|
|
153
|
+
throw new AdminForbiddenError(`${entry.schema.label}: a source has no trash`);
|
|
148
154
|
if (!this.permissionsOf(ctx).canOn(entry.schema.name, operation)) {
|
|
149
155
|
throw new AdminForbiddenError(`You may not ${operation === 'view' ? 'view' : operation} ${entry.schema.label} records`);
|
|
150
156
|
}
|
|
@@ -261,10 +267,10 @@ let AdminPolicy = class AdminPolicy {
|
|
|
261
267
|
const editable = (name) => (levels.get(name) ?? 'hidden') === 'edit';
|
|
262
268
|
const r = schema.name;
|
|
263
269
|
const permissions = {
|
|
264
|
-
create: schema.creatable && perms.canOn(r, 'create'),
|
|
265
|
-
update: !schema.readonly && perms.canOn(r, 'update'),
|
|
266
|
-
delete: !schema.readonly && perms.canOn(r, 'delete'),
|
|
267
|
-
purge: !schema.readonly && perms.canOn(r, 'purge'),
|
|
270
|
+
create: schema.creatable && (schema.source?.create ?? true) && perms.canOn(r, 'create'),
|
|
271
|
+
update: !schema.readonly && (schema.source?.update ?? true) && perms.canOn(r, 'update'),
|
|
272
|
+
delete: !schema.readonly && (schema.source?.delete ?? true) && perms.canOn(r, 'delete'),
|
|
273
|
+
purge: !schema.readonly && !schema.source && perms.canOn(r, 'purge'),
|
|
268
274
|
};
|
|
269
275
|
const create = permissions.create ? schema.form.create.filter(editable) : [];
|
|
270
276
|
const update = permissions.update ? schema.form.update.filter(editable) : [];
|
|
@@ -429,7 +435,8 @@ let AdminPolicy = class AdminPolicy {
|
|
|
429
435
|
}
|
|
430
436
|
/** Whether a query for `operation` needs restricting at all. */
|
|
431
437
|
scoped(entry, operation, ctx) {
|
|
432
|
-
|
|
438
|
+
// Row scopes are query filters: a source has no query, so they do not apply to it (documented).
|
|
439
|
+
if (!ctx?.permissions || entry.source)
|
|
433
440
|
return false;
|
|
434
441
|
return ctx.permissions.scopes(entry.schema.name, operation) !== 'all' || this.globalScopes(entry, ctx.permissions).length > 0;
|
|
435
442
|
}
|
package/dist/policy/explain.js
CHANGED
|
@@ -104,7 +104,8 @@ async function explainRecord(policy, entry, raw, ctx) {
|
|
|
104
104
|
return { id: raw, exists: false, view: false, update: false, delete: false, reasons: { view: 'missing', update: 'missing', delete: 'missing' } };
|
|
105
105
|
}
|
|
106
106
|
const keys = entry.schema.primaryKeys;
|
|
107
|
-
|
|
107
|
+
// A source's row exists when its own findOne finds it.
|
|
108
|
+
const stored = entry.dataSource ? await entry.dataSource.manager.getRepository(entry.metadata.target).createQueryBuilder('nma_explain').whereInIds([id]).getOne() : await entry.resource.findOne(id, ctx);
|
|
108
109
|
const exists = stored !== null;
|
|
109
110
|
const key = recordIdOf(typeof id === 'object' ? id : { [keys[0]]: id }, keys);
|
|
110
111
|
const inScope = async (operation) => (await policy.allowedIds(entry, [id], operation, ctx)).has(key);
|
|
@@ -17,8 +17,12 @@ export interface RegisteredResource {
|
|
|
17
17
|
schema: ResourceSchema;
|
|
18
18
|
resource: AdminResourceBase<any>;
|
|
19
19
|
className: string;
|
|
20
|
+
/** The entity class; the row class of a source. */
|
|
20
21
|
entity: Function;
|
|
21
|
-
|
|
22
|
+
/** The entity's DataSource; absent for a source (`source: true`). */
|
|
23
|
+
dataSource?: DataSource;
|
|
24
|
+
/** An `@AdminSource`: rows from the class's own findMany/findOne, no table, no transaction. `metadata` is a stand-in built from the row class. */
|
|
25
|
+
source?: true;
|
|
22
26
|
/** Database column and constraint names → entity properties (for mapping constraint errors to fields). */
|
|
23
27
|
dbNames: DbNames;
|
|
24
28
|
metadata: EntityMetadata;
|
|
@@ -97,9 +101,9 @@ export declare class ResourceRegistry implements OnModuleInit {
|
|
|
97
101
|
find(name: string): RegisteredResource | undefined;
|
|
98
102
|
list(): RegisteredResource[];
|
|
99
103
|
/** The resource registered for an entity class on a DataSource (the first one, when several share it). */
|
|
100
|
-
forEntity(entity: Function | string, dataSource: DataSource): RegisteredResource | undefined;
|
|
104
|
+
forEntity(entity: Function | string, dataSource: DataSource | undefined): RegisteredResource | undefined;
|
|
101
105
|
/** How records of an entity are titled: its resource's `title`, or the default for its columns. */
|
|
102
|
-
titleFor(metadata: EntityMetadata, dataSource: DataSource): TitleFn;
|
|
106
|
+
titleFor(metadata: EntityMetadata, dataSource: DataSource | undefined): TitleFn;
|
|
103
107
|
groupList(): RegisteredGroup[];
|
|
104
108
|
/**
|
|
105
109
|
* The group each `@AdminGroup` module configures, by key: the label, icon and order of that key's group, whoever its
|
|
@@ -20,6 +20,8 @@ import { getAdminGroupOptions } from '../decorators/admin-group.js';
|
|
|
20
20
|
import { getAdminResourceDefinition } from '../decorators/admin-resource.js';
|
|
21
21
|
import { AdminNotFoundError } from '../errors.js';
|
|
22
22
|
import { AdminResourceBase } from '../resource/admin-resource-base.js';
|
|
23
|
+
import { AdminSourceBase } from '../resource/admin-source-base.js';
|
|
24
|
+
import { sourceMetadata } from '../schema/source-metadata.js';
|
|
23
25
|
import { buildResourceSchema } from '../schema/build-resource-schema.js';
|
|
24
26
|
import { getAdminFieldOptions } from '../decorators/admin-field.js';
|
|
25
27
|
import { nestedProtected, protectedInside, protectedOption } from '../schema/dto-form.js';
|
|
@@ -87,6 +89,9 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
87
89
|
if (seen.has(instance))
|
|
88
90
|
continue;
|
|
89
91
|
seen.add(instance);
|
|
92
|
+
if (definition.source && !(instance instanceof AdminSourceBase)) {
|
|
93
|
+
throw new Error(`${metatype.name} is decorated with @AdminSource but does not extend AdminSourceBase`);
|
|
94
|
+
}
|
|
90
95
|
if (!(instance instanceof AdminResourceBase)) {
|
|
91
96
|
throw new Error(`${metatype.name} is decorated with @AdminResource but does not extend AdminResourceBase`);
|
|
92
97
|
}
|
|
@@ -168,8 +173,8 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
168
173
|
const child = this.list().find((entry) => entry.entity === entity);
|
|
169
174
|
if (child)
|
|
170
175
|
return child.resource.readQuery(alias, ctx);
|
|
171
|
-
const owner = this.list().find((entry) => entry.dataSource
|
|
172
|
-
const manager = ctx?.manager ?? owner?.dataSource
|
|
176
|
+
const owner = this.list().find((entry) => entry.dataSource?.hasMetadata(entity));
|
|
177
|
+
const manager = ctx?.manager ?? owner?.dataSource?.manager;
|
|
173
178
|
if (!manager)
|
|
174
179
|
throw new Error(`nest-my-admin: no DataSource holds ${entity.name}`);
|
|
175
180
|
return manager.getRepository(entity).createQueryBuilder(alias);
|
|
@@ -266,23 +271,45 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
266
271
|
return key;
|
|
267
272
|
}
|
|
268
273
|
register(className, definition, resource, moduleGroup) {
|
|
269
|
-
const
|
|
274
|
+
const failed = (message) => {
|
|
275
|
+
throw new Error(`${className}: ${message}`);
|
|
276
|
+
};
|
|
270
277
|
let dataSource;
|
|
271
|
-
|
|
272
|
-
|
|
278
|
+
let metadata;
|
|
279
|
+
if (definition.source) {
|
|
280
|
+
// A source has no table: its columns come from the row class, and nothing is attached.
|
|
281
|
+
metadata = sourceMetadata(definition.entity, definition.source.primaryKeys, failed);
|
|
282
|
+
checkSourceConfig(resource, failed);
|
|
273
283
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
284
|
+
else {
|
|
285
|
+
const dataSourceName = definition.dataSource ?? 'default';
|
|
286
|
+
try {
|
|
287
|
+
dataSource = this.moduleRef.get(getDataSourceToken(dataSourceName), { strict: false });
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
throw new Error(`${className}: TypeORM DataSource "${dataSourceName}" not found; is TypeOrmModule.forRoot() imported?`);
|
|
291
|
+
}
|
|
292
|
+
if (!dataSource.hasMetadata(definition.entity)) {
|
|
293
|
+
throw new Error(`${className}: entity ${definition.entity.name} is not registered in DataSource "${dataSourceName}"`);
|
|
294
|
+
}
|
|
295
|
+
metadata = dataSource.getMetadata(definition.entity);
|
|
296
|
+
resource.attachRepository(dataSource.getRepository(definition.entity));
|
|
279
297
|
}
|
|
280
|
-
const metadata = dataSource.getMetadata(definition.entity);
|
|
281
|
-
resource.attachRepository(dataSource.getRepository(definition.entity));
|
|
282
298
|
const order = memberOrder(definition.order, (message) => {
|
|
283
299
|
throw new Error(`${className}: ${message}`);
|
|
284
300
|
});
|
|
285
301
|
const schema = buildResourceSchema({ definition, resource, metadata, moduleGroup, className });
|
|
302
|
+
if (definition.source) {
|
|
303
|
+
// Only the writes the class implements are offered.
|
|
304
|
+
const writes = AdminSourceBase.writesOf(resource);
|
|
305
|
+
if (!writes.create)
|
|
306
|
+
schema.creatable = false;
|
|
307
|
+
if (!writes.create)
|
|
308
|
+
schema.form.create = [];
|
|
309
|
+
if (!writes.update)
|
|
310
|
+
schema.form.update = [];
|
|
311
|
+
schema.source = writes;
|
|
312
|
+
}
|
|
286
313
|
resource.attachUpdateFields(() => schema.form.update);
|
|
287
314
|
checkTabs(schema, resource.list?.tabs, (message) => {
|
|
288
315
|
throw new Error(`${className}: ${message}`);
|
|
@@ -309,6 +336,8 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
309
336
|
}
|
|
310
337
|
// All-or-nothing is a promise only a transaction can keep.
|
|
311
338
|
const atomic = [...actions.values()].find((action) => action.atomic);
|
|
339
|
+
if (atomic && definition.source)
|
|
340
|
+
failed(`@AdminAction "${atomic.name}" is \`atomic\`, which needs a transaction; a source has no DataSource`);
|
|
312
341
|
if (atomic && !this.options.transactions) {
|
|
313
342
|
throw new Error(`${className}: @AdminAction "${atomic.name}" is \`atomic\`, which needs the admin's transactions; they are off (\`transactions: false\`)`);
|
|
314
343
|
}
|
|
@@ -351,8 +380,9 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
351
380
|
resource,
|
|
352
381
|
className,
|
|
353
382
|
entity: definition.entity,
|
|
354
|
-
dataSource,
|
|
355
|
-
dbNames: dbNamesFor(metadata),
|
|
383
|
+
...(dataSource ? { dataSource } : {}),
|
|
384
|
+
dbNames: definition.source ? { columns: new Map(), constraints: new Map() } : dbNamesFor(metadata),
|
|
385
|
+
...(definition.source ? { source: true } : {}),
|
|
356
386
|
metadata,
|
|
357
387
|
relations,
|
|
358
388
|
title,
|
|
@@ -370,6 +400,13 @@ let ResourceRegistry = class ResourceRegistry {
|
|
|
370
400
|
...(definition.nav !== undefined ? { navOption: definition.nav } : {}),
|
|
371
401
|
inlines: [],
|
|
372
402
|
});
|
|
403
|
+
// Files belong to a stored record (they are attached, released and swept with it): a source has none.
|
|
404
|
+
if (definition.source) {
|
|
405
|
+
for (const [field, options] of this.resources.get(schema.name).fieldConfig) {
|
|
406
|
+
if (options.widget === 'file' || options.widget === 'image' || options.widget === 'richtext')
|
|
407
|
+
failed(`fields.${field}: the "${options.widget}" widget is not available on an @AdminSource (it needs a database table)`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
373
410
|
}
|
|
374
411
|
/** Points each relation field at the resource of its target entity, now that every resource is registered. */
|
|
375
412
|
/**
|
|
@@ -500,4 +537,30 @@ function checkExport(option, schema, fail) {
|
|
|
500
537
|
fail(`max must be an integer from 1 to ${EXPORT_LIMIT}`);
|
|
501
538
|
return { columns: columns, max: max };
|
|
502
539
|
}
|
|
540
|
+
/** What a source cannot have: everything that is a query on a table or needs a transaction. */
|
|
541
|
+
function checkSourceConfig(resource, fail) {
|
|
542
|
+
const list = resource.list;
|
|
543
|
+
const not = (what) => fail(`${what}: not available on an @AdminSource (it needs a database table)`);
|
|
544
|
+
if (list?.tabs?.length)
|
|
545
|
+
not('list.tabs');
|
|
546
|
+
if (list?.computed && Object.keys(list.computed).length > 0)
|
|
547
|
+
not('list.computed');
|
|
548
|
+
if (list?.pagination === 'keyset')
|
|
549
|
+
not("list.pagination 'keyset'");
|
|
550
|
+
if (list?.count !== undefined && list.count !== 'exact')
|
|
551
|
+
not(`list.count '${list.count}'`);
|
|
552
|
+
if (list?.export)
|
|
553
|
+
not('list.export');
|
|
554
|
+
const layout = resource.form?.layout;
|
|
555
|
+
const main = layout && !Array.isArray(layout) && 'main' in layout ? layout.main : layout;
|
|
556
|
+
const hasInline = (node) => Array.isArray(node) ? node.some(hasInline) : typeof node === 'object' && node !== null && ('inline' in node || Object.values(node).some(hasInline));
|
|
557
|
+
if (hasInline(main ?? []))
|
|
558
|
+
not('form.layout inlines');
|
|
559
|
+
if (layout && !Array.isArray(layout) && 'aside' in layout && layout.aside.some((card) => 'relation' in card && card.relation !== undefined))
|
|
560
|
+
not('form.layout relation aside cards');
|
|
561
|
+
for (const [field, options] of Object.entries((resource.fields ?? {}))) {
|
|
562
|
+
if (options?.history !== undefined)
|
|
563
|
+
not(`fields.${field}.history`);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
503
566
|
//# sourceMappingURL=resource-registry.js.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ObjectLiteral } from 'typeorm';
|
|
2
|
+
import type { AdminContext } from './admin-context.js';
|
|
3
|
+
import { AdminResourceBase, type FindManyResult, type ListParams, type RecordId } from './admin-resource-base.js';
|
|
4
|
+
/**
|
|
5
|
+
* The base of an `@AdminSource` resource: rows that are not database rows (an HTTP API, files, live state). Answer
|
|
6
|
+
* `findMany` (the list: `inMemoryList` does search, filters, sort and paging for rows fetched whole) and `findOne` (one
|
|
7
|
+
* row by id, `null` when there is none). Override `create`, `update` and `delete` to allow them: a source that does not
|
|
8
|
+
* is not offered New, Save or Delete, and the API refuses them (403).
|
|
9
|
+
*
|
|
10
|
+
* There is no DataSource: `ctx.manager` is never set, writes are not wrapped in a transaction, and the TypeORM helpers
|
|
11
|
+
* of AdminResourceBase (`query`, `buildListQuery`, `repository`, `restore`, `purge`) are not used.
|
|
12
|
+
*/
|
|
13
|
+
export declare abstract class AdminSourceBase<T extends ObjectLiteral = ObjectLiteral, Id extends RecordId = RecordId> extends AdminResourceBase<T, Id> {
|
|
14
|
+
abstract findMany(params: ListParams, ctx: AdminContext): Promise<FindManyResult<T>>;
|
|
15
|
+
abstract findOne(id: Id, ctx: AdminContext, options?: {
|
|
16
|
+
withDeleted?: boolean;
|
|
17
|
+
}): Promise<T | null>;
|
|
18
|
+
create(_dto: object, _ctx: AdminContext): Promise<T>;
|
|
19
|
+
update(_id: Id, _dto: object, _ctx: AdminContext): Promise<T>;
|
|
20
|
+
delete(_id: Id, _ctx: AdminContext): Promise<void>;
|
|
21
|
+
restore(_id: Id, _ctx: AdminContext): Promise<T>;
|
|
22
|
+
purge(_id: Id, _ctx: AdminContext): Promise<void>;
|
|
23
|
+
/** @internal Which writes the class allows: those it overrides. */
|
|
24
|
+
static writesOf(resource: AdminSourceBase<any, any>): {
|
|
25
|
+
create: boolean;
|
|
26
|
+
update: boolean;
|
|
27
|
+
delete: boolean;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A page of `rows` as the list asked for it: `params.search` (case-insensitive, any of its fields), `params.filters`,
|
|
32
|
+
* `params.sort` (stable) and `params.page`/`pageSize`. For sources that fetch every row at once (an API answering a
|
|
33
|
+
* few hundred records, a folder of files): return it from `findMany`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function inMemoryList<T extends ObjectLiteral>(rows: readonly T[], params: ListParams): FindManyResult<T>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { AdminForbiddenError } from '../errors.js';
|
|
2
|
+
import { AdminResourceBase } from './admin-resource-base.js';
|
|
3
|
+
/**
|
|
4
|
+
* The base of an `@AdminSource` resource: rows that are not database rows (an HTTP API, files, live state). Answer
|
|
5
|
+
* `findMany` (the list: `inMemoryList` does search, filters, sort and paging for rows fetched whole) and `findOne` (one
|
|
6
|
+
* row by id, `null` when there is none). Override `create`, `update` and `delete` to allow them: a source that does not
|
|
7
|
+
* is not offered New, Save or Delete, and the API refuses them (403).
|
|
8
|
+
*
|
|
9
|
+
* There is no DataSource: `ctx.manager` is never set, writes are not wrapped in a transaction, and the TypeORM helpers
|
|
10
|
+
* of AdminResourceBase (`query`, `buildListQuery`, `repository`, `restore`, `purge`) are not used.
|
|
11
|
+
*/
|
|
12
|
+
export class AdminSourceBase extends AdminResourceBase {
|
|
13
|
+
async create(_dto, _ctx) {
|
|
14
|
+
throw new AdminForbiddenError(`${this.constructor.name} does not create rows`);
|
|
15
|
+
}
|
|
16
|
+
async update(_id, _dto, _ctx) {
|
|
17
|
+
throw new AdminForbiddenError(`${this.constructor.name} does not change rows`);
|
|
18
|
+
}
|
|
19
|
+
async delete(_id, _ctx) {
|
|
20
|
+
throw new AdminForbiddenError(`${this.constructor.name} does not delete rows`);
|
|
21
|
+
}
|
|
22
|
+
async restore(_id, _ctx) {
|
|
23
|
+
throw new AdminForbiddenError(`${this.constructor.name} has no trash`);
|
|
24
|
+
}
|
|
25
|
+
async purge(_id, _ctx) {
|
|
26
|
+
throw new AdminForbiddenError(`${this.constructor.name} has no trash`);
|
|
27
|
+
}
|
|
28
|
+
/** @internal Which writes the class allows: those it overrides. */
|
|
29
|
+
static writesOf(resource) {
|
|
30
|
+
const proto = AdminSourceBase.prototype;
|
|
31
|
+
return { create: resource.create !== proto.create, update: resource.update !== proto.update, delete: resource.delete !== proto.delete };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const comparable = (value) => (value instanceof Date ? value.getTime() : value);
|
|
35
|
+
function compare(a, b) {
|
|
36
|
+
const x = comparable(a);
|
|
37
|
+
const y = comparable(b);
|
|
38
|
+
if (x === y)
|
|
39
|
+
return 0;
|
|
40
|
+
if (x === null || x === undefined)
|
|
41
|
+
return -1;
|
|
42
|
+
if (y === null || y === undefined)
|
|
43
|
+
return 1;
|
|
44
|
+
if (typeof x === 'number' && typeof y === 'number')
|
|
45
|
+
return x - y;
|
|
46
|
+
if (typeof x === 'boolean' && typeof y === 'boolean')
|
|
47
|
+
return Number(x) - Number(y);
|
|
48
|
+
return String(x).localeCompare(String(y), undefined, { numeric: true, sensitivity: 'base' });
|
|
49
|
+
}
|
|
50
|
+
/** A filter value next to a row value: dates and numbers compare as such, the rest as text. */
|
|
51
|
+
function same(row, value) {
|
|
52
|
+
if (row instanceof Date || value instanceof Date)
|
|
53
|
+
return comparable(row) === comparable(value instanceof Date ? value : new Date(String(value)));
|
|
54
|
+
if (typeof row === 'number')
|
|
55
|
+
return row === Number(value);
|
|
56
|
+
if (typeof row === 'boolean')
|
|
57
|
+
return row === (value === true || value === 'true');
|
|
58
|
+
return String(row ?? '') === String(value);
|
|
59
|
+
}
|
|
60
|
+
function matches(row, condition) {
|
|
61
|
+
const actual = row[condition.field];
|
|
62
|
+
const value = condition.value;
|
|
63
|
+
const list = Array.isArray(value) ? value : [value];
|
|
64
|
+
const text = (v) => String(v ?? '').toLocaleLowerCase();
|
|
65
|
+
switch (condition.operator) {
|
|
66
|
+
case 'eq':
|
|
67
|
+
return same(actual, value);
|
|
68
|
+
case 'ne':
|
|
69
|
+
return !same(actual, value);
|
|
70
|
+
case 'in':
|
|
71
|
+
return list.some((item) => same(actual, item));
|
|
72
|
+
case 'nin':
|
|
73
|
+
return !list.some((item) => same(actual, item));
|
|
74
|
+
case 'lt':
|
|
75
|
+
return actual !== null && actual !== undefined && compare(actual, value) < 0;
|
|
76
|
+
case 'lte':
|
|
77
|
+
return actual !== null && actual !== undefined && compare(actual, value) <= 0;
|
|
78
|
+
case 'gt':
|
|
79
|
+
return actual !== null && actual !== undefined && compare(actual, value) > 0;
|
|
80
|
+
case 'gte':
|
|
81
|
+
return actual !== null && actual !== undefined && compare(actual, value) >= 0;
|
|
82
|
+
case 'between':
|
|
83
|
+
return actual !== null && actual !== undefined && compare(actual, list[0]) >= 0 && compare(actual, list[1]) <= 0;
|
|
84
|
+
case 'contains':
|
|
85
|
+
return text(actual).includes(text(value));
|
|
86
|
+
case 'startsWith':
|
|
87
|
+
return text(actual).startsWith(text(value));
|
|
88
|
+
case 'isNull':
|
|
89
|
+
return (value === true || value === 'true') === (actual === null || actual === undefined);
|
|
90
|
+
default:
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* A page of `rows` as the list asked for it: `params.search` (case-insensitive, any of its fields), `params.filters`,
|
|
96
|
+
* `params.sort` (stable) and `params.page`/`pageSize`. For sources that fetch every row at once (an API answering a
|
|
97
|
+
* few hundred records, a folder of files): return it from `findMany`.
|
|
98
|
+
*/
|
|
99
|
+
export function inMemoryList(rows, params) {
|
|
100
|
+
let found = [...rows];
|
|
101
|
+
if (params.search && params.search.term.trim() !== '') {
|
|
102
|
+
const term = params.search.term.trim().toLocaleLowerCase();
|
|
103
|
+
found = found.filter((row) => params.search.fields.some((field) => String(row[field] ?? '').toLocaleLowerCase().includes(term)));
|
|
104
|
+
}
|
|
105
|
+
for (const condition of params.filters)
|
|
106
|
+
found = found.filter((row) => matches(row, condition));
|
|
107
|
+
const { field, direction } = params.sort;
|
|
108
|
+
if (field) {
|
|
109
|
+
const sign = direction === 'desc' ? -1 : 1;
|
|
110
|
+
found = found.map((row, index) => ({ row, index })).sort((a, b) => sign * compare(a.row[field], b.row[field]) || a.index - b.index).map(({ row }) => row);
|
|
111
|
+
}
|
|
112
|
+
const start = (Math.max(1, params.page) - 1) * params.pageSize;
|
|
113
|
+
return { items: found.slice(start, start + params.pageSize), total: found.length };
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=admin-source-base.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ColumnLike } from './column-field.js';
|
|
2
|
+
import type { EntityMetadataLike } from './build-resource-schema.js';
|
|
3
|
+
/**
|
|
4
|
+
* What a source row looks like to the schema builder: one column per property with a class-validator decorator, the
|
|
5
|
+
* primary keys marked, and nothing TypeORM-only (relations, embeddeds, inheritance, uniques). The schema of a source is
|
|
6
|
+
* then built like an entity's, so `list`, `form` and `fields` config are checked the same way.
|
|
7
|
+
*/
|
|
8
|
+
export declare function sourceMetadata(row: Function, primaryKeys: string[], fail: (message: string) => never): EntityMetadataLike & {
|
|
9
|
+
tablePath: string;
|
|
10
|
+
deleteDateColumn: undefined;
|
|
11
|
+
discriminatorColumn: undefined;
|
|
12
|
+
childEntityMetadatas: [];
|
|
13
|
+
embeddeds: [];
|
|
14
|
+
findColumnWithPropertyName(name: string): ColumnLike | undefined;
|
|
15
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { dtoConstraints } from './dto-constraints.js';
|
|
2
|
+
import { dtoOnlyField, dtoPropertyNames } from './dto-fields.js';
|
|
3
|
+
import { didYouMean } from './suggest.js';
|
|
4
|
+
/** The column type a row property of each field type stands for (what `columnToField` reads back). */
|
|
5
|
+
const COLUMN_TYPES = {
|
|
6
|
+
string: 'varchar',
|
|
7
|
+
text: 'text',
|
|
8
|
+
boolean: 'boolean',
|
|
9
|
+
date: 'date',
|
|
10
|
+
datetime: 'datetime',
|
|
11
|
+
json: 'simple-json',
|
|
12
|
+
uuid: 'uuid',
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* What a source row looks like to the schema builder: one column per property with a class-validator decorator, the
|
|
16
|
+
* primary keys marked, and nothing TypeORM-only (relations, embeddeds, inheritance, uniques). The schema of a source is
|
|
17
|
+
* then built like an entity's, so `list`, `form` and `fields` config are checked the same way.
|
|
18
|
+
*/
|
|
19
|
+
export function sourceMetadata(row, primaryKeys, fail) {
|
|
20
|
+
const dto = row;
|
|
21
|
+
const names = dtoPropertyNames(dto);
|
|
22
|
+
if (names.length === 0)
|
|
23
|
+
fail(`row ${row.name}: no property has a class-validator decorator (@IsString(), @IsInt()...), so the source has no fields`);
|
|
24
|
+
if (primaryKeys.length === 0)
|
|
25
|
+
fail('primaryKey: name at least one row property');
|
|
26
|
+
for (const key of primaryKeys) {
|
|
27
|
+
if (!names.includes(key))
|
|
28
|
+
fail(`primaryKey: "${key}" is not a decorated property of ${row.name}${didYouMean(key, names)}`);
|
|
29
|
+
}
|
|
30
|
+
const constraints = dtoConstraints(dto);
|
|
31
|
+
const columns = names.map((name) => {
|
|
32
|
+
const field = dtoOnlyField(dto, name);
|
|
33
|
+
const designType = Reflect.getMetadata('design:type', dto.prototype, name);
|
|
34
|
+
const type = field.type === 'enum'
|
|
35
|
+
? 'simple-enum'
|
|
36
|
+
: field.type === 'number'
|
|
37
|
+
? constraints[name]?.integer
|
|
38
|
+
? 'int'
|
|
39
|
+
: 'double'
|
|
40
|
+
: designType === Object || designType === Array
|
|
41
|
+
? 'simple-json'
|
|
42
|
+
: (COLUMN_TYPES[field.type] ?? 'varchar');
|
|
43
|
+
const primary = primaryKeys.includes(name);
|
|
44
|
+
return {
|
|
45
|
+
propertyName: name,
|
|
46
|
+
propertyPath: name,
|
|
47
|
+
type,
|
|
48
|
+
isNullable: field.nullable && !primary,
|
|
49
|
+
isPrimary: primary,
|
|
50
|
+
isGenerated: false,
|
|
51
|
+
isCreateDate: false,
|
|
52
|
+
isUpdateDate: false,
|
|
53
|
+
isDeleteDate: false,
|
|
54
|
+
isVersion: false,
|
|
55
|
+
isSelect: true,
|
|
56
|
+
...(field.enumValues ? { enum: [...field.enumValues] } : {}),
|
|
57
|
+
target: row,
|
|
58
|
+
};
|
|
59
|
+
});
|
|
60
|
+
return {
|
|
61
|
+
name: row.name,
|
|
62
|
+
target: row,
|
|
63
|
+
tablePath: `source:${row.name}`,
|
|
64
|
+
columns,
|
|
65
|
+
primaryColumns: columns.filter((column) => column.isPrimary),
|
|
66
|
+
relations: [],
|
|
67
|
+
childEntityMetadatas: [],
|
|
68
|
+
embeddeds: [],
|
|
69
|
+
uniques: [],
|
|
70
|
+
indices: [],
|
|
71
|
+
deleteDateColumn: undefined,
|
|
72
|
+
discriminatorColumn: undefined,
|
|
73
|
+
findColumnWithPropertyName: (name) => columns.find((column) => column.propertyName === name),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=source-metadata.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nest-my-admin/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
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.8.0"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"@nestjs/common": "^11.0.0 || ^12.0.0",
|