server/src/utilities/json.ts

50 lines
1.7 KiB
TypeScript

import * as fs from 'fs/promises'
import { appLogger } from './logger'
export async function readJsonFile<T>(filePath: string): Promise<T> {
try {
const fileContent = await fs.readFile(filePath, 'utf-8')
return JSON.parse(fileContent) as T
} catch (error) {
appLogger.error(`Error reading JSON file: ${error instanceof Error ? error.message : String(error)}`)
throw error
}
}
export async function writeJsonFile<T>(filePath: string, data: T): Promise<void> {
try {
const jsonString = JSON.stringify(data, null, 2)
await fs.writeFile(filePath, jsonString, 'utf-8')
} catch (error) {
appLogger.error(`Error writing JSON file: ${error instanceof Error ? error.message : String(error)}`)
throw error
}
}
export async function readJsonValue<T>(filePath: string, paramPath: string): Promise<T> {
try {
const jsonContent = await readJsonFile<any>(filePath)
const paramValue = paramPath.split('.').reduce((obj, key) => obj && obj[key], jsonContent)
if (paramValue === undefined) {
throw new Error(`Parameter ${paramPath} not found in the JSON file`)
}
return paramValue as T
} catch (error) {
appLogger.error(`Error reading JSON parameter: ${error instanceof Error ? error.message : String(error)}`)
throw error
}
}
export async function setJsonValue<T>(filePath: string, key: string, value: any): Promise<void> {
try {
const data = await readJsonFile<T>(filePath)
const updatedData = { ...data, [key]: value }
await writeJsonFile(filePath, updatedData)
} catch (error) {
appLogger.error(`Error setting JSON value: ${error instanceof Error ? error.message : String(error)}`)
throw error
}
}