refactor: 收口多品牌 API 控制器边界
This commit is contained in:
1 parent
98e66a60de
commit
178ffc2c11
5 files changed
+531
-493
No files matched your search
@@ -0,0 +1,243 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
import { CreateTrustContentDto, UpdateBrandDto, UpdateTrustContentDto } from "../../admin.dto.js";
|
||||
import { getVisualTemplate } from "@personal-brand/config";
|
||||
|
||||
@Controller("admin/config")
|
||||
export class AdminConfigController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
private brandId(request?: FastifyRequest): string {
|
||||
if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
return identity.brandId;
|
||||
}
|
||||
private requireAdmin(request: FastifyRequest): void {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
try {
|
||||
identity = readIdentity(token);
|
||||
} catch {
|
||||
throw new UnauthorizedException("管理员登录态无效或已过期");
|
||||
}
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
}
|
||||
@Get("brand")
|
||||
getBrand(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.brandProfile.findUnique({ where: { id: this.brandId(request) } });
|
||||
}
|
||||
@Patch("brand")
|
||||
async updateBrand(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: UpdateBrandDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const { config, ...fields } = body;
|
||||
const current = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: this.brandId(request) },
|
||||
select: { config: true },
|
||||
});
|
||||
const currentConfig =
|
||||
current?.config && typeof current.config === "object" && !Array.isArray(current.config)
|
||||
? (current.config as Record<string, unknown>)
|
||||
: {};
|
||||
const nextConfig = config ? { ...currentConfig, ...config } : undefined;
|
||||
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
|
||||
const installation = await this.prisma.brandTemplateInstallation.findFirst({
|
||||
where: { brandId: this.brandId(request) },
|
||||
});
|
||||
if (installation) {
|
||||
const history = Array.isArray(installation.previousSnapshots)
|
||||
? installation.previousSnapshots
|
||||
: [];
|
||||
await this.prisma.brandTemplateInstallation.update({
|
||||
where: { id: installation.id },
|
||||
data: {
|
||||
previousSnapshots: [
|
||||
...history,
|
||||
{
|
||||
visualTemplateKey: currentConfig.visualTemplateKey ?? "linjing-editorial",
|
||||
savedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return this.prisma.brandProfile.update({
|
||||
where: { id: this.brandId(request) },
|
||||
data: {
|
||||
...fields,
|
||||
...(nextConfig ? { config: nextConfig as Prisma.InputJsonValue } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
@Get("visual-template/history")
|
||||
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.brandTemplateInstallation
|
||||
.findFirst({ where: { brandId: this.brandId(request) }, select: { previousSnapshots: true } })
|
||||
.then((installation) => ({
|
||||
history: Array.isArray(installation?.previousSnapshots)
|
||||
? installation.previousSnapshots.filter(
|
||||
(item) =>
|
||||
item &&
|
||||
typeof item === "object" &&
|
||||
!Array.isArray(item) &&
|
||||
"visualTemplateKey" in item,
|
||||
)
|
||||
: [],
|
||||
}));
|
||||
}
|
||||
@Post("visual-template/rollback")
|
||||
async rollbackVisualTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const brandId = this.brandId(request);
|
||||
const [brand, installation] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
|
||||
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
|
||||
]);
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const history = Array.isArray(installation?.previousSnapshots)
|
||||
? installation.previousSnapshots
|
||||
: [];
|
||||
const index = [...history]
|
||||
.map((item, i) => ({ item, i }))
|
||||
.reverse()
|
||||
.find(
|
||||
({ item }) =>
|
||||
item && typeof item === "object" && !Array.isArray(item) && "visualTemplateKey" in item,
|
||||
)?.i;
|
||||
const previous =
|
||||
index === undefined ? undefined : (history[index] as { visualTemplateKey?: unknown });
|
||||
if (!previous || typeof previous.visualTemplateKey !== "string")
|
||||
throw new BadRequestException("没有可回滚的视觉模板版本");
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: {
|
||||
config: {
|
||||
...config,
|
||||
visualTemplateKey: previous.visualTemplateKey,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
}),
|
||||
...(installation
|
||||
? [
|
||||
this.prisma.brandTemplateInstallation.update({
|
||||
where: { id: installation.id },
|
||||
data: { previousSnapshots: history.slice(0, index) },
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
return { visualTemplateKey: previous.visualTemplateKey, rolledBack: true };
|
||||
}
|
||||
@Get("visual-template/preview")
|
||||
getVisualTemplatePreview(@Req() request: FastifyRequest): unknown {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.brandProfile
|
||||
.findUnique({ where: { id: this.brandId(request) }, select: { config: true } })
|
||||
.then((brand) => {
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const currentKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: "linjing-editorial";
|
||||
const current = getVisualTemplate(currentKey) ?? getVisualTemplate("linjing-editorial");
|
||||
return {
|
||||
current: current
|
||||
? {
|
||||
key: current.key,
|
||||
version: current.version,
|
||||
name: current.name,
|
||||
theme: current.theme,
|
||||
variants: current.variants,
|
||||
}
|
||||
: null,
|
||||
available: ["linjing-editorial", "minimal-neutral"],
|
||||
};
|
||||
});
|
||||
}
|
||||
@Get("trust-content")
|
||||
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.trustContent.findMany({
|
||||
where: { brandId: this.brandId(request) },
|
||||
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
||||
});
|
||||
}
|
||||
@Post("trust-content")
|
||||
createTrustContent(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateTrustContentDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.trustContent.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId: this.brandId(request),
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
@Patch("trust-content/:id")
|
||||
async updateTrustContent(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateTrustContentDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const item = await this.prisma.trustContent.findFirst({
|
||||
where: { id, brandId: this.brandId(request) },
|
||||
});
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.trustContent.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
@Delete("trust-content/:id")
|
||||
async deleteTrustContent(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const item = await this.prisma.trustContent.findFirst({
|
||||
where: { id, brandId: this.brandId(request) },
|
||||
});
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
await this.prisma.trustContent.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user