| 1 | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose' |
| 2 | import { UserType } from '@yikart/common' |
| 3 | import { AssetStatus, AssetType } from '../enums/asset.enum' |
| 4 | import { DEFAULT_SCHEMA_OPTIONS } from '../mongodb.constants' |
| 5 | import { WithTimestampSchema } from './timestamp.schema' |
| 6 | |
| 7 | /** 图片元数据 */ |
| 8 | export interface ImageMetadata { |
| 9 | width: number |
| 10 | height: number |
| 11 | } |
| 12 | |
| 13 | /** 视频元数据 */ |
| 14 | export interface VideoMetadata { |
| 15 | width?: number |
| 16 | height?: number |
| 17 | duration?: number // seconds |
| 18 | cover?: string // 封面图 path |
| 19 | bitrate?: number // bps |
| 20 | frameRate?: number // fps |
| 21 | } |
| 22 | |
| 23 | /** 音频元数据 */ |
| 24 | export interface AudioMetadata { |
| 25 | duration: number // seconds |
| 26 | bitrate?: number // bps |
| 27 | sampleRate?: number // Hz |
| 28 | channels?: number |
| 29 | } |
| 30 | |
| 31 | /** Asset 元数据联合类型 */ |
| 32 | export type AssetMetadata = ImageMetadata | VideoMetadata | AudioMetadata |
| 33 | |
| 34 | @Schema({ ...DEFAULT_SCHEMA_OPTIONS, collection: 'assets' }) |
| 35 | export class Asset extends WithTimestampSchema { |
| 36 | id: string |
| 37 | |
| 38 | @Prop({ required: true }) |
| 39 | userId: string |
| 40 | |
| 41 | @Prop({ |
| 42 | required: true, |
| 43 | enum: UserType, |
| 44 | default: UserType.User, |
| 45 | }) |
| 46 | userType: UserType |
| 47 | |
| 48 | @Prop({ required: true }) |
| 49 | path: string |
| 50 | |
| 51 | @Prop({ required: true, enum: AssetType }) |
| 52 | type: AssetType |
| 53 | |
| 54 | @Prop({ required: true, enum: AssetStatus, default: AssetStatus.Pending }) |
| 55 | status: AssetStatus |
| 56 | |
| 57 | @Prop() |
| 58 | size?: number |
| 59 | |
| 60 | @Prop({ required: true }) |
| 61 | mimeType: string |
| 62 | |
| 63 | @Prop() |
| 64 | filename?: string |
| 65 | |
| 66 | @Prop({ type: Object }) |
| 67 | metadata?: AssetMetadata |
| 68 | |
| 69 | @Prop({ type: Date }) |
| 70 | expiresAt?: Date |
| 71 | |
| 72 | @Prop({ type: Date }) |
| 73 | deletedAt?: Date |
| 74 | } |
| 75 | |
| 76 | export const AssetSchema = SchemaFactory.createForClass(Asset) |
| 77 | |
| 78 | AssetSchema.index({ userId: 1, userType: 1, type: 1, status: 1 }) |
| 79 | AssetSchema.index({ userId: 1, userType: 1, createdAt: -1 }) |
| 80 | AssetSchema.index({ path: 1 }, { unique: true }) |
| 81 | AssetSchema.index( |
| 82 | { expiresAt: 1 }, |
| 83 | { expireAfterSeconds: 0, partialFilterExpression: { expiresAt: { $exists: true } } }, |
| 84 | ) |
| 85 | AssetSchema.index( |
| 86 | { status: 1, createdAt: -1 }, |
| 87 | { partialFilterExpression: { deletedAt: { $exists: false } } }, |
| 88 | ) |
| 89 | AssetSchema.index({ status: 1, deletedAt: 1, createdAt: -1 }) |
| 90 |