All files / src/platform/settings settings.service.ts

0% Statements 0/23
0% Branches 0/20
0% Functions 0/3
0% Lines 0/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97                                                                                                                                                                                                 
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UniversalSetting } from './schemas/universal-setting.schema';
 
@Injectable()
export class SettingsService {
  constructor(
    @InjectModel(UniversalSetting.name)
    private readonly settingModel: Model<UniversalSetting>,
  ) {}
 
  async set(params: {
    tenantId?: string;
    scope: 'SYSTEM' | 'TENANT' | 'USER' | 'MODULE';
    scopeId?: string;
    key: string;
    value: any;
  }) {
    const filter = {
      tenantId: params.tenantId || 'SYSTEM',
      scope: params.scope,
      scopeId: params.scopeId || '',
      key: params.key,
    };
 
    return this.settingModel
      .findOneAndUpdate(
        filter,
        { ...filter, value: params.value },
        { upsert: true, new: true },
      )
      .lean()
      .exec();
  }
 
  async get(params: {
    tenantId: string;
    userId?: string;
    key: string;
    moduleKey?: string;
  }): Promise<any> {
    // 1. User scope
    if (params.userId) {
      const userSetting = await this.settingModel
        .findOne({
          tenantId: params.tenantId,
          scope: 'USER',
          scopeId: params.userId,
          key: params.key,
        })
        .lean()
        .exec();
      if (userSetting) return userSetting.value;
    }
 
    // 2. Module scope
    if (params.moduleKey) {
      const moduleSetting = await this.settingModel
        .findOne({
          tenantId: params.tenantId,
          scope: 'MODULE',
          scopeId: params.moduleKey,
          key: params.key,
        })
        .lean()
        .exec();
      if (moduleSetting) return moduleSetting.value;
    }
 
    // 3. Tenant scope
    const tenantSetting = await this.settingModel
      .findOne({
        tenantId: params.tenantId,
        scope: 'TENANT',
        scopeId: '',
        key: params.key,
      })
      .lean()
      .exec();
    if (tenantSetting) return tenantSetting.value;
 
    // 4. System default
    const systemSetting = await this.settingModel
      .findOne({
        tenantId: 'SYSTEM',
        scope: 'SYSTEM',
        scopeId: '',
        key: params.key,
      })
      .lean()
      .exec();
 
    return systemSetting ? systemSetting.value : null;
  }
}