import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { IDictionary, IDictionaryEmbedded } from '../models/interfaces'; import { ObjectId, Types } from 'mongoose'; import * as qs from 'qs'; import { DictionaryListDTO } from '../models/dtos/dictionary-list.dto'; import { plainToInstance } from 'class-transformer'; import { validateOrReject } from 'class-validator'; import { RestClient } from '../../../clients'; @Injectable() export class DictionaryService { //#region Private Members private readonly _client: RestClient; //#endregion //#region Constructor constructor(private readonly _configService: ConfigService) { this._client = new RestClient({ name: 'DICTIONARY_SERVICE', baseUrl: this._configService.get('EH_DICTIONARIES__REST__BASE_URL', ''), timeout: 30000, accessToken: this._configService.get('EH_DICTIONARIES__REST__ACCESS_TOKEN', ''), }); } //#endregion //#region Public APIs public async fetchActiveById(id: string | ObjectId) { return this._client.get(`/internals/v1/dictionaries/${id}`); } public async fetchActivesByIds(ids: string[] | ObjectId[]) { const requestBody = { data: { ids } }; return this._client.post(`/internals/v1/dictionaries/by-ids`, requestBody); } public async fetchActiveByKeyword(keyword: string) { return this._client.get(`/internals/v1/dictionaries/by-keyword/${keyword}`); } public async fetchActiveByOriginId(originId: string) { return this._client.get(`/internals/v1/dictionaries/by-origin/${originId}`); } public async fetchList(filters: DictionaryListDTO) { const query = qs.stringify(filters); await this._validateListDTO(filters); return this._client.get(`/internals/v1/dictionaries?${query}`); } public toEmbedded(dictionary: IDictionary): IDictionaryEmbedded { return { id: dictionary._id, originIds: dictionary.originIds, parentIds: this._extractParentIds(dictionary.parentIds), title: dictionary.title, metas: dictionary.metas, keyword: dictionary.keyword, }; } //#endregion //#region Private APIs private async _validateListDTO(filters: DictionaryListDTO) { const filtersInstance = plainToInstance(DictionaryListDTO, filters); await validateOrReject(filtersInstance); } private _extractParentIds(parentIds: Types.ObjectId[] | string[] | IDictionary[]): string[] { if (!parentIds || !parentIds.length) return []; return parentIds.map((item: Types.ObjectId | string | IDictionary) => { if (typeof item === 'string') return item; if (item instanceof Types.ObjectId) return item.toString(); return (item as IDictionary)._id.toString(); }); } //#endregion }