refactor: 拆分客户订单控制器
This commit is contained in:
1 parent
ee7f64c5f3
commit
f4a93bba23
3 files changed
+64
-55
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import { BadRequestException, Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { BookingService } from "../../booking.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { CreateBookingDto } from "../../booking.dto.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
|
||||
@Controller("customer/bookings")
|
||||
export class CustomerBookingController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly bookings: BookingService,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
async create(@Req() request: FastifyRequest, @Body() body: CreateBookingDto): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const customer = await this.prisma.customerUser.findUnique({
|
||||
where: { brandId_openid: identity },
|
||||
});
|
||||
if (!customer) throw new BadRequestException("请先完成微信登录");
|
||||
return this.bookings.create(identity.brandId, customer.id, {
|
||||
...body,
|
||||
extraData: body.extraData as Prisma.InputJsonObject,
|
||||
});
|
||||
}
|
||||
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const customer = await this.prisma.customerUser.findUnique({
|
||||
where: { brandId_openid: identity },
|
||||
});
|
||||
if (!customer) throw new BadRequestException("请先完成微信登录");
|
||||
return this.bookings.listForCustomer(identity.brandId, customer.id);
|
||||
}
|
||||
|
||||
@Post(":id/cancel")
|
||||
async cancel(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const customer = await this.prisma.customerUser.findUnique({
|
||||
where: { brandId_openid: identity },
|
||||
});
|
||||
if (!customer) throw new BadRequestException("请先完成微信登录");
|
||||
return this.bookings.cancelForCustomer(identity.brandId, customer.id, id);
|
||||
}
|
||||
|
||||
private identity(request: FastifyRequest): { brandId: string; openid: string } {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new BadRequestException("缺少客户登录态");
|
||||
try {
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "customer") throw new BadRequestException("客户登录态无效");
|
||||
return { brandId: identity.brandId, openid: identity.subject };
|
||||
} catch (error) {
|
||||
if (error instanceof BadRequestException) throw error;
|
||||
throw new BadRequestException("客户登录态无效");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user