deduplicate json config file access

This commit is contained in:
yml
2026-05-21 18:54:41 +08:00
parent 17a615b8de
commit 589de4b50b
6 changed files with 79 additions and 86 deletions
@@ -1,7 +1,7 @@
import fs from 'node:fs'
import path from 'node:path'
import { PROJECT_ROOT } from '../../config/runtime.js'
import { readJsonFile, writeJsonFile } from '../../utils/json-file-store.js'
const NOTIFICATION_CONFIG_FILE_PATH = path.join(PROJECT_ROOT, 'data', 'notification-config.json')
const DEFAULT_BARK_SERVER_URL = 'https://api.day.app'
@@ -17,10 +17,7 @@ export function getNotificationConfig() {
}
export function saveNotificationConfig(rawValue: unknown) {
const normalized = normalizeNotificationConfig(rawValue)
fs.mkdirSync(path.dirname(NOTIFICATION_CONFIG_FILE_PATH), { recursive: true })
fs.writeFileSync(NOTIFICATION_CONFIG_FILE_PATH, `${JSON.stringify(normalized, null, 2)}\n`, 'utf8')
return normalized
return writeJsonFile(NOTIFICATION_CONFIG_FILE_PATH, rawValue, normalizeNotificationConfig)
}
export function listEnabledBarkRecipients(config: JsonObject = getNotificationConfig()) {
@@ -33,16 +30,11 @@ export function listEnabledBarkRecipients(config: JsonObject = getNotificationCo
}
function loadNotificationConfigFromFile() {
if (!fs.existsSync(NOTIFICATION_CONFIG_FILE_PATH)) {
return createDefaultNotificationConfig()
}
try {
const rawText = fs.readFileSync(NOTIFICATION_CONFIG_FILE_PATH, 'utf8')
return normalizeNotificationConfig(JSON.parse(rawText))
} catch {
return createDefaultNotificationConfig()
}
return readJsonFile(
NOTIFICATION_CONFIG_FILE_PATH,
createDefaultNotificationConfig,
normalizeNotificationConfig,
)
}
function normalizeNotificationConfig(rawValue: unknown) {