返回 AiToEarn
media-group.repository.ts
根目录 / project / aitoearn-backend / libs / mongodb / src / repositories / media-group.repository.ts
1 /*
2 * @Author: nevin
3 * @Date: 2024-06-17 19:19:15
4 * @LastEditTime: 2024-09-05 15:19:25
5 * @LastEditors: nevin
6 * @Description: Material material
7 */
8 import { Injectable, Logger } from '@nestjs/common'
9 import { InjectModel } from '@nestjs/mongoose'
10 import { UserType } from '@yikart/common'
11 import { Model, RootFilterQuery } from 'mongoose'
12 import { MediaGroup } from '../schemas/media-group.schema'
13 import { MediaType } from '../schemas/media.schema'
14 import { BaseRepository } from './base.repository'
15
16 @Injectable()
17 export class MediaGroupRepository extends BaseRepository<MediaGroup> {
18 logger = new Logger(MediaGroupRepository.name)
19 constructor(
20 @InjectModel(MediaGroup.name)
21 private readonly mediaGroupModel: Model<MediaGroup>,
22 ) {
23 super(mediaGroupModel)
24 }
25
26 private async createDefaultGroupIfNotExists(userId: string, type: MediaType): Promise<boolean> {
27 try {
28 // 检查是否已存在默认组
29 const existingGroup = await this.mediaGroupModel.findOne({
30 userId,
31 type,
32 isDefault: true,
33 }).lean({ virtuals: true })
34
35 // 如果已存在默认组,直接返回 true
36 if (existingGroup) {
37 return true
38 }
39
40 // 创建默认组
41 const newGroup = await this.mediaGroupModel.create({
42 userId,
43 title: 'Default',
44 type,
45 isDefault: true,
46 })
47
48 return !!newGroup
49 }
50 catch (error) {
51 this.logger.error(`Error creating default ${type} group:`, error)
52 return false
53 }
54 }
55
56 async createDefault(userId: string): Promise<boolean> {
57 try {
58 const defaultGroups = await Promise.all([
59 this.createDefaultGroupIfNotExists(userId, MediaType.IMG),
60 this.createDefaultGroupIfNotExists(userId, MediaType.VIDEO),
61 ])
62 // 如果任何一个组创建失败,则返回 false
63 return defaultGroups.every(result => result === true)
64 }
65 catch (error) {
66 this.logger.error('Error creating default media groups:', error)
67 return false
68 }
69 }
70
71 async getDefaultGroup(userId: string) {
72 return await this.mediaGroupModel.findOne({ userId, isDefault: true }).lean({ virtuals: true })
73 }
74
75 override async create(newData: Partial<MediaGroup>) {
76 return await this.mediaGroupModel.create(newData)
77 }
78
79 // 删除
80 async delete(id: string): Promise<boolean> {
81 const res = await this.mediaGroupModel.deleteOne({ _id: id })
82 return res.deletedCount > 0
83 }
84
85 // 修改
86 async update(id: string, newData: Partial<MediaGroup>) {
87 const res = await this.mediaGroupModel.updateOne({ _id: id }, newData)
88 return res.modifiedCount > 0
89 }
90
91 async getInfo(id: string) {
92 return await this.mediaGroupModel.findOne({ _id: id }).lean({ virtuals: true })
93 }
94
95 async getInfoByName(userId: string, title: string) {
96 return await this.mediaGroupModel.findOne({ userId, title: { $regex: title, $options: 'i' } }).sort({ createdAt: -1 }).lean({ virtuals: true })
97 }
98
99 async getList(inFilter: {
100 userId?: string
101 userType?: UserType
102 title?: string
103 type?: MediaType
104 }, pageInfo: {
105 pageNo: number
106 pageSize: number
107 }) {
108 const { pageNo, pageSize } = pageInfo
109 const filter: RootFilterQuery<MediaGroup> = {
110 ...(inFilter.userId && { userId: inFilter.userId }),
111 userType: inFilter.userType || UserType.User,
112 ...(inFilter.type && { type: inFilter.type }),
113 ...(inFilter.title && {
114 title: { $regex: inFilter.title, $options: 'i' },
115 }),
116 }
117
118 const [total, list] = await Promise.all([
119 this.mediaGroupModel.countDocuments(filter),
120 this.mediaGroupModel
121 .find(filter)
122 .sort({ createdAt: -1 })
123 .skip((pageNo! - 1) * pageSize)
124 .limit(pageSize)
125 .lean({ virtuals: true })
126 .exec(),
127 ])
128
129 return {
130 total,
131 list,
132 }
133 }
134 }
135
135 lines TYPESCRIPT