import { HttpException, Injectable, InternalServerErrorException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import axios from 'axios'; import { createId } from '@paralleldrive/cuid2'; import { omit, omitBy, keys, pick } from 'lodash'; import { AddFieldTranslationDto } from './dto/add-field-translation.dto'; import { GetMediaDto } from './dto/get-media.dto'; @Injectable() export class CommonService { private readonly commonApiUrl: string; constructor(private configService: ConfigService) { this.commonApiUrl = this.configService.get('COMMON_API_URL'); } handleAxiosError(err) { if (err.response) { throw new HttpException(err.response.data, err.response.status); } else if (err.request) { throw new HttpException(err.request, 500); } else { throw new InternalServerErrorException(err.message); } } async addActivityHistory(record, entity, method) { const activity = method === 'create' ? 'Insert new' : method === 'update' ? 'Update' : 'Delete'; const filteredRecord = omit(record.EntityValueAfter, [ 'CreatedById', 'CreatedAt', 'UpdatedById', 'UpdatedAt', ]); const filteredRecordBefore = pick( record.EntityValueBefore, keys(filteredRecord), ); const payload = { Action: record.Action || (method === 'create' ? 'Insert' : activity), Activity: record.Activity || `${activity} ${entity}`, Description: record.Description || `${activity} details of ${entity}`, EntityType: record?.EntityType || entity, EntityValueBefore: method === 'create' ? JSON.stringify({}) : method === 'update' ? filteredRecordBefore : record.EntityValueBefore, EntityValueAfter: JSON.stringify(filteredRecord), PerformedById: record.PerformedById, PerformedAt: record.PerformedAt || Date.now(), EntityId: record.EntityId ? record.EntityId : createId(), }; try { const { data } = await axios.post( `${this.commonApiUrl}/activity-histories`, payload, ); return data.EntityId; } catch (err) { this.handleAxiosError(err); } } async getList(listName: string): Promise<[]> { try { const { data } = await axios.get(`${this.commonApiUrl}/lists/items`, { params: { ListName: listName }, }); return data?.rows; } catch (err) { this.handleAxiosError(err); } } async addFieldTranslation(payload: AddFieldTranslationDto) { try { await axios.post(`${this.commonApiUrl}/field-translations`, payload); } catch (err) { this.handleAxiosError(err); } } async getMedia(query: GetMediaDto) { try { const { data } = await axios.get(`${this.commonApiUrl}/medias`, { params: query, }); return data?.rows; } catch (err) { this.handleAxiosError(err); } } }