universo-platform-3d
108 строк · 2.7 Кб
1import { Injectable } from '@nestjs/common'
2import { InjectModel } from '@nestjs/mongoose'
3import { Model, Types } from 'mongoose'
4import { CreateUserGroupDto } from './dto/create-group.users.dto'
5import { UpdateUserGroupDto } from './dto/update-group.users.dto'
6import { UserGroup, UserGroupDocument } from './user-group.schema'
7
8@Injectable()
9export class UserGroupService {
10constructor(
11@InjectModel(UserGroup.name)
12private userGroupModel: Model<UserGroupDocument>
13) {}
14
15public create(createUserGroupDto: CreateUserGroupDto): Promise<any> {
16const created = new this.userGroupModel(createUserGroupDto)
17return created.save()
18}
19
20public findOne(id: string): Promise<any> {
21return this.userGroupModel
22.aggregate<UserGroupDocument[]>()
23.append({ $match: { _id: new Types.ObjectId(id) } })
24.lookup({
25from: 'users',
26localField: 'creator',
27foreignField: '_id',
28as: 'creator'
29})
30.unwind({ path: '$creator' })
31.exec()
32}
33
34public update(
35id: string,
36updateUserGroupDto: UpdateUserGroupDto
37): Promise<any> {
38return this.userGroupModel
39.findByIdAndUpdate(id, updateUserGroupDto, { new: true })
40.exec()
41}
42
43public remove(id: string): Promise<any> {
44return this.userGroupModel.findOneAndDelete({ _id: id }).exec()
45}
46
47/**
48* @description Returns all groups where the user is a creator, user, owner, or moderator
49*/
50public findAllForUser(userId: string): Promise<any> {
51return this.userGroupModel
52.find()
53.where({
54$or: [
55{
56creator: { $in: [userId] }
57},
58{
59users: { $in: [userId] }
60},
61{
62owners: { $in: [userId] }
63},
64{
65moderators: { $in: [userId] }
66}
67]
68})
69.exec()
70}
71
72public search(searchParams): Promise<any> {
73return this.userGroupModel
74.find({
75[searchParams.filterField]: {
76$regex: new RegExp(searchParams.filterValue),
77$options: 'i'
78}
79})
80.sort({ [searchParams.sortField]: searchParams.sortValue })
81.limit(searchParams.limit)
82.skip(searchParams.skip)
83.exec()
84}
85
86public removeMember(groupId, idUserRemove): Promise<any> {
87return this.userGroupModel
88.findByIdAndUpdate(
89groupId,
90{
91$pull: {
92users: idUserRemove,
93owners: idUserRemove,
94moderators: idUserRemove
95}
96},
97{ new: true }
98)
99.exec()
100}
101
102public async findGroupsInformation(userLinks): Promise<any> {
103const groupsIds = []
104userLinks.map((userLink) => groupsIds.push(userLink.group))
105
106return await this.userGroupModel.find({ _id: groupsIds })
107}
108}
109