36 lines
804 B
TypeScript
36 lines
804 B
TypeScript
|
|
import { randomBytes } from 'crypto'
|
||
|
|
|
||
|
|
export function generateTrackingCode(prefix: string, suffixLength: number) {
|
||
|
|
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
|
||
|
|
const bytes = randomBytes(suffixLength)
|
||
|
|
|
||
|
|
let suffix = ''
|
||
|
|
for (let i = 0; i < suffixLength; i++) {
|
||
|
|
suffix += chars[bytes[i] % chars.length]
|
||
|
|
}
|
||
|
|
|
||
|
|
return `${prefix}-${suffix}`
|
||
|
|
}
|
||
|
|
|
||
|
|
export function isTrackingCodeUniqueViolation(error: unknown) {
|
||
|
|
const prismaError = error as {
|
||
|
|
code?: string
|
||
|
|
meta?: { target?: string[] | string }
|
||
|
|
}
|
||
|
|
|
||
|
|
if (prismaError?.code !== 'P2002') {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
|
||
|
|
const target = prismaError.meta?.target
|
||
|
|
if (Array.isArray(target)) {
|
||
|
|
return target.includes('tracking_code')
|
||
|
|
}
|
||
|
|
|
||
|
|
if (typeof target === 'string') {
|
||
|
|
return target.includes('tracking_code')
|
||
|
|
}
|
||
|
|
|
||
|
|
return true
|
||
|
|
}
|