Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { AccountGroup } from '../schemas/account-group.schema'
import { BaseRepository } from './base.repository'
export class AccountGroupRepository extends BaseRepository<AccountGroup> {
constructor(
@InjectModel(AccountGroup.name)
private readonly accountGroupModel: Model<AccountGroup>,
) { super(accountGroupModel) }
// 获取默认用户组, 没有则创建
async getDefaultGroup(userId: string): Promise<AccountGroup> {
return await this.accountGroupModel
.findOneAndUpdate(
{ userId, isDefault: true },
{
$setOnInsert: {
isDefault: true,
name: 'default',
rank: 1,
userId,
},
},
{ upsert: true, new: true },
)
.lean({ virtuals: true })
.exec()
}
/**
* 添加组
* @param accountGroup
*/
async createAccountGroup(
accountGroup: Partial<AccountGroup>,
): Promise<AccountGroup> {
const created = await this.accountGroupModel.create(accountGroup)
return created.toObject()
}
/**
* 更新组
* @param accountGroup
*/
async updateAccountGroup(
id: string,
accountGroup: Partial<AccountGroup>,
): Promise<boolean> {
const res = await this.accountGroupModel.findByIdAndUpdate(
id,
{ $set: accountGroup },
).lean({ virtuals: true })
return !!res
}
/**
* 更新组
* @param accountGroup
*/
async getAccountGorupListByIds(
ids: string[],
userId: string,
) {
const accountGorupList = await this.accountGroupModel
.find({ userId, _id: { $in: ids } })
.lean({ virtuals: true })
.exec()
return accountGorupList
}
/**
* 删除多个组
* @param ids
* @param userId
*/
async deleteAccountGroup(ids: string[], userId: string): Promise<boolean> {
const res = await this.accountGroupModel.deleteMany({
_id: { $in: ids },
userId,
})
return res.deletedCount > 0
}
/**
* 获取所有组
* @param userId
* @returns
*/
async getAccountGroup(userId: string): Promise<AccountGroup[]> {
const accountGroupList: AccountGroup[] = await this.accountGroupModel.find({
userId,
}).lean({ virtuals: true })
// 创建默认用户组
if (accountGroupList.length === 0) {
const accountGroup = await this.getDefaultGroup(userId)
accountGroupList.push(accountGroup)
}
return accountGroupList
}
// 排序
async sortRank(userId: string, list: { id: string, rank: number }[]) {
const promises = list.map(element =>
this.accountGroupModel.updateOne(
{ userId, _id: element.id },
{ $set: { rank: element.rank } },
),
)
await Promise.all(promises)
return true
}
// 根据名称获取账户组列表
async getAccountGroupByName(userId: string, name: string): Promise<AccountGroup[]> {
const accountGroupList: AccountGroup[] = await this.accountGroupModel.find({
userId,
name: { $regex: name, $options: 'i' },
}).sort({ rank: 1 }).lean({ virtuals: true })
return accountGroupList
}
async listIdsByIp(ip: string): Promise<string[]> {
const groups = await this.accountGroupModel
.find({ ip: { $regex: ip, $options: 'i' } }, { _id: 1 })
.lean({ virtuals: true })
return groups.map(g => g._id.toString())
}
}