Skip to content

Commit

Permalink
chore(skeleton): obtaining and customizing application config
Browse files Browse the repository at this point in the history
  • Loading branch information
hywax committed Dec 28, 2023
1 parent d4f6a98 commit 644f690
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
56 changes: 56 additions & 0 deletions server/utils/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import fs from 'node:fs'
import crypto from 'node:crypto'
import yaml from 'yaml'
import type { BaseService, Config } from '~/types'

export function getLocalConfig(): Config | null {
try {
if (!fs.existsSync('assets/config.yaml')) {
return null
}

const config = yaml.parse(fs.readFileSync('assets/config.yaml', 'utf8')) || {}
const services = Object
.entries<Omit<BaseService, 'id'>[]>((config.services || []))
.reduce<Config['services']>((acc, [title, items]) => {
acc.push({
title,
items: items.map((item) => ({ ...item, id: crypto.randomUUID() })),
})

return acc
}, [])

return {
...config,
services,
}
} catch (e) {
// ...
}

return null
}

/**
* Safely retrieves a list of services for frontend.
* Omit "secrets" fields.
*/
export function extractSafelyConfig(config: Config) {
return JSON.parse(JSON.stringify(
config, (key, val) => key === 'secrets' ? undefined : val,
))
}

/**
* Create Map services
*/
export function extractServicesFromConfig(config: Config): Record<string, BaseService> {
return config.services.reduce<Record<string, BaseService>>((acc, group) => {
for (const item of group.items) {
acc[item.id] = item
}

return acc
}, {})
}
24 changes: 24 additions & 0 deletions server/utils/services.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { H3Event } from 'h3'

export async function getService<T>(event: H3Event): Promise<T> {
const { id } = getQuery<{ id?: string }>(event)

if (!id) {
throw createError({
statusCode: 400,
statusMessage: 'ID can not be null',
})
}

const storage = useStorage()
const services = await storage.getItem<Record<string, T>>('services')

if (!services || !Object.hasOwn(services, id)) {
throw createError({
statusCode: 404,
statusMessage: `Service with ID "${id}" does not exist`,
})
}

return services[id]
}

0 comments on commit 644f690

Please sign in to comment.