Files
inkreach-official-website/apps/api/src/countries/countries.service.ts
T
yeuimu ab79325ab0 perf(public): 公开读路径进程内分域缓存——meta/goods/matrix 版本域 + TTL 兜底 + in-flight 合并
- PublicCacheService:分域版本号失效(bump 即作废,不等 TTL)、loader 期间
  bump 的竞态防护(返回但不回写)、并发 miss 单飞、PUBLIC_CACHE_DISABLED
  /TTL_MS/MAX_ENTRIES 应急开关;@Global 模块
- PublicService 六端点接缓存:列表缓存全量物化(分页切片在缓存外按请求执行,
  修复'所有页返回第一页'的切片缓存错误)、详情/首页/树/标签组/树序元数据/
  族最低价聚合各按依赖域缓存
- 全写路径挂钩 bump:admin CRUD(goods/categories/countries/tags/tag-groups/
  positions/origin-goods 标签)、sync 三同步、族重算、整理全家桶——
  事务提交成功后失效对应域,product-families 经 recompute 天然覆盖
- 测试:PublicCacheService 单测 13 例 + 失效链路集成 8 例(读命中/写后立即可见
  端到端/每条写路径域断言);既有两套件测数据语义改为显式禁缓存
2026-09-03 03:40:20 +08:00

128 lines
3.7 KiB
TypeScript

import { Prisma } from '@prisma/client';
import {
BadRequestException,
ConflictException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { PublicCacheService } from '../public/public-cache.service';
import { CreateCountryDto } from './dto/create-country.dto';
import { UpdateCountryDto } from './dto/update-country.dto';
import { ReorderCountriesDto } from './dto/reorder-countries.dto';
@Injectable()
export class CountriesService {
constructor(
private readonly prisma: PrismaService,
private readonly publicCache: PublicCacheService,
) {}
findAll() {
return this.prisma.country.findMany({
orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }],
});
}
/** 批量保存拖拽后的顺序(全量提交,sortOrder = 目标下标) */
async reorder(dto: ReorderCountriesDto) {
await this.prisma.$transaction(
dto.items.map((item) =>
this.prisma.country.update({
where: { id: BigInt(item.id) },
data: { sortOrder: item.sortOrder },
}),
),
);
this.publicCache.bump('meta');
return this.findAll();
}
async findOne(id: bigint) {
const country = await this.prisma.country.findUnique({ where: { id } });
if (!country) {
throw new NotFoundException(`Country ${id} not found`);
}
return country;
}
async create(dto: CreateCountryDto) {
try {
const created = await this.prisma.country.create({
data: {
countryName: dto.countryName,
countryIcon: dto.countryIcon ?? null,
},
});
this.publicCache.bump('meta');
return created;
} catch (err) {
if (
err instanceof Prisma.PrismaClientKnownRequestError &&
err.code === 'P2002'
) {
throw new ConflictException('Country name already exists');
}
throw err;
}
}
async update(id: bigint, dto: UpdateCountryDto) {
await this.findOne(id);
try {
const updated = await this.prisma.country.update({
where: { id },
data: {
countryName: dto.countryName,
countryIcon: dto.countryIcon === undefined ? undefined : dto.countryIcon,
},
});
this.publicCache.bump('meta');
return updated;
} catch (err) {
if (
err instanceof Prisma.PrismaClientKnownRequestError &&
err.code === 'P2002'
) {
throw new ConflictException('Country name already exists');
}
throw err;
}
}
async remove(id: bigint) {
await this.findOne(id);
try {
const removed = await this.prisma.country.delete({ where: { id } });
this.publicCache.bump('meta');
return removed;
} catch (err) {
if (this.isForeignKeyViolation(err)) {
throw new BadRequestException(
'Country is referenced by goods or positions and cannot be deleted',
);
}
throw err;
}
}
private isForeignKeyViolation(err: unknown): boolean {
if (err instanceof Prisma.PrismaClientKnownRequestError) {
// P2003 = FK constraint violation
return err.code === 'P2003';
}
// Fallback: Prisma sometimes surfaces FK violations as UnknownRequestError
// when the constraint check happens server-side before the typed error
// is mapped (e.g. cascading RESTRICT).
if (err instanceof Prisma.PrismaClientUnknownRequestError) {
const msg = err.message ?? '';
return (
msg.includes('foreign key constraint') ||
msg.includes('RESTRICT') ||
msg.includes('violates')
);
}
return false;
}
}