Files
code-server/src/node/settings.ts
T

56 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

2020-08-04 15:51:39 -05:00
import { logger } from "@coder/logger"
2020-10-20 18:05:58 -05:00
import { Query } from "express-serve-static-core"
2021-03-15 16:15:24 -05:00
import { promises as fs } from "fs"
2020-02-04 13:27:46 -06:00
export type Settings = { [key: string]: Settings | string | boolean | number }
/**
* Provides read and write access to settings.
*/
export class SettingsProvider<T> {
public constructor(private readonly settingsPath: string) {}
/**
* Read settings from the file. On a failure return last known settings and
* log a warning.
*/
public async read(): Promise<T> {
try {
const raw = (await fs.readFile(this.settingsPath, "utf8")).trim()
return raw ? JSON.parse(raw) : {}
} catch (error: any) {
2020-02-04 13:27:46 -06:00
if (error.code !== "ENOENT") {
logger.warn(error.message)
}
}
return {} as T
}
/**
* Write settings combined with current settings. On failure log a warning.
2020-08-04 15:12:15 -05:00
* Settings will be merged shallowly.
2020-02-04 13:27:46 -06:00
*/
2020-08-04 15:12:15 -05:00
public async write(settings: Partial<T>): Promise<void> {
2020-02-04 13:27:46 -06:00
try {
const oldSettings = await this.read()
2020-08-04 15:12:15 -05:00
const nextSettings = { ...oldSettings, ...settings }
await fs.writeFile(this.settingsPath, JSON.stringify(nextSettings, null, 2))
} catch (error: any) {
2020-02-04 13:27:46 -06:00
logger.warn(error.message)
}
}
}
2020-02-14 16:41:42 -06:00
export interface UpdateSettings {
2020-02-14 16:41:42 -06:00
update: {
checked: number
version: string
}
}
/**
* Global code-server settings.
*/
export interface CoderSettings extends UpdateSettings {
2021-12-17 13:06:52 -06:00
query?: Query
}