Skip to content

Commit

Permalink
feat: start building config importer
Browse files Browse the repository at this point in the history
  • Loading branch information
finxol committed Dec 12, 2024
1 parent e4e3055 commit 42ef864
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/config/deno.json
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
{}
{
"imports": {
"@std/fs": "jsr:@std/fs@^1.0.6",
"@std/path": "jsr:@std/path@^1.0.8",
"@std/yaml": "jsr:@std/yaml@^1.0.5"
}
}
10 changes: 10 additions & 0 deletions packages/config/karr_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
application_name: Karr Auth

database:
name: karr_auth
user: karr_auth
password: karr_auth
host: localhost
port: 5432

foo: bar
12 changes: 12 additions & 0 deletions packages/config/src/default_config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"application_name": "Karr",
"database": {
"host": "localhost",
"port": 5432,
"username": "karr",
"password": "karr",
"database": "karr",
"user_name": "karr"
},
"admin_email": ""
}
65 changes: 65 additions & 0 deletions packages/config/src/importer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { parse } from "@std/yaml"
import { dirname, fromFileUrl, join } from "@std/path"
import { existsSync } from "@std/fs"
import { logger, toCamelCase } from "@util"

import defaultConfig from "./default_config.json" with { type: "json" }

type Config = typeof defaultConfig

function resolvePath(file: string) {
return join(dirname(fromFileUrl(import.meta.url)), file)
}

function parseFile(file: string = "../karr_config.yaml") {
const filetype = file.split(".").pop()
if (!filetype) {
throw new Error("Invalid file type")
}

switch (filetype) {
case "yaml":
case "yml":
return parse(Deno.readTextFileSync(file))
case "json":
return JSON.parse(Deno.readTextFileSync(file))
default:
throw new Error("Invalid file type")
}
}

function camelCaseify(obj: Config) {
return Object.keys(obj).reduce((acc: unknown, key: string) => {
acc[toCamelCase(key)] = obj[key]
return acc
}, {} as Config)
}

export function readConfig() {
const acceptedExtensions = ["yaml", "yml", "json"]

for (const ext of acceptedExtensions) {
const path = resolvePath(`../karr_config.${ext}`)

if (existsSync(path)) {
const userConfig = parseFile(path)

const filteredUserConfig =
(Object.keys(userConfig) as Array<keyof typeof defaultConfig>)
.filter((key) => key in defaultConfig)
.reduce((obj, key) => {
obj[key] = userConfig[key]
return obj
}, {} as typeof defaultConfig)

return camelCaseify(Object.assign(defaultConfig, filteredUserConfig))
}
}

logger.error("No configuration file found")
return camelCaseify(defaultConfig)
}

if (import.meta.main) {
logger.info("Read config", readConfig())
}

0 comments on commit 42ef864

Please sign in to comment.