Initial Commit
This commit is contained in:
82
src/services/config.ts
Normal file
82
src/services/config.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const configSchema = z.object({
|
||||
engine: z.object({
|
||||
mnemonic: z.string(),
|
||||
database: z.object({
|
||||
path: z.string().default("data/engine"),
|
||||
}),
|
||||
}),
|
||||
syncServer: z.object({
|
||||
url: z.string().default("http://localhost:3000"),
|
||||
}),
|
||||
database: z.object({
|
||||
path: z.string().default("data.db"),
|
||||
}),
|
||||
server: z.object({
|
||||
port: z.number().default(3000),
|
||||
host: z.string().default("0.0.0.0"),
|
||||
cors: z
|
||||
.object({
|
||||
origin: z.string().default("*"),
|
||||
methods: z
|
||||
.array(z.string())
|
||||
.default(["GET", "POST", "PUT", "DELETE", "OPTIONS"]),
|
||||
allowedHeaders: z
|
||||
.array(z.string())
|
||||
.default(["Content-Type", "Authorization"]),
|
||||
})
|
||||
.partial()
|
||||
.prefault({}),
|
||||
}),
|
||||
});
|
||||
|
||||
type ConfigInput = z.input<typeof configSchema>;
|
||||
type ConfigSchema = z.output<typeof configSchema>;
|
||||
|
||||
/**
|
||||
* Converts an object's keys to camelCase.
|
||||
* @param obj - The object to convert to camelCase.
|
||||
* @returns The camelCase object.
|
||||
*/
|
||||
const toCamelCaseObject = (obj: Record<string, string>): Record<string, string> => {
|
||||
return Object.fromEntries(Object.entries(obj).map(([key, value]) => {
|
||||
const camelCaseKey = key.toLowerCase().replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace("-", "").replace("_", ""));
|
||||
return [camelCaseKey, value];
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* The Config class is used to load and parse the configuration for the vending machine.
|
||||
*/
|
||||
export class Config {
|
||||
static fromEnv(): Config {
|
||||
// Parse through process.env, and convert the upperCase keys to camelCase.
|
||||
const envConfig = toCamelCaseObject(Object(process.env));
|
||||
|
||||
// Parse the environment config.
|
||||
return this.from(configSchema.parse(envConfig));
|
||||
}
|
||||
|
||||
static from(config: ConfigInput): Config {
|
||||
return new Config(configSchema.parse(config));
|
||||
}
|
||||
|
||||
public get syncServer() {
|
||||
return this.config.syncServer;
|
||||
}
|
||||
|
||||
public get engine() {
|
||||
return this.config.engine;
|
||||
}
|
||||
|
||||
public get database() {
|
||||
return this.config.database;
|
||||
}
|
||||
|
||||
public get server() {
|
||||
return this.config.server;
|
||||
}
|
||||
|
||||
private constructor(private readonly config: ConfigSchema) {}
|
||||
}
|
||||
Reference in New Issue
Block a user