import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { Logger } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { SystemSettingHashValueTypeEnum, SystemSettingsQueryOutput, SystemSettingsQueryOutputError, UpdateSystemSettingInput, UpdateSystemSettingOutput, UpdateSystemSettingOutputError } from '../__generated__/graphql'; import { normalizePairs } from '../utils'; const getUrn = (hashKey: string): string => `urn:system-settings:${hashKey}`; const parseUrn = (urn: string): string => urn.split(':').pop(); @Resolver('SystemSettings') export class SystemSettingsResolver { private readonly logger: Logger = new Logger(SystemSettingsResolver.name); constructor( private readonly prismaService: PrismaService, ) {} @Query() async systemSettings(): Promise { try { const systemSettingsPairs = await this.prismaService.systemSetting.findMany(); const systemSettingsHashSet = normalizePairs(systemSettingsPairs); return { data: Object.keys(systemSettingsHashSet).map(hashKey => ({ urn: getUrn(hashKey), hashKey, hashValue: systemSettingsHashSet[hashKey].toString(), hashValueType: this.determineHashValueType(systemSettingsHashSet[hashKey]), })), } } catch (e) { this.logger.error(e.message); return { error: SystemSettingsQueryOutputError.Unknown, } } } @Mutation() async updateSystemSetting( @Args('input') { urn, hashValue }: UpdateSystemSettingInput ): Promise { try { const hashKey = parseUrn(urn); const existing = await this.prismaService.systemSetting.findUnique({ where: { hashKey } }); if (!existing) { return { error: UpdateSystemSettingOutputError.NotFound, } } await this.prismaService.systemSetting.update({ data: { hashValue }, where: { hashKey }, }); return {}; } catch (e) { this.logger.error(e.message); return { error: UpdateSystemSettingOutputError.Unknown, } } } private determineHashValueType = (hashValue: string | number | boolean): SystemSettingHashValueTypeEnum => { if (typeof hashValue === 'number') { return SystemSettingHashValueTypeEnum.Number; } if (typeof hashValue === 'boolean') { return SystemSettingHashValueTypeEnum.Boolean; } return SystemSettingHashValueTypeEnum.String; } }