Files
XCDesktop/api/core/settings/routes.ts

55 lines
1.5 KiB
TypeScript
Raw Normal View History

2026-03-08 01:34:54 +08:00
import express, { type Request, type Response } from 'express'
import fs from 'fs/promises'
import path from 'path'
import { asyncHandler } from '../../utils/asyncHandler.js'
import { successResponse } from '../../utils/response.js'
import { NOTEBOOK_ROOT } from '../../config/paths.js'
import type { SettingsDTO } from '../../../shared/types.js'
const router = express.Router()
const getSettingsPath = () => path.join(NOTEBOOK_ROOT, '.config', 'settings.json')
router.get(
'/',
asyncHandler(async (req: Request, res: Response) => {
const settingsPath = getSettingsPath()
try {
const content = await fs.readFile(settingsPath, 'utf-8')
const settings = JSON.parse(content)
successResponse(res, settings)
} catch (error) {
successResponse(res, {})
}
}),
)
router.post(
'/',
asyncHandler(async (req: Request, res: Response) => {
const settings = req.body as SettingsDTO
const settingsPath = getSettingsPath()
const configDir = path.dirname(settingsPath)
try {
await fs.mkdir(configDir, { recursive: true })
let existingSettings = {}
try {
const content = await fs.readFile(settingsPath, 'utf-8')
existingSettings = JSON.parse(content)
} catch {
}
const newSettings = { ...existingSettings, ...settings }
await fs.writeFile(settingsPath, JSON.stringify(newSettings, null, 2), 'utf-8')
successResponse(res, newSettings)
} catch (error) {
throw error
}
}),
)
export default router