Skip to content

Commit 644f690

Browse files
committed
chore(skeleton): obtaining and customizing application config
1 parent d4f6a98 commit 644f690

2 files changed

Lines changed: 80 additions & 0 deletions

File tree

server/utils/config.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import fs from 'node:fs'
2+
import crypto from 'node:crypto'
3+
import yaml from 'yaml'
4+
import type { BaseService, Config } from '~/types'
5+
6+
export function getLocalConfig(): Config | null {
7+
try {
8+
if (!fs.existsSync('assets/config.yaml')) {
9+
return null
10+
}
11+
12+
const config = yaml.parse(fs.readFileSync('assets/config.yaml', 'utf8')) || {}
13+
const services = Object
14+
.entries<Omit<BaseService, 'id'>[]>((config.services || []))
15+
.reduce<Config['services']>((acc, [title, items]) => {
16+
acc.push({
17+
title,
18+
items: items.map((item) => ({ ...item, id: crypto.randomUUID() })),
19+
})
20+
21+
return acc
22+
}, [])
23+
24+
return {
25+
...config,
26+
services,
27+
}
28+
} catch (e) {
29+
// ...
30+
}
31+
32+
return null
33+
}
34+
35+
/**
36+
* Safely retrieves a list of services for frontend.
37+
* Omit "secrets" fields.
38+
*/
39+
export function extractSafelyConfig(config: Config) {
40+
return JSON.parse(JSON.stringify(
41+
config, (key, val) => key === 'secrets' ? undefined : val,
42+
))
43+
}
44+
45+
/**
46+
* Create Map services
47+
*/
48+
export function extractServicesFromConfig(config: Config): Record<string, BaseService> {
49+
return config.services.reduce<Record<string, BaseService>>((acc, group) => {
50+
for (const item of group.items) {
51+
acc[item.id] = item
52+
}
53+
54+
return acc
55+
}, {})
56+
}

server/utils/services.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import type { H3Event } from 'h3'
2+
3+
export async function getService<T>(event: H3Event): Promise<T> {
4+
const { id } = getQuery<{ id?: string }>(event)
5+
6+
if (!id) {
7+
throw createError({
8+
statusCode: 400,
9+
statusMessage: 'ID can not be null',
10+
})
11+
}
12+
13+
const storage = useStorage()
14+
const services = await storage.getItem<Record<string, T>>('services')
15+
16+
if (!services || !Object.hasOwn(services, id)) {
17+
throw createError({
18+
statusCode: 404,
19+
statusMessage: `Service with ID "${id}" does not exist`,
20+
})
21+
}
22+
23+
return services[id]
24+
}

0 commit comments

Comments
 (0)