|
| 1 | +import { Injectable } from '@nestjs/common' |
| 2 | +import { InjectModel } from '@nestjs/mongoose' |
| 3 | +import { Model } from 'mongoose' |
| 4 | +import { Setting } from '~/core/settings/_schemas/setting.schema' |
| 5 | +import { AbstractService } from '~/_common/abstracts/abstract.service' |
| 6 | +import { ConfigService } from '@nestjs/config' |
| 7 | +import { MixedSettingValue } from '~/core/settings/settings.interface' |
| 8 | +import { SettingFor } from '~/core/settings/_enum/setting-for.enum' |
| 9 | +import { IdentityType } from '~/_common/types/identity.type' |
| 10 | +import { set } from 'radash' |
| 11 | + |
| 12 | +@Injectable() |
| 13 | +export class SettingsService extends AbstractService { |
| 14 | + public constructor( |
| 15 | + protected readonly config: ConfigService, |
| 16 | + @InjectModel(Setting.name) protected _model: Model<Setting>, |
| 17 | + ) { |
| 18 | + super() |
| 19 | + } |
| 20 | + |
| 21 | + public async settings(forType: SettingFor[], identity: IdentityType): Promise<any> { |
| 22 | + const settingsBase = this.config.get<MixedSettingValue>(`settings`) |
| 23 | + const filters = [{ for: SettingFor.ALL, scope: null }] |
| 24 | + forType.forEach((type) => { |
| 25 | + switch (type) { |
| 26 | + case SettingFor.USER: { |
| 27 | + filters.push({ for: type, scope: identity._id.toString() }) |
| 28 | + break |
| 29 | + } |
| 30 | + case SettingFor.ROLE: { |
| 31 | + for (const role of identity.roles) { |
| 32 | + filters.push({ for: type, scope: role }) |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + }) |
| 37 | + const settings = await this._model.find( |
| 38 | + { $or: filters }, |
| 39 | + { key: 1, value: 1, _id: 0 }, |
| 40 | + { sort: { for: 1, scope: 1 } }, |
| 41 | + ) |
| 42 | + |
| 43 | + for (const setting of settings) { |
| 44 | + set(settingsBase as object, setting.key, setting.value) |
| 45 | + } |
| 46 | + return settingsBase |
| 47 | + } |
| 48 | + |
| 49 | + protected setting<T>(name: string): T | MixedSettingValue { |
| 50 | + return this.config.get<MixedSettingValue>(`settings.${name}`) |
| 51 | + } |
| 52 | + |
| 53 | + public async get<T>(name: string): Promise<T | MixedSettingValue> { |
| 54 | + const setting = await this._model.findOne({ name }) |
| 55 | + if (setting) return setting.value |
| 56 | + return this.setting<T>(name) |
| 57 | + } |
| 58 | + |
| 59 | + public async set<T>( |
| 60 | + key: string, |
| 61 | + value: T | MixedSettingValue, |
| 62 | + options?: { for: SettingFor, scope: string }, |
| 63 | + ): Promise<T | MixedSettingValue> { |
| 64 | + const updated = await this._model.findOneAndUpdate( |
| 65 | + { key }, |
| 66 | + { $set: { value, ...options } }, |
| 67 | + { upsert: true, new: true }, |
| 68 | + ) |
| 69 | + return updated.value |
| 70 | + } |
| 71 | +} |
0 commit comments