universo-platform-3d

Форк
0
159 строк · 4.4 Кб
1
import {
2
  BadRequestException,
3
  ForbiddenException,
4
  Inject,
5
  Injectable,
6
  NotFoundException,
7
  forwardRef
8
} from '@nestjs/common'
9
import { InjectModel } from '@nestjs/mongoose'
10
import { Environment, EnvironmentDocument } from './environment.schema'
11
import { Model, Types } from 'mongoose'
12
import { UpdateEnvironmentDto } from './dto/update-environment.dto'
13
import { ObjectId } from 'mongodb'
14
import { Space, SpaceDocument } from '../space/space.schema'
15
import {
16
  SpaceService,
17
  SpaceServiceType,
18
  SpaceWithStandardPopulatedProperties
19
} from '../space/space.service'
20
import { UserId } from '../util/mongo-object-id-helpers'
21

22
@Injectable()
23
export class EnvironmentService {
24
  constructor(
25
    @InjectModel(Environment.name)
26
    private readonly environmentModel: Model<EnvironmentDocument>,
27
    @InjectModel(Space.name)
28
    private spaceModel: Model<SpaceDocument>,
29
    @Inject(forwardRef(() => SpaceService))
30
    private readonly spaceService: SpaceServiceType
31
  ) {}
32

33
  public create() {
34
    const createdEnvironment = new this.environmentModel()
35
    return createdEnvironment.save()
36
  }
37

38
  public findOne(id: string) {
39
    return this.environmentModel.findById(id).exec()
40
  }
41

42
  public async findOneWithRolesCheck(id: string, userId: UserId) {
43
    const environment = await this.environmentModel.findById(id).exec()
44
    if (!environment) {
45
      throw new NotFoundException()
46
    }
47

48
    // find the space that is associated with this environment
49
    const space = await this.spaceModel
50
      .findOne({ environment: new ObjectId(id) })
51
      .exec()
52

53
    if (!space) {
54
      throw new NotFoundException()
55
    }
56

57
    // get the space with standard populated properties
58
    // this is necessary to check if the user has access to the space
59
    const spaceWithStandardPopulatedProperties =
60
      await this.spaceService.getSpace(space._id)
61

62
    // check if the user has access to the space
63
    if (
64
      this.spaceService.canFindWithRolesCheck(
65
        userId,
66
        spaceWithStandardPopulatedProperties
67
      )
68
    ) {
69
      return environment
70
    } else {
71
      throw new ForbiddenException()
72
    }
73
  }
74

75
  public update(id: string, dto: UpdateEnvironmentDto) {
76
    return this.environmentModel
77
      .findByIdAndUpdate(id, dto, { new: true })
78
      .exec()
79
  }
80

81
  public async updateWithRolesCheck(
82
    id: string,
83
    dto: UpdateEnvironmentDto,
84
    userId: UserId
85
  ) {
86
    const environment = await this.environmentModel.findById(id).exec()
87
    if (!environment) {
88
      throw new NotFoundException()
89
    }
90

91
    // find the space that is associated with this environment
92
    const space = await this.spaceModel
93
      .findOne({ environment: new ObjectId(id) })
94
      .exec()
95

96
    if (!space) {
97
      throw new NotFoundException()
98
    }
99

100
    // get the space with standard populated properties
101
    // this is necessary to check if the user has access to the space
102
    const spaceWithStandardPopulatedProperties =
103
      await this.spaceService.getSpace(space._id)
104

105
    // check if the user has access to the space
106
    if (
107
      this.spaceService.canUpdateWithRolesCheck(
108
        userId,
109
        spaceWithStandardPopulatedProperties
110
      )
111
    ) {
112
      return this.environmentModel
113
        .findByIdAndUpdate(id, dto, { new: true })
114
        .exec()
115
    } else {
116
      throw new ForbiddenException()
117
    }
118
  }
119

120
  public async copyFromEnvironment(environmentId: string) {
121
    let environment: EnvironmentDocument
122

123
    if (!environmentId) {
124
      environment = new this.environmentModel()
125
    } else {
126
      environment = await this.environmentModel.findById(environmentId).exec()
127
      environment._id = new ObjectId()
128
      environment.isNew = true
129
      environment.updatedAt = new Date()
130
      environment.createdAt = new Date()
131
    }
132

133
    return environment.save()
134
  }
135

136
  public remove(id: string) {
137
    if (!Types.ObjectId.isValid(id)) {
138
      throw new BadRequestException('ID is not a valid Mongo ObjectID')
139
    }
140
    return this.environmentModel
141
      .findOneAndDelete({ _id: id }, { new: true })
142
      .exec()
143
      .then((data) => {
144
        if (data) {
145
          return data
146
        } else {
147
          throw new NotFoundException()
148
        }
149
      })
150
  }
151

152
  public async restoreEnvironment(environment: EnvironmentDocument) {
153
    environment._id = new ObjectId()
154
    const newEnvironment = new this.environmentModel(environment)
155
    newEnvironment.updatedAt = new Date()
156
    newEnvironment.createdAt = new Date()
157
    return await newEnvironment.save()
158
  }
159
}
160

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.