-
Notifications
You must be signed in to change notification settings - Fork 59
/
RuntimeConfiguration.ts
58 lines (45 loc) · 1.4 KB
/
RuntimeConfiguration.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { copyFileSync, existsSync, readFileSync } from 'node:fs'
import * as toml from 'toml'
import { Environment } from '@/config'
import { RuntimeConfigurationSchema } from './RuntimeConfigurationSchema'
export class RuntimeConfiguration {
private _data?: RuntimeConfigurationSchema
constructor(private readonly url = Environment.BOT_CONFIG) {}
async init() {
return this._data ?? (await this.reload())
}
async reload() {
this._data = RuntimeConfigurationSchema.parse(
toml.parse(await this.fetch()),
)
return this._data
}
private async fetch(): Promise<string> {
const { url } = this
// Handle local file
if (url.startsWith('file:')) {
const path = url.slice(5)
const exampleFile = 'bot-config.example.toml'
if (!existsSync(path) && existsSync(exampleFile)) {
copyFileSync(exampleFile, path)
console.info(
`[RuntimeConfiguration] Created initial configuration file: ${path}`,
)
}
return readFileSync(path, 'utf8')
}
const response = await fetch(url)
if (!response.ok) {
throw new Error(
`Unable to fetch runtime configuration: ${response.status} ${response.statusText}`,
)
}
return response.text()
}
get data(): RuntimeConfigurationSchema {
if (!this._data) {
throw new Error('Runtime configuration not initialized')
}
return this._data
}
}