import { Injectable } from "@nestjs/common" ; import { InjectModel } from "@nestjs/mongoose" ; import { MongooseService , ResultList } from "nestx-common" ; import { SettingModel } from "./../interfaces" ; import { SettingsGroup , SettingRes } from "./../dto" ; import { Model } from "mongoose" ; @ Injectable ( ) export class SettingsService extends MongooseService < SettingModel > { defaultQueryFields = [ "name" , "key" , "value" , "description" ] ; constructor ( @ InjectModel ( "Setting" ) protected readonly model ) { super ( model ) ; } async querySearch ( keyword , page , size , sort ) { return super . query ( page , size , { } , { keyword , field : "name" } , this . defaultQueryFields , sort ) ; } async getSettingsByName ( name ? ) { const result = new SettingsGroup ( ) ; result . options = { } ; if ( name ) { const docs = await this . model . find ( { name : name } ) . exec ( ) ; if ( docs ) { docs . forEach ( doc => { result . options [ doc . key ] = doc . value ; } ) ; } } return result ; } async getSettingsByKey ( name ) { const setting = await this . model . findOne ( { key : name } ) . exec ( ) ; return setting ; } async updateSettingsByName ( name , entry ) { entry . options = entry . options || { } ; const keys = Object . keys ( entry . options ) ; for ( let key of keys ) { const instance = { key : key , value : entry . options [ key ] } ; await this . model . findOneAndUpdate ( { key : key , name : name } , { $set : instance } , { upsert : true , new : true } ) . exec ( ) ; } return this . getSettingsByName ( name ) ; } }