gongxiangp2/lib/performance-survey-attachment-contract.ts

57 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export const PERFORMANCE_CASE_UPLOAD_PURPOSE = 'performance-case'
export const PERFORMANCE_CASE_ATTACHMENT_LIMITS = {
count: 5,
totalBytes: 256 * 1024 * 1024,
videoBytes: 200 * 1024 * 1024,
documentBytes: 50 * 1024 * 1024,
previewPages: 100,
} as const
export const PERFORMANCE_CASE_FILE_TYPES: Record<string, { kind: 'video' | 'document'; mime: string }> = {
mp4: { kind: 'video', mime: 'video/mp4' },
mov: { kind: 'video', mime: 'video/quicktime' },
webm: { kind: 'video', mime: 'video/webm' },
ppt: { kind: 'document', mime: 'application/vnd.ms-powerpoint' },
pptx: { kind: 'document', mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' },
doc: { kind: 'document', mime: 'application/msword' },
docx: { kind: 'document', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' },
pdf: { kind: 'document', mime: 'application/pdf' },
}
export function getPerformanceCaseFileType(name: string) {
const extension = name.split('.').pop()?.toLowerCase() || ''
const type = name.includes('.') && Object.hasOwn(PERFORMANCE_CASE_FILE_TYPES, extension) ? PERFORMANCE_CASE_FILE_TYPES[extension] : null
return type ? { ...type, extension } : null
}
export type PerformanceCaseAttachment = {
id: string
originalName: string
kind: string
size: number
status: string
pageCount: number | null
previewPageCount: number | null
error: string | null
}
export function validatePerformanceCaseAttachments(files: Array<{ name: string; size: number }>) {
const limits = PERFORMANCE_CASE_ATTACHMENT_LIMITS
if (files.length > limits.count) return '每个案例最多添加5个视频或文档'
if (files.reduce((sum, file) => sum + file.size, 0) > limits.totalBytes) return '视频和文档合计不能超过256MB'
for (const file of files) {
const type = getPerformanceCaseFileType(file.name)
if (!type) return `文件「${file.name}」格式不支持,请选择MP4、MOV、WebM、PPT、PPTX、DOC、DOCX或PDF`
if (!Number.isSafeInteger(file.size) || file.size <= 0) return `文件「${file.name}」为空或大小无效`
const limit = type.kind === 'video' ? limits.videoBytes : limits.documentBytes
if (file.size > limit) return `文件「${file.name}」超过${type.kind === 'video' ? '200' : '50'}MB`
}
return null
}
export function serializePerformanceCaseAttachments(records: PerformanceCaseAttachment[] = []) {
return records.map(({ id, originalName, kind, size, status, pageCount, previewPageCount, error }) => ({
id, originalName, kind, size, status, pageCount, previewPageCount, error,
}))
}