feat: 搭建 NestJS 后端基础设施与 Prisma 数据模型
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -48,4 +48,6 @@
|
|||||||
|
|
||||||
- 阶段 0(脚手架)已完成:pnpm monorepo(apps/* + packages/*)、根脚本、`.env`/`.env.example`、`docker/docker-compose.dev.yml`(MySQL 8 + Redis7-alpine,本地镜像)、`packages/shared`(枚举/错误码/响应类型/常量,含出库导入列定义)。MySQL/Redis 已起并连通,shared 已构建。
|
- 阶段 0(脚手架)已完成:pnpm monorepo(apps/* + packages/*)、根脚本、`.env`/`.env.example`、`docker/docker-compose.dev.yml`(MySQL 8 + Redis7-alpine,本地镜像)、`packages/shared`(枚举/错误码/响应类型/常量,含出库导入列定义)。MySQL/Redis 已起并连通,shared 已构建。
|
||||||
- 约定:shared 用 tsc 构建为 CommonJS 供 api/admin/h5 复用;env 驱动存储(local/oss)、区块链(mock/tianhe)、Geo(mock) 可切换。
|
- 约定:shared 用 tsc 构建为 CommonJS 供 api/admin/h5 复用;env 驱动存储(local/oss)、区块链(mock/tianhe)、Geo(mock) 可切换。
|
||||||
|
- 阶段 1(后端基础设施)已完成:`apps/api` NestJS 工程;Prisma 全量建模并迁移(init),生成客户端;全局统一响应拦截器/异常过滤器/校验管道/BigInt 序列化;ConfigModule 读根 `.env`(dotenv-cli 供 Prisma CLI 用 `dotenv -e ../../.env`);静态目录 `/uploads`;Swagger 在 `/api/docs`。已验证启动、DB 连接、health/app-info 正常。
|
||||||
|
- 踩坑:pnpm 10 默认禁用原生构建脚本,已在根 `pnpm.onlyBuiltDependencies` 放行 prisma/sharp 等;Prisma migrate 需 shadow db 权限,开发库已对 `artveris` 用户授予全部权限;nanoid 固定 ^3(CJS)。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
{
|
||||||
|
"name": "@artveris/api",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"start": "node dist/main.js",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:prod": "node dist/main.js",
|
||||||
|
"prisma:generate": "prisma generate",
|
||||||
|
"prisma:migrate": "dotenv -e ../../.env -- prisma migrate dev",
|
||||||
|
"prisma:deploy": "dotenv -e ../../.env -- prisma migrate deploy",
|
||||||
|
"prisma:studio": "dotenv -e ../../.env -- prisma studio",
|
||||||
|
"seed": "dotenv -e ../../.env -- ts-node prisma/seed.ts",
|
||||||
|
"test": "jest",
|
||||||
|
"lint": "echo \"(api) lint skipped\""
|
||||||
|
},
|
||||||
|
"prisma": {
|
||||||
|
"seed": "ts-node prisma/seed.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@artveris/shared": "workspace:*",
|
||||||
|
"@aws-sdk/client-s3": "^3.700.0",
|
||||||
|
"@aws-sdk/s3-request-presigner": "^3.700.0",
|
||||||
|
"@nestjs/bullmq": "^10.2.3",
|
||||||
|
"@nestjs/common": "^10.4.15",
|
||||||
|
"@nestjs/config": "^3.3.0",
|
||||||
|
"@nestjs/core": "^10.4.15",
|
||||||
|
"@nestjs/jwt": "^10.2.0",
|
||||||
|
"@nestjs/platform-express": "^10.4.15",
|
||||||
|
"@nestjs/serve-static": "^4.0.2",
|
||||||
|
"@nestjs/swagger": "^8.1.0",
|
||||||
|
"@prisma/client": "^5.22.0",
|
||||||
|
"bcryptjs": "^2.4.3",
|
||||||
|
"bullmq": "^5.34.6",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.1",
|
||||||
|
"dayjs": "^1.11.13",
|
||||||
|
"exceljs": "^4.4.0",
|
||||||
|
"ioredis": "^5.4.2",
|
||||||
|
"nanoid": "^3.3.8",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1",
|
||||||
|
"sharp": "^0.33.5"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@nestjs/cli": "^10.4.9",
|
||||||
|
"@nestjs/schematics": "^10.2.3",
|
||||||
|
"@nestjs/testing": "^10.4.15",
|
||||||
|
"@types/bcryptjs": "^2.4.6",
|
||||||
|
"@types/express": "^4.17.21",
|
||||||
|
"@types/jest": "^29.5.14",
|
||||||
|
"@types/multer": "^1.4.12",
|
||||||
|
"@types/node": "^22.10.2",
|
||||||
|
"@types/qrcode": "^1.5.5",
|
||||||
|
"dotenv-cli": "^7.4.4",
|
||||||
|
"jest": "^29.7.0",
|
||||||
|
"prisma": "^5.22.0",
|
||||||
|
"ts-jest": "^29.2.5",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.6.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sys_user` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`username` VARCHAR(191) NOT NULL,
|
||||||
|
`password_hash` VARCHAR(191) NOT NULL,
|
||||||
|
`real_name` VARCHAR(191) NULL,
|
||||||
|
`role` ENUM('SUPER_ADMIN', 'OPERATOR', 'AUDITOR', 'VIEWER') NOT NULL DEFAULT 'VIEWER',
|
||||||
|
`status` ENUM('ACTIVE', 'DISABLED') NOT NULL DEFAULT 'ACTIVE',
|
||||||
|
`last_login_at` DATETIME(3) NULL,
|
||||||
|
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
`updated_at` DATETIME(3) NOT NULL,
|
||||||
|
|
||||||
|
UNIQUE INDEX `sys_user_username_key`(`username`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `template` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`name` VARCHAR(191) NOT NULL,
|
||||||
|
`remark` VARCHAR(191) NULL,
|
||||||
|
`status` ENUM('ENABLED', 'DISABLED') NOT NULL DEFAULT 'ENABLED',
|
||||||
|
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
`updated_at` DATETIME(3) NOT NULL,
|
||||||
|
`deleted_at` DATETIME(3) NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `template_field` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`template_id` INTEGER NOT NULL,
|
||||||
|
`field_key` VARCHAR(191) NOT NULL,
|
||||||
|
`label` VARCHAR(191) NOT NULL,
|
||||||
|
`type` ENUM('TEXT', 'NUMBER', 'DATE', 'IMAGE', 'FILE', 'LINK', 'TEXTAREA') NOT NULL DEFAULT 'TEXT',
|
||||||
|
`required` BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
`sort_order` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
|
||||||
|
INDEX `template_field_template_id_idx`(`template_id`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `artwork` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`template_id` INTEGER NOT NULL,
|
||||||
|
`title` VARCHAR(191) NOT NULL,
|
||||||
|
`artist` VARCHAR(191) NULL,
|
||||||
|
`dynamic_fields` JSON NULL,
|
||||||
|
`images` JSON NULL,
|
||||||
|
`status` ENUM('DRAFT', 'ACTIVE', 'DISABLED') NOT NULL DEFAULT 'DRAFT',
|
||||||
|
`created_by` INTEGER NULL,
|
||||||
|
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
`updated_at` DATETIME(3) NOT NULL,
|
||||||
|
`deleted_at` DATETIME(3) NULL,
|
||||||
|
|
||||||
|
INDEX `artwork_template_id_idx`(`template_id`),
|
||||||
|
INDEX `artwork_status_idx`(`status`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `trace_node` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`artwork_id` INTEGER NOT NULL,
|
||||||
|
`node_type` ENUM('CREATE', 'PRODUCE', 'STORAGE', 'OUTBOUND', 'OTHER') NOT NULL DEFAULT 'OTHER',
|
||||||
|
`title` VARCHAR(191) NOT NULL,
|
||||||
|
`occurred_at` DATETIME(3) NULL,
|
||||||
|
`location` VARCHAR(191) NULL,
|
||||||
|
`description` TEXT NULL,
|
||||||
|
`media_files` JSON NULL,
|
||||||
|
`sort_order` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
|
||||||
|
INDEX `trace_node_artwork_id_idx`(`artwork_id`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `certificate` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`artwork_id` INTEGER NOT NULL,
|
||||||
|
`name` VARCHAR(191) NOT NULL,
|
||||||
|
`issuer` VARCHAR(191) NULL,
|
||||||
|
`issued_at` DATETIME(3) NULL,
|
||||||
|
`type` ENUM('PHOTO', 'CERT', 'APPRAISAL') NOT NULL DEFAULT 'CERT',
|
||||||
|
`origin_file_url` VARCHAR(191) NOT NULL,
|
||||||
|
`watermark_file_url` VARCHAR(191) NULL,
|
||||||
|
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
|
||||||
|
INDEX `certificate_artwork_id_idx`(`artwork_id`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `batch` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`batch_no` VARCHAR(191) NOT NULL,
|
||||||
|
`quantity` INTEGER NOT NULL,
|
||||||
|
`generated_count` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
`status` ENUM('PENDING', 'GENERATING', 'DONE', 'FAILED') NOT NULL DEFAULT 'PENDING',
|
||||||
|
`created_by` INTEGER NULL,
|
||||||
|
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
|
||||||
|
UNIQUE INDEX `batch_batch_no_key`(`batch_no`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `trace_code` (
|
||||||
|
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||||
|
`code` VARCHAR(191) NOT NULL,
|
||||||
|
`short_code` VARCHAR(191) NOT NULL,
|
||||||
|
`artwork_id` INTEGER NULL,
|
||||||
|
`batch_id` INTEGER NULL,
|
||||||
|
`sku` VARCHAR(191) NULL,
|
||||||
|
`archive_no` VARCHAR(191) NULL,
|
||||||
|
`out_time` DATETIME(3) NULL,
|
||||||
|
`out_image` VARCHAR(191) NULL,
|
||||||
|
`remark` VARCHAR(191) NULL,
|
||||||
|
`status` ENUM('UNBOUND', 'INACTIVE', 'ACTIVE', 'DISABLED', 'ABNORMAL') NOT NULL DEFAULT 'UNBOUND',
|
||||||
|
`query_count` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
`first_activated_at` DATETIME(3) NULL,
|
||||||
|
`last_queried_at` DATETIME(3) NULL,
|
||||||
|
`url` VARCHAR(191) NULL,
|
||||||
|
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
|
||||||
|
UNIQUE INDEX `trace_code_code_key`(`code`),
|
||||||
|
UNIQUE INDEX `trace_code_short_code_key`(`short_code`),
|
||||||
|
UNIQUE INDEX `trace_code_artwork_id_key`(`artwork_id`),
|
||||||
|
INDEX `trace_code_batch_id_idx`(`batch_id`),
|
||||||
|
INDEX `trace_code_status_idx`(`status`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `blockchain_proof` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`trace_code_id` BIGINT NOT NULL,
|
||||||
|
`data_hash` VARCHAR(191) NOT NULL,
|
||||||
|
`tx_hash` VARCHAR(191) NULL,
|
||||||
|
`block_hash` VARCHAR(191) NULL,
|
||||||
|
`block_height` BIGINT NULL,
|
||||||
|
`chain_name` VARCHAR(191) NULL,
|
||||||
|
`explorer_url` VARCHAR(191) NULL,
|
||||||
|
`onchain_at` DATETIME(3) NULL,
|
||||||
|
`status` ENUM('PENDING', 'ONCHAIN', 'FAILED') NOT NULL DEFAULT 'PENDING',
|
||||||
|
`raw_response` JSON NULL,
|
||||||
|
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
|
||||||
|
INDEX `blockchain_proof_trace_code_id_idx`(`trace_code_id`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `query_log` (
|
||||||
|
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||||
|
`trace_code_id` BIGINT NULL,
|
||||||
|
`artwork_id` INTEGER NULL,
|
||||||
|
`short_code` VARCHAR(191) NULL,
|
||||||
|
`queried_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
`query_result` ENUM('FIRST_ACTIVATE', 'REPEAT', 'INVALID', 'DISABLED', 'ABNORMAL') NOT NULL,
|
||||||
|
`ip` VARCHAR(191) NULL,
|
||||||
|
`region` VARCHAR(191) NULL,
|
||||||
|
`user_agent` TEXT NULL,
|
||||||
|
`device_type` VARCHAR(191) NULL,
|
||||||
|
|
||||||
|
INDEX `query_log_trace_code_id_idx`(`trace_code_id`),
|
||||||
|
INDEX `query_log_queried_at_idx`(`queried_at`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `job` (
|
||||||
|
`id` VARCHAR(191) NOT NULL,
|
||||||
|
`type` ENUM('GEN_CODE', 'IMPORT_OUTBOUND', 'WATERMARK', 'ONCHAIN') NOT NULL,
|
||||||
|
`status` ENUM('PENDING', 'PROCESSING', 'SUCCESS', 'PARTIAL', 'FAILED') NOT NULL DEFAULT 'PENDING',
|
||||||
|
`total` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
`success_count` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
`fail_count` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
`result_file_url` VARCHAR(191) NULL,
|
||||||
|
`payload` JSON NULL,
|
||||||
|
`error` TEXT NULL,
|
||||||
|
`created_by` INTEGER NULL,
|
||||||
|
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
`updated_at` DATETIME(3) NOT NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `system_setting` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`key` VARCHAR(191) NOT NULL,
|
||||||
|
`value` TEXT NOT NULL,
|
||||||
|
`updated_at` DATETIME(3) NOT NULL,
|
||||||
|
|
||||||
|
UNIQUE INDEX `system_setting_key_key`(`key`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `template_field` ADD CONSTRAINT `template_field_template_id_fkey` FOREIGN KEY (`template_id`) REFERENCES `template`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `artwork` ADD CONSTRAINT `artwork_template_id_fkey` FOREIGN KEY (`template_id`) REFERENCES `template`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `artwork` ADD CONSTRAINT `artwork_created_by_fkey` FOREIGN KEY (`created_by`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `trace_node` ADD CONSTRAINT `trace_node_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `certificate` ADD CONSTRAINT `certificate_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_batch_id_fkey` FOREIGN KEY (`batch_id`) REFERENCES `batch`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `blockchain_proof` ADD CONSTRAINT `blockchain_proof_trace_code_id_fkey` FOREIGN KEY (`trace_code_id`) REFERENCES `trace_code`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `query_log` ADD CONSTRAINT `query_log_trace_code_id_fkey` FOREIGN KEY (`trace_code_id`) REFERENCES `trace_code`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (i.e. Git)
|
||||||
|
provider = "mysql"
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "mysql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum RoleType {
|
||||||
|
SUPER_ADMIN
|
||||||
|
OPERATOR
|
||||||
|
AUDITOR
|
||||||
|
VIEWER
|
||||||
|
}
|
||||||
|
|
||||||
|
enum UserStatus {
|
||||||
|
ACTIVE
|
||||||
|
DISABLED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TemplateStatus {
|
||||||
|
ENABLED
|
||||||
|
DISABLED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum FieldType {
|
||||||
|
TEXT
|
||||||
|
NUMBER
|
||||||
|
DATE
|
||||||
|
IMAGE
|
||||||
|
FILE
|
||||||
|
LINK
|
||||||
|
TEXTAREA
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ArtworkStatus {
|
||||||
|
DRAFT
|
||||||
|
ACTIVE
|
||||||
|
DISABLED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum NodeType {
|
||||||
|
CREATE
|
||||||
|
PRODUCE
|
||||||
|
STORAGE
|
||||||
|
OUTBOUND
|
||||||
|
OTHER
|
||||||
|
}
|
||||||
|
|
||||||
|
enum CertType {
|
||||||
|
PHOTO
|
||||||
|
CERT
|
||||||
|
APPRAISAL
|
||||||
|
}
|
||||||
|
|
||||||
|
enum BatchStatus {
|
||||||
|
PENDING
|
||||||
|
GENERATING
|
||||||
|
DONE
|
||||||
|
FAILED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TraceCodeStatus {
|
||||||
|
UNBOUND
|
||||||
|
INACTIVE
|
||||||
|
ACTIVE
|
||||||
|
DISABLED
|
||||||
|
ABNORMAL
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ProofStatus {
|
||||||
|
PENDING
|
||||||
|
ONCHAIN
|
||||||
|
FAILED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum QueryResult {
|
||||||
|
FIRST_ACTIVATE
|
||||||
|
REPEAT
|
||||||
|
INVALID
|
||||||
|
DISABLED
|
||||||
|
ABNORMAL
|
||||||
|
}
|
||||||
|
|
||||||
|
enum JobType {
|
||||||
|
GEN_CODE
|
||||||
|
IMPORT_OUTBOUND
|
||||||
|
WATERMARK
|
||||||
|
ONCHAIN
|
||||||
|
}
|
||||||
|
|
||||||
|
enum JobStatus {
|
||||||
|
PENDING
|
||||||
|
PROCESSING
|
||||||
|
SUCCESS
|
||||||
|
PARTIAL
|
||||||
|
FAILED
|
||||||
|
}
|
||||||
|
|
||||||
|
model SysUser {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
username String @unique
|
||||||
|
passwordHash String @map("password_hash")
|
||||||
|
realName String? @map("real_name")
|
||||||
|
role RoleType @default(VIEWER)
|
||||||
|
status UserStatus @default(ACTIVE)
|
||||||
|
lastLoginAt DateTime? @map("last_login_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
artworks Artwork[]
|
||||||
|
|
||||||
|
@@map("sys_user")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Template {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String
|
||||||
|
remark String?
|
||||||
|
status TemplateStatus @default(ENABLED)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
deletedAt DateTime? @map("deleted_at")
|
||||||
|
|
||||||
|
fields TemplateField[]
|
||||||
|
artworks Artwork[]
|
||||||
|
|
||||||
|
@@map("template")
|
||||||
|
}
|
||||||
|
|
||||||
|
model TemplateField {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
templateId Int @map("template_id")
|
||||||
|
fieldKey String @map("field_key")
|
||||||
|
label String
|
||||||
|
type FieldType @default(TEXT)
|
||||||
|
required Boolean @default(false)
|
||||||
|
sortOrder Int @default(0) @map("sort_order")
|
||||||
|
|
||||||
|
template Template @relation(fields: [templateId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([templateId])
|
||||||
|
@@map("template_field")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Artwork {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
templateId Int @map("template_id")
|
||||||
|
title String
|
||||||
|
artist String?
|
||||||
|
dynamicFields Json? @map("dynamic_fields")
|
||||||
|
images Json?
|
||||||
|
status ArtworkStatus @default(DRAFT)
|
||||||
|
createdBy Int? @map("created_by")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
deletedAt DateTime? @map("deleted_at")
|
||||||
|
|
||||||
|
template Template @relation(fields: [templateId], references: [id])
|
||||||
|
creator SysUser? @relation(fields: [createdBy], references: [id])
|
||||||
|
traceNodes TraceNode[]
|
||||||
|
certificates Certificate[]
|
||||||
|
traceCode TraceCode?
|
||||||
|
|
||||||
|
@@index([templateId])
|
||||||
|
@@index([status])
|
||||||
|
@@map("artwork")
|
||||||
|
}
|
||||||
|
|
||||||
|
model TraceNode {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
artworkId Int @map("artwork_id")
|
||||||
|
nodeType NodeType @default(OTHER) @map("node_type")
|
||||||
|
title String
|
||||||
|
occurredAt DateTime? @map("occurred_at")
|
||||||
|
location String?
|
||||||
|
description String? @db.Text
|
||||||
|
mediaFiles Json? @map("media_files")
|
||||||
|
sortOrder Int @default(0) @map("sort_order")
|
||||||
|
|
||||||
|
artwork Artwork @relation(fields: [artworkId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([artworkId])
|
||||||
|
@@map("trace_node")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Certificate {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
artworkId Int @map("artwork_id")
|
||||||
|
name String
|
||||||
|
issuer String?
|
||||||
|
issuedAt DateTime? @map("issued_at")
|
||||||
|
type CertType @default(CERT)
|
||||||
|
originFileUrl String @map("origin_file_url")
|
||||||
|
watermarkFileUrl String? @map("watermark_file_url")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
artwork Artwork @relation(fields: [artworkId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([artworkId])
|
||||||
|
@@map("certificate")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Batch {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
batchNo String @unique @map("batch_no")
|
||||||
|
quantity Int
|
||||||
|
generatedCount Int @default(0) @map("generated_count")
|
||||||
|
status BatchStatus @default(PENDING)
|
||||||
|
createdBy Int? @map("created_by")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
traceCodes TraceCode[]
|
||||||
|
|
||||||
|
@@map("batch")
|
||||||
|
}
|
||||||
|
|
||||||
|
model TraceCode {
|
||||||
|
id BigInt @id @default(autoincrement())
|
||||||
|
code String @unique
|
||||||
|
shortCode String @unique @map("short_code")
|
||||||
|
artworkId Int? @unique @map("artwork_id")
|
||||||
|
batchId Int? @map("batch_id")
|
||||||
|
sku String?
|
||||||
|
archiveNo String? @map("archive_no")
|
||||||
|
outTime DateTime? @map("out_time")
|
||||||
|
outImage String? @map("out_image")
|
||||||
|
remark String?
|
||||||
|
status TraceCodeStatus @default(UNBOUND)
|
||||||
|
queryCount Int @default(0) @map("query_count")
|
||||||
|
firstActivatedAt DateTime? @map("first_activated_at")
|
||||||
|
lastQueriedAt DateTime? @map("last_queried_at")
|
||||||
|
url String?
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
artwork Artwork? @relation(fields: [artworkId], references: [id])
|
||||||
|
batch Batch? @relation(fields: [batchId], references: [id])
|
||||||
|
proofs BlockchainProof[]
|
||||||
|
queryLogs QueryLog[]
|
||||||
|
|
||||||
|
@@index([batchId])
|
||||||
|
@@index([status])
|
||||||
|
@@map("trace_code")
|
||||||
|
}
|
||||||
|
|
||||||
|
model BlockchainProof {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
traceCodeId BigInt @map("trace_code_id")
|
||||||
|
dataHash String @map("data_hash")
|
||||||
|
txHash String? @map("tx_hash")
|
||||||
|
blockHash String? @map("block_hash")
|
||||||
|
blockHeight BigInt? @map("block_height")
|
||||||
|
chainName String? @map("chain_name")
|
||||||
|
explorerUrl String? @map("explorer_url")
|
||||||
|
onchainAt DateTime? @map("onchain_at")
|
||||||
|
status ProofStatus @default(PENDING)
|
||||||
|
rawResponse Json? @map("raw_response")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
traceCode TraceCode @relation(fields: [traceCodeId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([traceCodeId])
|
||||||
|
@@map("blockchain_proof")
|
||||||
|
}
|
||||||
|
|
||||||
|
model QueryLog {
|
||||||
|
id BigInt @id @default(autoincrement())
|
||||||
|
traceCodeId BigInt? @map("trace_code_id")
|
||||||
|
artworkId Int? @map("artwork_id")
|
||||||
|
shortCode String? @map("short_code")
|
||||||
|
queriedAt DateTime @default(now()) @map("queried_at")
|
||||||
|
queryResult QueryResult @map("query_result")
|
||||||
|
ip String?
|
||||||
|
region String?
|
||||||
|
userAgent String? @db.Text @map("user_agent")
|
||||||
|
deviceType String? @map("device_type")
|
||||||
|
|
||||||
|
traceCode TraceCode? @relation(fields: [traceCodeId], references: [id])
|
||||||
|
|
||||||
|
@@index([traceCodeId])
|
||||||
|
@@index([queriedAt])
|
||||||
|
@@map("query_log")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Job {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
type JobType
|
||||||
|
status JobStatus @default(PENDING)
|
||||||
|
total Int @default(0)
|
||||||
|
successCount Int @default(0) @map("success_count")
|
||||||
|
failCount Int @default(0) @map("fail_count")
|
||||||
|
resultFileUrl String? @map("result_file_url")
|
||||||
|
payload Json?
|
||||||
|
error String? @db.Text
|
||||||
|
createdBy Int? @map("created_by")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("job")
|
||||||
|
}
|
||||||
|
|
||||||
|
model SystemSetting {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
key String @unique
|
||||||
|
value String @db.Text
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("system_setting")
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { Controller, Get } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
||||||
|
import { Public } from './common/decorators/public.decorator';
|
||||||
|
|
||||||
|
@ApiTags('系统')
|
||||||
|
@Controller()
|
||||||
|
export class AppController {
|
||||||
|
constructor(private readonly config: ConfigService) {}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Get('health')
|
||||||
|
@ApiOperation({ summary: '健康检查' })
|
||||||
|
health() {
|
||||||
|
return { status: 'ok', time: new Date().toISOString() };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Get('app-info')
|
||||||
|
@ApiOperation({ summary: '应用基本信息(公开)' })
|
||||||
|
appInfo() {
|
||||||
|
return { appName: this.config.get<string>('appName') };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import configuration from './config/configuration';
|
||||||
|
import { PrismaModule } from './prisma/prisma.module';
|
||||||
|
import { AppController } from './app.controller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
load: [configuration],
|
||||||
|
envFilePath: ['../../.env', '.env'],
|
||||||
|
}),
|
||||||
|
PrismaModule,
|
||||||
|
],
|
||||||
|
controllers: [AppController],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||||
|
|
||||||
|
export interface AuthUser {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
role: string;
|
||||||
|
realName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CurrentUser = createParamDecorator(
|
||||||
|
(data: keyof AuthUser | undefined, ctx: ExecutionContext): AuthUser | unknown => {
|
||||||
|
const request = ctx.switchToHttp().getRequest();
|
||||||
|
const user = request.user as AuthUser;
|
||||||
|
return data ? user?.[data] : user;
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const IS_PUBLIC_KEY = 'isPublic';
|
||||||
|
// 标记接口为公开(无需登录),用于 C 端溯源等匿名访问。
|
||||||
|
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
import { RoleType } from '@artveris/shared';
|
||||||
|
|
||||||
|
export const ROLES_KEY = 'roles';
|
||||||
|
// 限定可访问的角色;未标注则任意已登录用户可访问。
|
||||||
|
export const Roles = (...roles: RoleType[]) => SetMetadata(ROLES_KEY, roles);
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import { IsInt, IsOptional, Max, Min } from 'class-validator';
|
||||||
|
|
||||||
|
export class PaginationDto {
|
||||||
|
@ApiPropertyOptional({ description: '页码,从 1 开始', default: 1 })
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
page = 1;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ description: '每页条数', default: 10 })
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
@Max(200)
|
||||||
|
pageSize = 10;
|
||||||
|
|
||||||
|
get skip(): number {
|
||||||
|
return (this.page - 1) * this.pageSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
get take(): number {
|
||||||
|
return this.pageSize;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { ErrorMessage } from '@artveris/shared';
|
||||||
|
|
||||||
|
// 业务异常:携带统一业务码,由全局过滤器转换为标准响应体。
|
||||||
|
export class BusinessException extends Error {
|
||||||
|
constructor(
|
||||||
|
public readonly code: number,
|
||||||
|
message?: string,
|
||||||
|
public readonly httpStatus = 400,
|
||||||
|
) {
|
||||||
|
super(message || ErrorMessage[code] || '业务处理失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import {
|
||||||
|
ArgumentsHost,
|
||||||
|
Catch,
|
||||||
|
ExceptionFilter,
|
||||||
|
HttpException,
|
||||||
|
HttpStatus,
|
||||||
|
Logger,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Response } from 'express';
|
||||||
|
import { ErrorCode } from '@artveris/shared';
|
||||||
|
import { BusinessException } from '../exceptions/business.exception';
|
||||||
|
|
||||||
|
@Catch()
|
||||||
|
export class AllExceptionsFilter implements ExceptionFilter {
|
||||||
|
private readonly logger = new Logger('Exception');
|
||||||
|
|
||||||
|
catch(exception: unknown, host: ArgumentsHost): void {
|
||||||
|
const ctx = host.switchToHttp();
|
||||||
|
const res = ctx.getResponse<Response>();
|
||||||
|
|
||||||
|
let httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
let code: number = ErrorCode.INTERNAL_ERROR;
|
||||||
|
let message = '服务器内部错误';
|
||||||
|
|
||||||
|
if (exception instanceof BusinessException) {
|
||||||
|
httpStatus = exception.httpStatus;
|
||||||
|
code = exception.code;
|
||||||
|
message = exception.message;
|
||||||
|
} else if (exception instanceof HttpException) {
|
||||||
|
httpStatus = exception.getStatus();
|
||||||
|
const r = exception.getResponse();
|
||||||
|
if (typeof r === 'string') {
|
||||||
|
message = r;
|
||||||
|
} else if (r && typeof r === 'object') {
|
||||||
|
const m = (r as Record<string, unknown>).message;
|
||||||
|
message = Array.isArray(m) ? String(m[0]) : String(m ?? exception.message);
|
||||||
|
}
|
||||||
|
code = this.mapStatusToCode(httpStatus);
|
||||||
|
} else {
|
||||||
|
this.logger.error(
|
||||||
|
(exception as Error)?.message ?? String(exception),
|
||||||
|
(exception as Error)?.stack,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(httpStatus).json({ code, message, data: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapStatusToCode(status: number): number {
|
||||||
|
switch (status) {
|
||||||
|
case HttpStatus.BAD_REQUEST:
|
||||||
|
return ErrorCode.VALIDATION_FAILED;
|
||||||
|
case HttpStatus.UNAUTHORIZED:
|
||||||
|
return ErrorCode.UNAUTHORIZED;
|
||||||
|
case HttpStatus.FORBIDDEN:
|
||||||
|
return ErrorCode.FORBIDDEN;
|
||||||
|
case HttpStatus.NOT_FOUND:
|
||||||
|
return ErrorCode.NOT_FOUND;
|
||||||
|
case HttpStatus.TOO_MANY_REQUESTS:
|
||||||
|
return ErrorCode.TOO_MANY_REQUESTS;
|
||||||
|
default:
|
||||||
|
return ErrorCode.INTERNAL_ERROR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { map } from 'rxjs/operators';
|
||||||
|
import { ApiResponse } from '@artveris/shared';
|
||||||
|
|
||||||
|
// 将控制器返回值统一包裹为 { code, message, data }。
|
||||||
|
@Injectable()
|
||||||
|
export class TransformInterceptor<T> implements NestInterceptor<T, ApiResponse<T>> {
|
||||||
|
intercept(_context: ExecutionContext, next: CallHandler<T>): Observable<ApiResponse<T>> {
|
||||||
|
return next.handle().pipe(
|
||||||
|
map((data) => {
|
||||||
|
if (
|
||||||
|
data &&
|
||||||
|
typeof data === 'object' &&
|
||||||
|
'code' in (data as object) &&
|
||||||
|
'message' in (data as object) &&
|
||||||
|
'data' in (data as object)
|
||||||
|
) {
|
||||||
|
return data as unknown as ApiResponse<T>;
|
||||||
|
}
|
||||||
|
return { code: 0, message: 'success', data: (data ?? null) as T | null };
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { PageResult } from '@artveris/shared';
|
||||||
|
|
||||||
|
export function buildPage<T>(list: T[], total: number, page: number, pageSize: number): PageResult<T> {
|
||||||
|
return { list, total, page, pageSize };
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
export interface AppConfig {
|
||||||
|
appName: string;
|
||||||
|
env: string;
|
||||||
|
port: number;
|
||||||
|
baseUrl: string;
|
||||||
|
publicTracePath: string;
|
||||||
|
adminOrigin: string;
|
||||||
|
h5Origin: string;
|
||||||
|
traceUrlTemplate: string;
|
||||||
|
jwt: { secret: string; expiresIn: string };
|
||||||
|
redis: { host: string; port: number; password?: string };
|
||||||
|
storage: {
|
||||||
|
driver: 'local' | 'oss';
|
||||||
|
localDir: string;
|
||||||
|
publicPrefix: string;
|
||||||
|
cdnBaseUrl: string;
|
||||||
|
oss: {
|
||||||
|
endpoint: string;
|
||||||
|
region: string;
|
||||||
|
bucket: string;
|
||||||
|
accessKeyId: string;
|
||||||
|
accessKeySecret: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
blockchain: {
|
||||||
|
driver: 'mock' | 'tianhe';
|
||||||
|
tianhe: { baseUrl: string; appId: string; appKey: string };
|
||||||
|
};
|
||||||
|
geo: { driver: string };
|
||||||
|
seedAdmin: { username: string; password: string; name: string };
|
||||||
|
logRetentionDays: number;
|
||||||
|
watermarkText: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default (): AppConfig => {
|
||||||
|
const h5Origin = process.env.H5_ORIGIN || 'http://localhost:5174';
|
||||||
|
return {
|
||||||
|
appName: process.env.APP_NAME || '艺术品可信溯源与认证平台',
|
||||||
|
env: process.env.NODE_ENV || 'development',
|
||||||
|
port: parseInt(process.env.API_PORT || '3000', 10),
|
||||||
|
baseUrl: process.env.BASE_URL || 'http://localhost:3000',
|
||||||
|
publicTracePath: process.env.PUBLIC_TRACE_PATH || '/t',
|
||||||
|
adminOrigin: process.env.ADMIN_ORIGIN || 'http://localhost:5173',
|
||||||
|
h5Origin,
|
||||||
|
// 短链跳转到 C 端溯源页的地址模板,{code} 会被替换为短码
|
||||||
|
traceUrlTemplate:
|
||||||
|
process.env.TRACE_URL_TEMPLATE || `${h5Origin}/#/pages/trace/index?code={code}`,
|
||||||
|
jwt: {
|
||||||
|
secret: process.env.JWT_SECRET || 'artveris_dev_secret',
|
||||||
|
expiresIn: process.env.JWT_EXPIRES_IN || '7d',
|
||||||
|
},
|
||||||
|
redis: {
|
||||||
|
host: process.env.REDIS_HOST || 'localhost',
|
||||||
|
port: parseInt(process.env.REDIS_PORT || '6379', 10),
|
||||||
|
password: process.env.REDIS_PASSWORD || undefined,
|
||||||
|
},
|
||||||
|
storage: {
|
||||||
|
driver: (process.env.STORAGE_DRIVER as 'local' | 'oss') || 'local',
|
||||||
|
localDir: process.env.STORAGE_LOCAL_DIR || './storage',
|
||||||
|
publicPrefix: process.env.STORAGE_PUBLIC_PREFIX || '/uploads',
|
||||||
|
cdnBaseUrl: process.env.CDN_BASE_URL || '',
|
||||||
|
oss: {
|
||||||
|
endpoint: process.env.OSS_ENDPOINT || '',
|
||||||
|
region: process.env.OSS_REGION || '',
|
||||||
|
bucket: process.env.OSS_BUCKET || '',
|
||||||
|
accessKeyId: process.env.OSS_ACCESS_KEY_ID || '',
|
||||||
|
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET || '',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
blockchain: {
|
||||||
|
driver: (process.env.BLOCKCHAIN_DRIVER as 'mock' | 'tianhe') || 'mock',
|
||||||
|
tianhe: {
|
||||||
|
baseUrl: process.env.TIANHE_BASE_URL || '',
|
||||||
|
appId: process.env.TIANHE_APP_ID || '',
|
||||||
|
appKey: process.env.TIANHE_APP_KEY || '',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
geo: { driver: process.env.GEO_DRIVER || 'mock' },
|
||||||
|
seedAdmin: {
|
||||||
|
username: process.env.SEED_ADMIN_USERNAME || 'admin',
|
||||||
|
password: process.env.SEED_ADMIN_PASSWORD || 'Admin@12345',
|
||||||
|
name: process.env.SEED_ADMIN_NAME || '超级管理员',
|
||||||
|
},
|
||||||
|
logRetentionDays: parseInt(process.env.LOG_RETENTION_DAYS || '365', 10),
|
||||||
|
watermarkText: process.env.WATERMARK_TEXT || '仅供溯源核验使用',
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { ValidationPipe, RequestMethod, Logger } from '@nestjs/common';
|
||||||
|
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
|
import { existsSync, mkdirSync } from 'fs';
|
||||||
|
import { resolve } from 'path';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
|
||||||
|
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
|
||||||
|
|
||||||
|
// 让 BigInt 可被 JSON 序列化为字符串,避免精度问题。
|
||||||
|
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
|
||||||
|
return this.toString();
|
||||||
|
};
|
||||||
|
|
||||||
|
async function bootstrap(): Promise<void> {
|
||||||
|
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
|
||||||
|
bodyParser: true,
|
||||||
|
});
|
||||||
|
const config = app.get(ConfigService);
|
||||||
|
const logger = new Logger('Bootstrap');
|
||||||
|
|
||||||
|
app.setGlobalPrefix('api', {
|
||||||
|
exclude: [{ path: 't/:shortCode', method: RequestMethod.GET }],
|
||||||
|
});
|
||||||
|
|
||||||
|
app.enableCors({
|
||||||
|
origin: [
|
||||||
|
config.get<string>('adminOrigin') as string,
|
||||||
|
config.get<string>('h5Origin') as string,
|
||||||
|
/^http:\/\/localhost(:\d+)?$/,
|
||||||
|
/^http:\/\/127\.0\.0\.1(:\d+)?$/,
|
||||||
|
],
|
||||||
|
credentials: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
whitelist: true,
|
||||||
|
transform: true,
|
||||||
|
transformOptions: { enableImplicitConversion: true },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
app.useGlobalFilters(new AllExceptionsFilter());
|
||||||
|
app.useGlobalInterceptors(new TransformInterceptor());
|
||||||
|
|
||||||
|
// 本地文件存储静态访问
|
||||||
|
const localDir = resolve(config.get<string>('storage.localDir') || './storage');
|
||||||
|
if (!existsSync(localDir)) {
|
||||||
|
mkdirSync(localDir, { recursive: true });
|
||||||
|
}
|
||||||
|
app.useStaticAssets(localDir, {
|
||||||
|
prefix: config.get<string>('storage.publicPrefix') || '/uploads',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Swagger(开发文档)
|
||||||
|
const swaggerConfig = new DocumentBuilder()
|
||||||
|
.setTitle('artveris API')
|
||||||
|
.setDescription('艺术品可信溯源与认证系统接口文档')
|
||||||
|
.setVersion('0.1.0')
|
||||||
|
.addBearerAuth()
|
||||||
|
.build();
|
||||||
|
const document = SwaggerModule.createDocument(app, swaggerConfig);
|
||||||
|
SwaggerModule.setup('api/docs', app, document);
|
||||||
|
|
||||||
|
const port = config.get<number>('port') || 3000;
|
||||||
|
await app.listen(port);
|
||||||
|
logger.log(`API 已启动: http://localhost:${port}/api`);
|
||||||
|
logger.log(`接口文档: http://localhost:${port}/api/docs`);
|
||||||
|
}
|
||||||
|
|
||||||
|
void bootstrap();
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { PrismaService } from './prisma.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [PrismaService],
|
||||||
|
exports: [PrismaService],
|
||||||
|
})
|
||||||
|
export class PrismaModule {}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
||||||
|
private readonly logger = new Logger(PrismaService.name);
|
||||||
|
|
||||||
|
async onModuleInit(): Promise<void> {
|
||||||
|
await this.$connect();
|
||||||
|
this.logger.log('数据库已连接');
|
||||||
|
}
|
||||||
|
|
||||||
|
async onModuleDestroy(): Promise<void> {
|
||||||
|
await this.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "commonjs",
|
||||||
|
"declaration": false,
|
||||||
|
"removeComments": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "ES2021",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strictNullChecks": true,
|
||||||
|
"noImplicitAny": false,
|
||||||
|
"strictBindCallApply": false,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noFallthroughCasesInSwitch": false,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"resolveJsonModule": true
|
||||||
|
},
|
||||||
|
"include": ["src", "prisma"],
|
||||||
|
"exclude": ["node_modules", "dist"]
|
||||||
|
}
|
||||||
@@ -17,5 +17,17 @@
|
|||||||
"db:up": "docker compose --env-file .env -f docker/docker-compose.dev.yml up -d",
|
"db:up": "docker compose --env-file .env -f docker/docker-compose.dev.yml up -d",
|
||||||
"db:down": "docker compose --env-file .env -f docker/docker-compose.dev.yml down",
|
"db:down": "docker compose --env-file .env -f docker/docker-compose.dev.yml down",
|
||||||
"db:logs": "docker compose --env-file .env -f docker/docker-compose.dev.yml logs -f"
|
"db:logs": "docker compose --env-file .env -f docker/docker-compose.dev.yml logs -f"
|
||||||
|
},
|
||||||
|
"pnpm": {
|
||||||
|
"onlyBuiltDependencies": [
|
||||||
|
"@prisma/client",
|
||||||
|
"@prisma/engines",
|
||||||
|
"prisma",
|
||||||
|
"sharp",
|
||||||
|
"@nestjs/core",
|
||||||
|
"esbuild",
|
||||||
|
"@scarf/scarf",
|
||||||
|
"msgpackr-extract"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+7009
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user