openadminjs 0.1.7 → 0.1.9
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 +114 -18
- package/dist/create-project.js +27 -4
- package/dist/create-project.test.js +57 -41
- package/dist/index.js +16 -5
- package/package.json +4 -2
- package/template/.env.example +2 -2
- package/template/README.md +24 -5
- package/template/apps/admin/app/api/auth/login/route.ts +51 -0
- package/template/apps/admin/app/api/auth/logout/route.ts +11 -0
- package/template/apps/admin/app/api/auth/refresh/route.ts +46 -0
- package/template/apps/admin/app/api-tokens/page.tsx +253 -0
- package/template/apps/admin/app/audit-logs/page.tsx +5 -0
- package/template/apps/admin/app/dashboard/page.tsx +392 -0
- package/template/apps/admin/app/files/page.tsx +5 -0
- package/template/apps/admin/app/globals.css +206 -0
- package/template/apps/admin/app/jobs/page.tsx +19 -0
- package/template/apps/admin/app/layout.tsx +57 -0
- package/template/apps/admin/app/login/page.test.tsx +18 -0
- package/template/apps/admin/app/login/page.tsx +161 -0
- package/template/apps/admin/app/login/safe-next-param.ts +4 -0
- package/template/apps/admin/app/notifications/page.tsx +146 -0
- package/template/apps/admin/app/page.tsx +5 -0
- package/template/apps/admin/app/plugins/page.tsx +407 -0
- package/template/apps/admin/app/profile/page.tsx +116 -0
- package/template/apps/admin/app/resources/[resource]/[id]/edit/page.tsx +45 -0
- package/template/apps/admin/app/resources/[resource]/[id]/page.tsx +449 -0
- package/template/apps/admin/app/resources/[resource]/create/page.tsx +34 -0
- package/template/apps/admin/app/resources/[resource]/page.tsx +100 -0
- package/template/apps/admin/app/settings/page.tsx +233 -0
- package/template/apps/admin/components/ai-assistant-widget.tsx +684 -0
- package/template/apps/admin/components/app-shell.tsx +305 -0
- package/template/apps/admin/components/auth-guard.test.tsx +55 -0
- package/template/apps/admin/components/auth-guard.tsx +39 -0
- package/template/apps/admin/components/jobs-panel.tsx +103 -0
- package/template/apps/admin/components/logo.tsx +30 -0
- package/template/apps/admin/components/resource-form.tsx +349 -0
- package/template/apps/admin/components/resource-table.tsx +277 -0
- package/template/apps/admin/lib/ai-events.ts +23 -0
- package/template/apps/admin/lib/api.test.ts +118 -0
- package/template/apps/admin/lib/api.ts +135 -0
- package/template/apps/admin/lib/auth-flow.e2e.test.ts +79 -0
- package/template/apps/admin/lib/brand.ts +14 -0
- package/template/apps/admin/lib/locale.ts +49 -0
- package/template/apps/admin/lib/tokens.ts +93 -0
- package/template/apps/admin/middleware.ts +58 -0
- package/template/apps/admin/next-env.d.ts +6 -0
- package/template/apps/admin/next.config.mjs +7 -0
- package/template/apps/admin/package.json +44 -0
- package/template/apps/admin/postcss.config.mjs +6 -0
- package/template/apps/admin/public/brand/apple-touch-icon.png +0 -0
- package/template/apps/admin/public/brand/favicon.svg +1 -0
- package/template/apps/admin/public/brand/og-image.png +0 -0
- package/template/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
- package/template/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/template/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
- package/template/apps/admin/tailwind.config.ts +37 -0
- package/template/apps/admin/tsconfig.json +23 -0
- package/template/apps/admin/vitest.config.ts +7 -0
- package/template/apps/api/package.json +56 -0
- package/template/apps/api/plugins.manifest.example.json +34 -0
- package/template/apps/api/plugins.manifest.json +4 -0
- package/template/apps/api/src/access/catalog.ts +112 -0
- package/template/apps/api/src/access/derive-permissions.test.ts +26 -0
- package/template/apps/api/src/access/derive-permissions.ts +36 -0
- package/template/apps/api/src/access/public-catalog.ts +28 -0
- package/template/apps/api/src/admin/admin-ai.controller.ts +125 -0
- package/template/apps/api/src/admin/admin-ai.events.ts +23 -0
- package/template/apps/api/src/admin/admin-ai.service.ts +1271 -0
- package/template/apps/api/src/admin/admin-analytics.service.ts +164 -0
- package/template/apps/api/src/admin/admin-plugins.controller.ts +32 -0
- package/template/apps/api/src/admin/admin-plugins.service.ts +267 -0
- package/template/apps/api/src/admin/admin-resource.service.test.ts +118 -0
- package/template/apps/api/src/admin/admin-resource.service.ts +375 -0
- package/template/apps/api/src/admin/admin.controller.ts +72 -0
- package/template/apps/api/src/admin/admin.module.ts +30 -0
- package/template/apps/api/src/admin/dto/plugins.dto.ts +55 -0
- package/template/apps/api/src/admin/validate-resource-payload.test.ts +44 -0
- package/template/apps/api/src/admin/validate-resource-payload.ts +103 -0
- package/template/apps/api/src/app.module.ts +45 -0
- package/template/apps/api/src/auth/auth.controller.ts +70 -0
- package/template/apps/api/src/auth/auth.dto.ts +49 -0
- package/template/apps/api/src/auth/auth.module.ts +30 -0
- package/template/apps/api/src/auth/auth.service.test.ts +75 -0
- package/template/apps/api/src/auth/auth.service.ts +231 -0
- package/template/apps/api/src/common/auth-realm.decorator.ts +6 -0
- package/template/apps/api/src/common/auth.guard.test.ts +61 -0
- package/template/apps/api/src/common/auth.guard.ts +78 -0
- package/template/apps/api/src/common/casl-ability.factory.test.ts +33 -0
- package/template/apps/api/src/common/casl-ability.factory.ts +41 -0
- package/template/apps/api/src/common/current-user.decorator.ts +6 -0
- package/template/apps/api/src/common/permission.decorator.ts +7 -0
- package/template/apps/api/src/common/permissions.guard.ts +31 -0
- package/template/apps/api/src/common/prisma.service.ts +13 -0
- package/template/apps/api/src/health/health.controller.ts +25 -0
- package/template/apps/api/src/mail/mail.module.ts +9 -0
- package/template/apps/api/src/mail/mail.service.ts +115 -0
- package/template/apps/api/src/main.ts +37 -0
- package/template/apps/api/src/plugins/bootstrap.ts +4 -0
- package/template/apps/api/src/plugins/bundled/admin-widget.plugin.ts +25 -0
- package/template/apps/api/src/plugins/bundled/hello.plugin.ts +19 -0
- package/template/apps/api/src/plugins/bundled/image-optimizer.plugin.ts +22 -0
- package/template/apps/api/src/plugins/bundled/registry.ts +13 -0
- package/template/apps/api/src/plugins/bundled/seo.plugin.ts +25 -0
- package/template/apps/api/src/plugins/manifest-path.ts +35 -0
- package/template/apps/api/src/plugins/manifest.schema.test.ts +36 -0
- package/template/apps/api/src/plugins/manifest.schema.ts +58 -0
- package/template/apps/api/src/plugins/plugin-api.interceptor.ts +47 -0
- package/template/apps/api/src/plugins/plugin-loader.ts +134 -0
- package/template/apps/api/src/plugins/plugin-runtime.test.ts +24 -0
- package/template/apps/api/src/plugins/plugin-runtime.ts +85 -0
- package/template/apps/api/src/queue/queue.controller.ts +28 -0
- package/template/apps/api/src/queue/queue.module.ts +23 -0
- package/template/apps/api/src/queue/queue.processor.ts +47 -0
- package/template/apps/api/src/queue/queue.service.ts +50 -0
- package/template/apps/api/src/resources/categories.resource.ts +21 -0
- package/template/apps/api/src/resources/commerce.resource.ts +157 -0
- package/template/apps/api/src/resources/operations.resource.ts +111 -0
- package/template/apps/api/src/resources/posts.resource.ts +88 -0
- package/template/apps/api/src/resources/registry.ts +27 -0
- package/template/apps/api/src/resources/resource-hooks.install.ts +18 -0
- package/template/apps/api/src/resources/resource-hooks.registry.test.ts +72 -0
- package/template/apps/api/src/resources/resource-hooks.registry.ts +66 -0
- package/template/apps/api/src/resources/resource-hooks.runner.ts +93 -0
- package/template/apps/api/src/resources/system.resource.ts +51 -0
- package/template/apps/api/src/resources/users.resource.ts +19 -0
- package/template/apps/api/src/store/payment/payment.controller.ts +98 -0
- package/template/apps/api/src/store/payment/payment.module.ts +14 -0
- package/template/apps/api/src/store/payment/payment.provider.ts +38 -0
- package/template/apps/api/src/store/payment/payment.service.ts +235 -0
- package/template/apps/api/src/store/store.controller.ts +26 -0
- package/template/apps/api/src/store/store.module.ts +12 -0
- package/template/apps/api/src/test-setup.ts +1 -0
- package/template/apps/api/tsconfig.json +11 -0
- package/template/apps/api/vitest.config.ts +21 -0
- package/template/apps/web/lib/openadmin-client.ts +11 -0
- package/template/apps/web/lib/seo.test.ts +41 -0
- package/template/apps/web/lib/seo.ts +24 -13
- package/template/apps/web/next-env.d.ts +4 -0
- package/template/apps/web/package.json +2 -1
- package/template/apps/web/test/next-stub.ts +7 -0
- package/template/apps/web/vitest.config.ts +19 -0
- package/template/package.json +18 -11
- package/template/packages/auth/package.json +17 -0
- package/template/packages/auth/src/index.test.ts +10 -0
- package/template/packages/auth/src/index.ts +17 -0
- package/template/packages/auth/tsconfig.json +8 -0
- package/template/packages/brand/apps/admin/public/brand/apple-touch-icon.png +0 -0
- package/template/packages/brand/apps/admin/public/brand/favicon.svg +1 -0
- package/template/packages/brand/apps/admin/public/brand/og-image.png +0 -0
- package/template/packages/brand/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
- package/template/packages/brand/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/template/packages/brand/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
- package/template/packages/brand/apps/web/public/brand/apple-touch-icon.png +0 -0
- package/template/packages/brand/apps/web/public/brand/favicon.svg +1 -0
- package/template/packages/brand/apps/web/public/brand/og-image.png +0 -0
- package/template/packages/brand/apps/web/public/brand/openadminjs-icon-new.png +0 -0
- package/template/packages/brand/apps/web/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/template/packages/brand/apps/web/public/brand/openadminjs-logo-new.png +0 -0
- package/template/packages/brand/package.json +19 -0
- package/template/packages/brand/site/assets/brand/favicon.svg +1 -0
- package/template/packages/brand/site/assets/brand/og-image.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-icon.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-logo-dark.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-logo-horizontal.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-logo-monochrome.svg +1 -0
- package/template/packages/brand/site/assets/brand/openadminjs-logo.svg +1 -0
- package/template/packages/brand/src/generate-assets.mjs +182 -0
- package/template/packages/brand/src/index.test.ts +9 -0
- package/template/packages/brand/src/index.ts +7 -0
- package/template/packages/brand/tsconfig.json +7 -0
- package/template/packages/core/package.json +20 -0
- package/template/packages/core/src/index.js +1 -0
- package/template/packages/core/src/index.test.ts +27 -0
- package/template/packages/core/src/index.ts +61 -0
- package/template/packages/core/tsconfig.json +8 -0
- package/template/packages/mail/package.json +18 -0
- package/template/packages/mail/src/index.test.ts +23 -0
- package/template/packages/mail/src/index.ts +246 -0
- package/template/packages/mail/tsconfig.json +5 -0
- package/template/packages/notifications/package.json +16 -0
- package/template/packages/notifications/src/index.test.ts +9 -0
- package/template/packages/notifications/src/index.ts +5 -0
- package/template/packages/notifications/tsconfig.json +5 -0
- package/template/packages/payments/package.json +15 -0
- package/template/packages/payments/src/index.ts +256 -0
- package/template/packages/payments/tsconfig.json +9 -0
- package/template/packages/permissions/package.json +17 -0
- package/template/packages/permissions/src/blueprints.js +57 -0
- package/template/packages/permissions/src/blueprints.test.ts +62 -0
- package/template/packages/permissions/src/blueprints.ts +89 -0
- package/template/packages/permissions/src/index.js +11 -0
- package/template/packages/permissions/src/index.test.ts +34 -0
- package/template/packages/permissions/src/index.ts +22 -0
- package/template/packages/permissions/tsconfig.json +8 -0
- package/template/packages/plugin-sdk/package.json +26 -0
- package/template/packages/plugin-sdk/src/hooks.ts +135 -0
- package/template/packages/plugin-sdk/src/index.ts +42 -0
- package/template/packages/plugin-sdk/src/sdk.test.ts +13 -0
- package/template/packages/plugin-sdk/tsconfig.json +8 -0
- package/template/packages/plugin-sdk/vitest.config.ts +5 -0
- package/template/packages/queue/package.json +16 -0
- package/template/packages/queue/src/index.test.ts +12 -0
- package/template/packages/queue/src/index.ts +6 -0
- package/template/packages/queue/tsconfig.json +5 -0
- package/template/packages/resource/package.json +17 -0
- package/template/packages/resource/src/index.js +177 -0
- package/template/packages/resource/src/index.test.ts +151 -0
- package/template/packages/resource/src/index.ts +344 -0
- package/template/packages/resource/tsconfig.json +8 -0
- package/template/packages/storage/package.json +16 -0
- package/template/packages/storage/src/index.test.ts +10 -0
- package/template/packages/storage/src/index.ts +23 -0
- package/template/packages/storage/tsconfig.json +5 -0
- package/template/prisma/migrations/20260505151751_baseline_init_all_tables/migration.sql +371 -0
- package/template/prisma/migrations/migration_lock.toml +3 -0
- package/template/prisma/schema.prisma +291 -0
- package/template/prisma/seed.ts +217 -0
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
|
|
2
|
+
import { Prisma } from "@prisma/client";
|
|
3
|
+
import type { ResourceConfig, ResourceField } from "@openadminjs/core";
|
|
4
|
+
import {
|
|
5
|
+
listScopeWhereClause,
|
|
6
|
+
mergeWhereClauses,
|
|
7
|
+
resolveResourceForLocale,
|
|
8
|
+
shouldApplyListScope
|
|
9
|
+
} from "@openadminjs/core";
|
|
10
|
+
import bcrypt from "bcryptjs";
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
|
+
import { PrismaService } from "../common/prisma.service";
|
|
13
|
+
import { getResource, resources } from "../resources/registry";
|
|
14
|
+
import {
|
|
15
|
+
runAfterCreate,
|
|
16
|
+
runAfterDelete,
|
|
17
|
+
runAfterUpdate,
|
|
18
|
+
runBeforeCreate,
|
|
19
|
+
runBeforeDelete,
|
|
20
|
+
runBeforeUpdate
|
|
21
|
+
} from "../resources/resource-hooks.runner";
|
|
22
|
+
import { parseWritePayload } from "./validate-resource-payload";
|
|
23
|
+
|
|
24
|
+
type UserContext = { id: string; email?: string; permissions: string[] };
|
|
25
|
+
type PrismaDelegate = {
|
|
26
|
+
findMany(args?: unknown): Promise<unknown[]>;
|
|
27
|
+
count(args?: unknown): Promise<number>;
|
|
28
|
+
findUnique(args: unknown): Promise<unknown | null>;
|
|
29
|
+
create(args: unknown): Promise<unknown>;
|
|
30
|
+
update(args: unknown): Promise<unknown>;
|
|
31
|
+
delete(args: unknown): Promise<unknown>;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
@Injectable()
|
|
35
|
+
export class AdminResourceService {
|
|
36
|
+
constructor(private readonly prisma: PrismaService) {}
|
|
37
|
+
|
|
38
|
+
listResources(user: UserContext, locale?: string) {
|
|
39
|
+
return resources
|
|
40
|
+
.filter((resource) => this.has(user, resource.permissions.read))
|
|
41
|
+
.map((resource) => {
|
|
42
|
+
const view = resolveResourceForLocale(resource, locale);
|
|
43
|
+
return {
|
|
44
|
+
name: view.name,
|
|
45
|
+
label: view.label,
|
|
46
|
+
icon: view.icon,
|
|
47
|
+
titleField: view.titleField,
|
|
48
|
+
permissions: view.permissions,
|
|
49
|
+
fields: view.fields,
|
|
50
|
+
actions: view.actions,
|
|
51
|
+
i18n: view.i18n,
|
|
52
|
+
seo: view.seo
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async list(name: string, query: Record<string, unknown>, user: UserContext) {
|
|
58
|
+
const resource = this.authorizedResource(name, user, "read");
|
|
59
|
+
const delegate = this.delegate(resource);
|
|
60
|
+
const page = Number(query.page ?? 1);
|
|
61
|
+
const limit = Math.min(Number(query.limit ?? 20), 100);
|
|
62
|
+
const baseWhere = this.buildWhere(resource, query);
|
|
63
|
+
const scope = shouldApplyListScope(resource, user.permissions) ? listScopeWhereClause(resource, user.id) : undefined;
|
|
64
|
+
const where = mergeWhereClauses(baseWhere, scope);
|
|
65
|
+
const orderBy = this.buildOrderBy(resource, String(query.sort ?? "createdAt:desc"));
|
|
66
|
+
const [data, total] = await Promise.all([
|
|
67
|
+
delegate.findMany({ where, orderBy, skip: (page - 1) * limit, take: limit }),
|
|
68
|
+
delegate.count({ where })
|
|
69
|
+
]);
|
|
70
|
+
return { data: data.map((row) => this.sanitizeRecord(resource, row)), meta: { page, limit, total, pages: Math.ceil(total / limit) || 1 } };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async get(name: string, id: string, user: UserContext) {
|
|
74
|
+
const resource = this.authorizedResource(name, user, "read");
|
|
75
|
+
const record = await this.delegate(resource).findUnique({ where: { id } });
|
|
76
|
+
if (!record) throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
77
|
+
if (this.isOutOfListScope(resource, user, record)) {
|
|
78
|
+
throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
79
|
+
}
|
|
80
|
+
return this.sanitizeRecord(resource, record);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async create(name: string, data: Record<string, unknown>, user: UserContext) {
|
|
84
|
+
const resource = this.authorizedResource(name, user, "create");
|
|
85
|
+
|
|
86
|
+
if (name === "api-tokens") {
|
|
87
|
+
const rawToken = randomBytes(32).toString("base64url");
|
|
88
|
+
const scopes = this.normalizeScopes(data.scopes);
|
|
89
|
+
const record = await this.prisma.$transaction(async (tx) => {
|
|
90
|
+
const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
91
|
+
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
92
|
+
const created = await txDelegate.create({
|
|
93
|
+
data: {
|
|
94
|
+
name: String(data.name ?? "Token"),
|
|
95
|
+
scopes,
|
|
96
|
+
userId: user.id,
|
|
97
|
+
tokenHash: await bcrypt.hash(rawToken, 12)
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
const safeRecord = this.sanitizeRecord(resource, created) as Record<string, unknown>;
|
|
101
|
+
await tx.auditLog.create({
|
|
102
|
+
data: { userId: user.id, resource: name, resourceId: (created as { id?: string }).id, action: "create", before: Prisma.JsonNull, after: safeRecord as object }
|
|
103
|
+
});
|
|
104
|
+
return created;
|
|
105
|
+
});
|
|
106
|
+
const safeRecord = this.sanitizeRecord(resource, record) as Record<string, unknown>;
|
|
107
|
+
return { ...safeRecord, plainToken: rawToken };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const payload = this.safeData(resource, data, "create");
|
|
111
|
+
if (name === "notifications") payload.userId = String(data.userId ?? user.id);
|
|
112
|
+
const hookUser = { id: user.id, email: user.email ?? "", permissions: user.permissions };
|
|
113
|
+
await runBeforeCreate(name, resource, hookUser, this.prisma, payload);
|
|
114
|
+
const validated = parseWritePayload(resource, "create", payload);
|
|
115
|
+
|
|
116
|
+
const record = await this.prisma.$transaction(async (tx) => {
|
|
117
|
+
const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
118
|
+
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
119
|
+
const created = await txDelegate.create({ data: validated });
|
|
120
|
+
await tx.auditLog.create({
|
|
121
|
+
data: { userId: user.id, resource: name, resourceId: (created as { id?: string }).id, action: "create", before: Prisma.JsonNull, after: created as object }
|
|
122
|
+
});
|
|
123
|
+
return created;
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
await runAfterCreate(name, resource, hookUser, this.prisma, payload, record);
|
|
127
|
+
return this.sanitizeRecord(resource, record);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async update(name: string, id: string, data: Record<string, unknown>, user: UserContext) {
|
|
131
|
+
const resource = this.authorizedResource(name, user, "update");
|
|
132
|
+
const delegate = this.delegate(resource);
|
|
133
|
+
const before = await delegate.findUnique({ where: { id } });
|
|
134
|
+
if (!before) throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
135
|
+
if (this.isOutOfListScope(resource, user, before)) {
|
|
136
|
+
throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
137
|
+
}
|
|
138
|
+
const payload = this.safeData(resource, data, "edit");
|
|
139
|
+
const hookUser = { id: user.id, email: user.email ?? "", permissions: user.permissions };
|
|
140
|
+
await runBeforeUpdate(name, resource, hookUser, this.prisma, id, payload);
|
|
141
|
+
const validated = parseWritePayload(resource, "edit", payload);
|
|
142
|
+
|
|
143
|
+
const record = await this.prisma.$transaction(async (tx) => {
|
|
144
|
+
const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
145
|
+
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
146
|
+
const updated = await txDelegate.update({ where: { id }, data: validated });
|
|
147
|
+
await tx.auditLog.create({
|
|
148
|
+
data: { userId: user.id, resource: name, resourceId: id, action: "update", before: before as object, after: updated as object }
|
|
149
|
+
});
|
|
150
|
+
return updated;
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
await runAfterUpdate(name, resource, hookUser, this.prisma, id, payload, before, record);
|
|
154
|
+
return this.sanitizeRecord(resource, record);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async delete(name: string, id: string, user: UserContext) {
|
|
158
|
+
const resource = this.authorizedResource(name, user, "delete");
|
|
159
|
+
const delegate = this.delegate(resource);
|
|
160
|
+
const before = await delegate.findUnique({ where: { id } });
|
|
161
|
+
if (!before) throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
162
|
+
if (this.isOutOfListScope(resource, user, before)) {
|
|
163
|
+
throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
164
|
+
}
|
|
165
|
+
const hookUser = { id: user.id, email: user.email ?? "", permissions: user.permissions };
|
|
166
|
+
await runBeforeDelete(name, resource, hookUser, this.prisma, id);
|
|
167
|
+
|
|
168
|
+
await this.prisma.$transaction(async (tx) => {
|
|
169
|
+
const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
170
|
+
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
171
|
+
await txDelegate.delete({ where: { id } });
|
|
172
|
+
await tx.auditLog.create({
|
|
173
|
+
data: { userId: user.id, resource: name, resourceId: id, action: "delete", before: before as object, after: Prisma.JsonNull }
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
await runAfterDelete(name, resource, hookUser, this.prisma, id);
|
|
178
|
+
return { ok: true };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async action(name: string, id: string, action: string, user: UserContext, input?: unknown) {
|
|
182
|
+
const resource = getResource(name);
|
|
183
|
+
const config = resource?.actions?.[action];
|
|
184
|
+
if (!resource || !config) throw new NotFoundException({ message: "Action not found", code: "ACTION_NOT_FOUND" });
|
|
185
|
+
if (!this.has(user, config.permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
186
|
+
|
|
187
|
+
if (config.handler) {
|
|
188
|
+
const existing = await this.delegate(resource).findUnique({ where: { id } });
|
|
189
|
+
if (!existing) throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
190
|
+
if (this.isOutOfListScope(resource, user, existing)) {
|
|
191
|
+
throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
192
|
+
}
|
|
193
|
+
const result = await config.handler({
|
|
194
|
+
id,
|
|
195
|
+
prisma: this.prisma,
|
|
196
|
+
user: { id: user.id, email: user.email ?? "", permissions: user.permissions },
|
|
197
|
+
input
|
|
198
|
+
});
|
|
199
|
+
await this.audit(user.id, name, id, action, existing, result);
|
|
200
|
+
return this.sanitizeRecord(resource, result);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
throw new NotFoundException({ message: "Action not implemented for this resource", code: "ACTION_NOT_IMPLEMENTED" });
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private isOutOfListScope(resource: ResourceConfig, user: UserContext, record: unknown): boolean {
|
|
207
|
+
if (!shouldApplyListScope(resource, user.permissions)) return false;
|
|
208
|
+
const clause = listScopeWhereClause(resource, user.id);
|
|
209
|
+
if (!clause) return false;
|
|
210
|
+
const row = record as Record<string, unknown>;
|
|
211
|
+
for (const [key, expected] of Object.entries(clause)) {
|
|
212
|
+
if (row[key] !== expected) return true;
|
|
213
|
+
}
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
private authorizedResource(name: string, user: UserContext, action: keyof ResourceConfig["permissions"]) {
|
|
218
|
+
const resource = getResource(name);
|
|
219
|
+
if (!resource) throw new NotFoundException({ message: "Resource not found", code: "RESOURCE_NOT_FOUND" });
|
|
220
|
+
const permission = resource.permissions[action];
|
|
221
|
+
if (!permission || !this.has(user, permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
222
|
+
return resource;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private delegate(resource: ResourceConfig): PrismaDelegate {
|
|
226
|
+
const delegate = (this.prisma as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
227
|
+
if (!delegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
228
|
+
return delegate;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private has(user: UserContext, permission?: string) {
|
|
232
|
+
return Boolean(permission && (user.permissions.includes(permission) || user.permissions.includes("*")));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private safeData(resource: ResourceConfig, data: Record<string, unknown>, mode: "create" | "edit") {
|
|
236
|
+
return Object.fromEntries(
|
|
237
|
+
Object.entries(data).filter(([name]) => {
|
|
238
|
+
const field = resource.fields[name];
|
|
239
|
+
return field && field[mode] !== false && !field.sensitive && field.type !== "id";
|
|
240
|
+
})
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
private sanitizeRecord(resource: ResourceConfig, record: unknown) {
|
|
245
|
+
if (!record || typeof record !== "object") return record;
|
|
246
|
+
const hiddenFields = Object.entries(resource.fields)
|
|
247
|
+
.filter(([, field]) => field.type === "hidden" || field.sensitive)
|
|
248
|
+
.map(([name]) => name);
|
|
249
|
+
const copy = { ...(record as Record<string, unknown>) };
|
|
250
|
+
for (const hidden of hiddenFields) delete copy[hidden];
|
|
251
|
+
return copy;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private normalizeScopes(input: unknown): string[] {
|
|
255
|
+
if (Array.isArray(input)) return input.map((item) => String(item));
|
|
256
|
+
if (typeof input === "string") {
|
|
257
|
+
try {
|
|
258
|
+
const parsed = JSON.parse(input);
|
|
259
|
+
if (Array.isArray(parsed)) return parsed.map((item) => String(item));
|
|
260
|
+
} catch {
|
|
261
|
+
return input
|
|
262
|
+
.split(",")
|
|
263
|
+
.map((item) => item.trim())
|
|
264
|
+
.filter(Boolean);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return ["*"];
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private buildWhere(resource: ResourceConfig, query: Record<string, unknown>) {
|
|
271
|
+
const clauses: Record<string, unknown>[] = [];
|
|
272
|
+
if (query.search) {
|
|
273
|
+
const searchable = Object.entries(resource.fields).filter(([, field]) => field.searchable);
|
|
274
|
+
clauses.push({ OR: searchable.map(([field]) => ({ [field]: { contains: String(query.search), mode: "insensitive" } })) });
|
|
275
|
+
}
|
|
276
|
+
for (const [key, value] of Object.entries(query)) {
|
|
277
|
+
const opMatch = key.match(/^filter\[([^\]]+)]\[(\w+)]$/);
|
|
278
|
+
if (opMatch?.[1] && opMatch[2]) {
|
|
279
|
+
const clause = this.buildOperatorClause(resource, opMatch[1], opMatch[2], value);
|
|
280
|
+
if (clause) clauses.push(clause);
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
const legacy = key.match(/^filter\[([^\]]+)]$/);
|
|
284
|
+
if (legacy?.[1]) {
|
|
285
|
+
const clause = this.buildOperatorClause(resource, legacy[1], "eq", value);
|
|
286
|
+
if (clause) clauses.push(clause);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return clauses.length ? { AND: clauses } : undefined;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private buildOperatorClause(resource: ResourceConfig, fieldName: string, op: string, raw: unknown): Record<string, unknown> | null {
|
|
293
|
+
const field = resource.fields[fieldName];
|
|
294
|
+
if (!field?.filterable) {
|
|
295
|
+
throw new BadRequestException({ message: `Field "${fieldName}" is not filterable`, code: "FILTER_NOT_ALLOWED" });
|
|
296
|
+
}
|
|
297
|
+
const str = raw == null ? "" : String(raw);
|
|
298
|
+
switch (op) {
|
|
299
|
+
case "eq":
|
|
300
|
+
return { [fieldName]: this.coerceFilterScalar(field, str) };
|
|
301
|
+
case "ne":
|
|
302
|
+
return { [fieldName]: { not: this.coerceFilterScalar(field, str) } };
|
|
303
|
+
case "in": {
|
|
304
|
+
const parts = str
|
|
305
|
+
.split(",")
|
|
306
|
+
.map((s) => s.trim())
|
|
307
|
+
.filter(Boolean)
|
|
308
|
+
.map((p) => this.coerceFilterScalar(field, p));
|
|
309
|
+
return { [fieldName]: { in: parts } };
|
|
310
|
+
}
|
|
311
|
+
case "gt":
|
|
312
|
+
return { [fieldName]: { gt: this.coerceFilterComparable(field, str) } };
|
|
313
|
+
case "gte":
|
|
314
|
+
return { [fieldName]: { gte: this.coerceFilterComparable(field, str) } };
|
|
315
|
+
case "lt":
|
|
316
|
+
return { [fieldName]: { lt: this.coerceFilterComparable(field, str) } };
|
|
317
|
+
case "lte":
|
|
318
|
+
return { [fieldName]: { lte: this.coerceFilterComparable(field, str) } };
|
|
319
|
+
case "contains": {
|
|
320
|
+
if (!this.isStringFilterField(field)) {
|
|
321
|
+
throw new BadRequestException({ message: `Operator "contains" is only for string-like fields`, code: "FILTER_OP_INVALID" });
|
|
322
|
+
}
|
|
323
|
+
return { [fieldName]: { contains: str, mode: "insensitive" } };
|
|
324
|
+
}
|
|
325
|
+
default:
|
|
326
|
+
throw new BadRequestException({ message: `Unknown filter operator "${op}"`, code: "FILTER_OP_UNKNOWN" });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private isStringFilterField(field: ResourceField): boolean {
|
|
331
|
+
return ["text", "textarea", "email", "url", "slug", "markdown", "code", "richtext", "badge", "select"].includes(field.type);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private coerceFilterScalar(field: ResourceField, value: string): string | number | boolean {
|
|
335
|
+
if (field.type === "number" || field.type === "money") {
|
|
336
|
+
const n = Number(value);
|
|
337
|
+
if (Number.isNaN(n)) {
|
|
338
|
+
throw new BadRequestException({ message: `Invalid number for filter`, code: "FILTER_VALUE_INVALID" });
|
|
339
|
+
}
|
|
340
|
+
return n;
|
|
341
|
+
}
|
|
342
|
+
if (field.type === "boolean") return value === "true" || value === "1";
|
|
343
|
+
return value;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
private coerceFilterComparable(field: ResourceField, value: string): Date | number | string | boolean {
|
|
347
|
+
if (field.type === "datetime" || field.type === "date") {
|
|
348
|
+
const d = new Date(value);
|
|
349
|
+
if (Number.isNaN(d.getTime())) {
|
|
350
|
+
throw new BadRequestException({ message: `Invalid date for filter`, code: "FILTER_VALUE_INVALID" });
|
|
351
|
+
}
|
|
352
|
+
return d;
|
|
353
|
+
}
|
|
354
|
+
return this.coerceFilterScalar(field, value);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
private buildOrderBy(resource: ResourceConfig, sort: string) {
|
|
358
|
+
const [field, dirRaw] = sort.split(":");
|
|
359
|
+
const direction = dirRaw === "asc" ? "asc" : "desc";
|
|
360
|
+
const candidate = field ? resource.fields[field] : undefined;
|
|
361
|
+
if (field && candidate?.sortable) {
|
|
362
|
+
return { [field]: direction };
|
|
363
|
+
}
|
|
364
|
+
if (resource.fields.createdAt?.sortable) {
|
|
365
|
+
return { createdAt: direction };
|
|
366
|
+
}
|
|
367
|
+
return undefined;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Write an audit log entry outside a transaction (used by the action handler). */
|
|
371
|
+
private audit(userId: string, resource: string, resourceId: string | undefined, action: string, before: unknown, after: unknown) {
|
|
372
|
+
return this.prisma.auditLog.create({ data: { userId, resource, resourceId, action, before: before as object, after: after as object } });
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Body, Controller, Delete, Get, Inject, Optional, Param, Patch, Post, Query, UseGuards } from "@nestjs/common";
|
|
2
|
+
import { AuthGuard } from "../common/auth.guard";
|
|
3
|
+
import { RequireAuthRealm } from "../common/auth-realm.decorator";
|
|
4
|
+
import { CurrentUser } from "../common/current-user.decorator";
|
|
5
|
+
import { AdminResourceService } from "./admin-resource.service";
|
|
6
|
+
import { AdminAnalyticsService } from "./admin-analytics.service";
|
|
7
|
+
import { PaymentService } from "../store/payment/payment.service";
|
|
8
|
+
|
|
9
|
+
type UserContext = { id: string; email?: string; permissions: string[] };
|
|
10
|
+
|
|
11
|
+
@UseGuards(AuthGuard)
|
|
12
|
+
@RequireAuthRealm("admin")
|
|
13
|
+
@Controller("admin/resources")
|
|
14
|
+
export class AdminController {
|
|
15
|
+
constructor(
|
|
16
|
+
private readonly resources: AdminResourceService,
|
|
17
|
+
private readonly analytics: AdminAnalyticsService,
|
|
18
|
+
@Optional() @Inject(PaymentService) private readonly payments?: PaymentService
|
|
19
|
+
) {}
|
|
20
|
+
|
|
21
|
+
@Get("/overview")
|
|
22
|
+
overview(@Query("period") period: "7d" | "30d" | "90d" | undefined, @CurrentUser() user: UserContext) {
|
|
23
|
+
return this.analytics.overview(user, period ?? "30d");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
@Get()
|
|
27
|
+
all(@Query("locale") locale: string | undefined, @CurrentUser() user: UserContext) {
|
|
28
|
+
return this.resources.listResources(user, locale);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
@Get(":resource")
|
|
32
|
+
list(@Param("resource") resource: string, @Query() query: Record<string, unknown>, @CurrentUser() user: UserContext) {
|
|
33
|
+
return this.resources.list(resource, query, user);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
@Get(":resource/:id")
|
|
37
|
+
get(@Param("resource") resource: string, @Param("id") id: string, @CurrentUser() user: UserContext) {
|
|
38
|
+
return this.resources.get(resource, id, user);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
@Post(":resource")
|
|
42
|
+
create(@Param("resource") resource: string, @Body() body: Record<string, unknown>, @CurrentUser() user: UserContext) {
|
|
43
|
+
return this.resources.create(resource, body, user);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
@Patch(":resource/:id")
|
|
47
|
+
update(@Param("resource") resource: string, @Param("id") id: string, @Body() body: Record<string, unknown>, @CurrentUser() user: UserContext) {
|
|
48
|
+
return this.resources.update(resource, id, body, user);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
@Delete(":resource/:id")
|
|
52
|
+
delete(@Param("resource") resource: string, @Param("id") id: string, @CurrentUser() user: UserContext) {
|
|
53
|
+
return this.resources.delete(resource, id, user);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
@Post("orders/:id/refund")
|
|
57
|
+
refundOrder(@Param("id") id: string) {
|
|
58
|
+
if (!this.payments) throw new Error("PaymentService not available");
|
|
59
|
+
return this.payments.refundOrder(id);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
@Post(":resource/:id/actions/:action")
|
|
63
|
+
action(
|
|
64
|
+
@Param("resource") resource: string,
|
|
65
|
+
@Param("id") id: string,
|
|
66
|
+
@Param("action") action: string,
|
|
67
|
+
@Body() body: Record<string, unknown> = {},
|
|
68
|
+
@CurrentUser() user: UserContext
|
|
69
|
+
) {
|
|
70
|
+
return this.resources.action(resource, id, action, user, body);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Module } from "@nestjs/common";
|
|
2
|
+
import { JwtModule } from "@nestjs/jwt";
|
|
3
|
+
import { PrismaService } from "../common/prisma.service";
|
|
4
|
+
import { AuthGuard } from "../common/auth.guard";
|
|
5
|
+
import { PermissionsGuard } from "../common/permissions.guard";
|
|
6
|
+
import { CaslAbilityFactory } from "../common/casl-ability.factory";
|
|
7
|
+
import { AdminController } from "./admin.controller";
|
|
8
|
+
import { AdminAiController } from "./admin-ai.controller";
|
|
9
|
+
import { AdminPluginsController } from "./admin-plugins.controller";
|
|
10
|
+
import { AdminPluginsService } from "./admin-plugins.service";
|
|
11
|
+
import { AdminResourceService } from "./admin-resource.service";
|
|
12
|
+
import { AdminAnalyticsService } from "./admin-analytics.service";
|
|
13
|
+
import { AdminAiService } from "./admin-ai.service";
|
|
14
|
+
import { PaymentModule } from "../store/payment/payment.module";
|
|
15
|
+
|
|
16
|
+
@Module({
|
|
17
|
+
imports: [JwtModule.register({}), PaymentModule],
|
|
18
|
+
controllers: [AdminController, AdminPluginsController, AdminAiController],
|
|
19
|
+
providers: [
|
|
20
|
+
AdminResourceService,
|
|
21
|
+
AdminAnalyticsService,
|
|
22
|
+
AdminAiService,
|
|
23
|
+
AdminPluginsService,
|
|
24
|
+
PrismaService,
|
|
25
|
+
AuthGuard,
|
|
26
|
+
PermissionsGuard,
|
|
27
|
+
CaslAbilityFactory
|
|
28
|
+
]
|
|
29
|
+
})
|
|
30
|
+
export class AdminModule {}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { IsArray, IsBoolean, IsIn, IsObject, IsOptional, IsString } from "class-validator";
|
|
2
|
+
|
|
3
|
+
export class AddPluginDto {
|
|
4
|
+
@IsString()
|
|
5
|
+
id!: string;
|
|
6
|
+
|
|
7
|
+
@IsOptional()
|
|
8
|
+
@IsString()
|
|
9
|
+
bundled?: string;
|
|
10
|
+
|
|
11
|
+
@IsOptional()
|
|
12
|
+
@IsString()
|
|
13
|
+
package?: string;
|
|
14
|
+
|
|
15
|
+
@IsOptional()
|
|
16
|
+
@IsBoolean()
|
|
17
|
+
enabled?: boolean;
|
|
18
|
+
|
|
19
|
+
@IsOptional()
|
|
20
|
+
@IsObject()
|
|
21
|
+
config?: Record<string, unknown>;
|
|
22
|
+
|
|
23
|
+
@IsOptional()
|
|
24
|
+
@IsIn(["trusted", "sandboxed"])
|
|
25
|
+
trustMode?: "trusted" | "sandboxed";
|
|
26
|
+
|
|
27
|
+
@IsOptional()
|
|
28
|
+
@IsArray()
|
|
29
|
+
@IsString({ each: true })
|
|
30
|
+
capabilities?: string[];
|
|
31
|
+
|
|
32
|
+
/** When true and `package` is set, runs `pnpm add <package> --filter @openadminjs/api` (dev / non-production only). */
|
|
33
|
+
@IsOptional()
|
|
34
|
+
@IsBoolean()
|
|
35
|
+
runPnpmInstall?: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class PatchPluginDto {
|
|
39
|
+
@IsOptional()
|
|
40
|
+
@IsBoolean()
|
|
41
|
+
enabled?: boolean;
|
|
42
|
+
|
|
43
|
+
@IsOptional()
|
|
44
|
+
@IsObject()
|
|
45
|
+
config?: Record<string, unknown>;
|
|
46
|
+
|
|
47
|
+
@IsOptional()
|
|
48
|
+
@IsIn(["trusted", "sandboxed"])
|
|
49
|
+
trustMode?: "trusted" | "sandboxed";
|
|
50
|
+
|
|
51
|
+
@IsOptional()
|
|
52
|
+
@IsArray()
|
|
53
|
+
@IsString({ each: true })
|
|
54
|
+
capabilities?: string[];
|
|
55
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { UnprocessableEntityException } from "@nestjs/common";
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import { defineResource } from "@openadminjs/core";
|
|
4
|
+
import { parseWritePayload } from "./validate-resource-payload";
|
|
5
|
+
|
|
6
|
+
describe("parseWritePayload", () => {
|
|
7
|
+
const widget = defineResource({
|
|
8
|
+
name: "widgets",
|
|
9
|
+
label: "Widgets",
|
|
10
|
+
model: "Widget",
|
|
11
|
+
permissions: { read: "w.read", create: "w.create", update: "w.update" },
|
|
12
|
+
fields: {
|
|
13
|
+
id: { type: "id", list: true },
|
|
14
|
+
title: { type: "text", required: true, list: true },
|
|
15
|
+
count: { type: "number", list: true },
|
|
16
|
+
mode: { type: "select", options: ["a", "b"], list: true },
|
|
17
|
+
published: { type: "boolean", required: true, list: true }
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it("accepts valid create payload", () => {
|
|
22
|
+
const out = parseWritePayload(widget, "create", { title: "Hi", count: "3", mode: "a", published: true });
|
|
23
|
+
expect(out.title).toBe("Hi");
|
|
24
|
+
expect(out.count).toBe(3);
|
|
25
|
+
expect(out.mode).toBe("a");
|
|
26
|
+
expect(out.published).toBe(true);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("rejects missing required field on create", () => {
|
|
30
|
+
expect(() => parseWritePayload(widget, "create", { count: 1 })).toThrow(UnprocessableEntityException);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it("rejects missing required boolean on create (does not default to false)", () => {
|
|
34
|
+
expect(() => parseWritePayload(widget, "create", { title: "x", count: 0, mode: "a" })).toThrow(
|
|
35
|
+
UnprocessableEntityException
|
|
36
|
+
);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("rejects unknown keys (strict)", () => {
|
|
40
|
+
expect(() =>
|
|
41
|
+
parseWritePayload(widget, "create", { title: "x", mode: "a", published: false, extra: 1 })
|
|
42
|
+
).toThrow(UnprocessableEntityException);
|
|
43
|
+
});
|
|
44
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { UnprocessableEntityException } from "@nestjs/common";
|
|
2
|
+
import type { ResourceConfig, ResourceField } from "@openadminjs/core";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
function fieldSchema(field: ResourceField, mode: "create" | "edit"): z.ZodTypeAny {
|
|
6
|
+
const required = Boolean(field.required && mode === "create");
|
|
7
|
+
const optionalize = <T extends z.ZodTypeAny>(schema: T) => (required ? schema : schema.optional()) as z.ZodTypeAny;
|
|
8
|
+
|
|
9
|
+
switch (field.type) {
|
|
10
|
+
case "number":
|
|
11
|
+
case "money": {
|
|
12
|
+
let num = z.coerce.number();
|
|
13
|
+
if (typeof field.min === "number") num = num.min(field.min, `Must be ≥ ${field.min}`);
|
|
14
|
+
if (typeof field.max === "number") num = num.max(field.max, `Must be ≤ ${field.max}`);
|
|
15
|
+
return optionalize(num);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
case "boolean":
|
|
19
|
+
if (required && mode === "create") return z.boolean();
|
|
20
|
+
return z.boolean().optional();
|
|
21
|
+
|
|
22
|
+
case "json":
|
|
23
|
+
return z.unknown().optional();
|
|
24
|
+
|
|
25
|
+
case "multiselect":
|
|
26
|
+
return optionalize(
|
|
27
|
+
z.union([
|
|
28
|
+
z.array(z.string()),
|
|
29
|
+
z.string().transform((s) =>
|
|
30
|
+
s
|
|
31
|
+
.split(",")
|
|
32
|
+
.map((x) => x.trim())
|
|
33
|
+
.filter(Boolean)
|
|
34
|
+
)
|
|
35
|
+
])
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
case "select":
|
|
39
|
+
case "badge":
|
|
40
|
+
if (field.options?.length === 1) {
|
|
41
|
+
return optionalize(z.literal(field.options[0]!));
|
|
42
|
+
}
|
|
43
|
+
if (field.options && field.options.length >= 2) {
|
|
44
|
+
return optionalize(z.enum(field.options as [string, string, ...string[]]));
|
|
45
|
+
}
|
|
46
|
+
return optionalize(z.coerce.string());
|
|
47
|
+
|
|
48
|
+
case "datetime":
|
|
49
|
+
case "date":
|
|
50
|
+
return optionalize(z.union([z.coerce.date(), z.string()]));
|
|
51
|
+
|
|
52
|
+
case "email": {
|
|
53
|
+
let email = z.string().email("Invalid email address");
|
|
54
|
+
if (typeof field.maxLength === "number") email = email.max(field.maxLength, `Max ${field.maxLength} characters`);
|
|
55
|
+
return optionalize(email);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
case "url": {
|
|
59
|
+
let url = z.string().url("Invalid URL");
|
|
60
|
+
if (typeof field.maxLength === "number") url = url.max(field.maxLength, `Max ${field.maxLength} characters`);
|
|
61
|
+
return optionalize(url);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
case "slug": {
|
|
65
|
+
let slug = z
|
|
66
|
+
.string()
|
|
67
|
+
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Slug must be lowercase alphanumeric with hyphens");
|
|
68
|
+
if (typeof field.maxLength === "number") slug = slug.max(field.maxLength);
|
|
69
|
+
return optionalize(required ? slug.min(1, "Required") : slug);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
default: {
|
|
73
|
+
let str = z.string();
|
|
74
|
+
if (typeof field.minLength === "number") str = str.min(field.minLength, `Min ${field.minLength} characters`);
|
|
75
|
+
if (typeof field.maxLength === "number") str = str.max(field.maxLength, `Max ${field.maxLength} characters`);
|
|
76
|
+
if (required) return str.min(1, "Required");
|
|
77
|
+
return str.optional();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function buildWriteSchema(resource: ResourceConfig, mode: "create" | "edit"): z.ZodObject<Record<string, z.ZodTypeAny>> {
|
|
83
|
+
const shape: Record<string, z.ZodTypeAny> = {};
|
|
84
|
+
const flag = mode === "create" ? "create" : "edit";
|
|
85
|
+
for (const [name, field] of Object.entries(resource.fields)) {
|
|
86
|
+
if (field[flag] === false || field.sensitive || field.type === "id" || field.type === "computed") continue;
|
|
87
|
+
shape[name] = fieldSchema(field, mode);
|
|
88
|
+
}
|
|
89
|
+
return z.object(shape).strict();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function parseWritePayload(resource: ResourceConfig, mode: "create" | "edit", data: Record<string, unknown>): Record<string, unknown> {
|
|
93
|
+
const schema = buildWriteSchema(resource, mode);
|
|
94
|
+
const parsed = schema.safeParse(data);
|
|
95
|
+
if (!parsed.success) {
|
|
96
|
+
throw new UnprocessableEntityException({
|
|
97
|
+
message: "Validation failed",
|
|
98
|
+
code: "VALIDATION_ERROR",
|
|
99
|
+
issues: parsed.error.flatten()
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
return parsed.data as Record<string, unknown>;
|
|
103
|
+
}
|