Files
persionalBrand/apps/api/src/modules/customer/customer-inquiry-submission.controller.ts
T

71 lines
2.3 KiB
TypeScript

import {
Body,
Controller,
ForbiddenException,
Get,
NotFoundException,
Param,
Post,
Req,
UnauthorizedException,
} from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { readIdentity } from "../../auth.js";
import { CreateInquirySubmissionDto } from "../../booking.dto.js";
import { CustomerInquirySubmissionService } from "./customer-inquiry-submission.service.js";
@Controller("customer/inquiry-submissions")
export class CustomerInquirySubmissionController {
constructor(private readonly submissions: CustomerInquirySubmissionService) {}
private present<T extends { customerSubject: string; adminNote?: string | null }>(submission: T) {
const {
customerSubject: _customerSubject,
adminNote: _adminNote,
...publicSubmission
} = submission;
void _customerSubject;
void _adminNote;
return publicSubmission;
}
private identity(request: FastifyRequest): ReturnType<typeof readIdentity> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少客户登录态");
try {
const identity = readIdentity(token);
if (identity.role !== "customer") throw new ForbiddenException("无客户权限");
return identity;
} catch (error) {
if (error instanceof ForbiddenException) throw error;
throw new UnauthorizedException("客户登录态无效或已过期");
}
}
@Get()
async list(@Req() request: FastifyRequest): Promise<unknown> {
const identity = this.identity(request);
const submissions = await this.submissions.listForCustomer(identity.brandId, identity.subject);
return submissions.map((submission) => this.present(submission));
}
@Get(":id")
async get(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const identity = this.identity(request);
const submission = await this.submissions.getForCustomer(
identity.brandId,
identity.subject,
id,
);
return this.present(submission);
}
@Post()
async create(
@Req() request: FastifyRequest,
@Body() body: CreateInquirySubmissionDto,
): Promise<unknown> {
const identity = this.identity(request);
const submission = await this.submissions.create(identity.brandId, identity.subject, body);
return this.present(submission);
}
}