feat: integrate Prisma into createPayer function and enhance error handling for existing ABN

This commit is contained in:
Astrian Zheng 2025-01-12 08:10:21 +11:00
parent 3446954648
commit 361bfc6d75
Signed by: Astrian
SSH Key Fingerprint: SHA256:rVnhx3DAKjujCwWE13aDl7uV6+9U1MvydLkNRXJrBiA
3 changed files with 34 additions and 23 deletions

View File

@ -5,6 +5,7 @@ import Debug from 'debug'
import koaBody from 'koa-body'
import func from './func'
import { ErrorDescEnum, HttpError } from './types/HttpError'
import { PrismaClient } from '@prisma/client'
dotenv.config()
console.log = Debug('invoiceIssuer:app.ts')
@ -12,10 +13,13 @@ console.log = Debug('invoiceIssuer:app.ts')
const app = new Koa()
app.use(koaBody())
// 错误处理中间件
// 语境中间件
app.use(async (ctx, next) => {
try {
const prismaClient = new PrismaClient()
ctx.prisma = prismaClient
await next()
prismaClient.$disconnect()
} catch (e) {
if (e instanceof HttpError) {
ctx.status = e.status
@ -65,7 +69,7 @@ app.use(route.post('/payer', async (ctx) => {
if (abn && !abnRegex.test(abn)) throw new HttpError(ErrorDescEnum.invalid_field_format, 400, ['abn'])
// 创建新的付款人
await func.createPayer(name, address, email, abn)
await func.createPayer(ctx.prisma, name, address, email, abn)
ctx.status = 204
}))

View File

@ -1,5 +1,6 @@
import Debug from 'debug'
import { PrismaClient } from '@prisma/client'
import { ErrorDescEnum, HttpError } from '../types/HttpError'
import { PrismaClient, Prisma } from '@prisma/client'
console.log = Debug('invoiceIssuer:func/createPayer.ts')
@ -11,24 +12,23 @@ console.log = Debug('invoiceIssuer:func/createPayer.ts')
* @param {string} email -
* @param {string} abn -
*/
export default async (name: string, address: string[], email: string, abn?: string) => {
const prisma = new PrismaClient()
export default async (prisma: PrismaClient<Prisma.PrismaClientOptions, never>, name: string, address: string[], email: string, abn?: string) => {
// 验证 ABN 是否已存在
const existingPayer = await prisma.payer.findFirst({
where: {
payer_abn: abn
}
})
if (existingPayer) throw new HttpError(ErrorDescEnum.item_exists, 400, ['abn'])
try {
// 创建新的付款人
const payer = await prisma.payer.create({
data: {
payer_name: name,
payer_address: address.join('\n'),
payer_email: email,
payer_abn: abn
}
})
return payer
} catch (e) {
console.log(e)
throw new Error('unknown_issues')
} finally {
await prisma.$disconnect()
}
// 创建新的付款人
const payer = await prisma.payer.create({
data: {
payer_name: name,
payer_address: address.join('\n'),
payer_email: email,
payer_abn: abn
}
})
return payer
}

View File

@ -34,14 +34,21 @@ enum ErrorDescEnum {
* HTTP 400 Bad Request 使
*/
required_fields_missing = 'required_fields_missing',
/**
* HTTP 400 Bad Request 使
*/
invalid_field_format = 'invalid_field_format',
/**
* HTTP 500 Internal Server Error 使
*/
unknown_issues = 'unknown_issues'
unknown_issues = 'unknown_issues',
/**
* HTTP 400 Bad Request 使
*/
item_exists = 'item_exists'
}
export { HttpError, ErrorDescEnum }