this repo has no description
at main 88 lines 2.5 kB view raw
1import { readFileSync } from "node:fs"; 2import { hostname } from "node:os"; 3import { Logger } from "common"; 4import { z } from "zod"; 5 6const developerSchema = z.object({ 7 name: z.string(), 8 email: z.string().email(), 9}); 10 11const appSchema = z.object({ 12 name: z.string(), 13 prefix: z.string().optional(), 14 fullName: z.string().max(32).default(""), 15 version: z.string(), 16 description: z.string().min(10).max(100), 17 privacyPolicy: z.string().url(), 18 termsOfService: z.string().url(), 19}); 20 21const repositorySchema = z.object({ 22 url: z.string().url(), 23 branch: z.string(), 24}); 25 26const cookieSchema = z.object({ 27 secret: z.string().min(32).max(256), 28 path: z.string().default("/"), 29 httpOnly: z.boolean().default(true), 30 secure: z.boolean().default(false), 31 sameSite: z.enum(["strict", "lax", "none"]).default("strict"), 32}); 33 34const serverSchema = z.object({ 35 port: z.number().int().positive().min(1024).max(65535), 36 basePath: z.string().default("/"), 37 secure: z.boolean().default(false), 38 hostName: z.string().default(hostname()), 39}); 40 41const dbSchema = z.object({ 42 path: z.string().min(1).max(256), 43}); 44 45const configSchema = z.object({ 46 app: appSchema, 47 developer: developerSchema, 48 repository: repositorySchema, 49 cookie: cookieSchema, 50 server: serverSchema, 51 db: dbSchema, 52}); 53 54export type Config = z.infer<typeof configSchema>; 55 56const loadConfig = (filePath = "./../../config.json"): Config => { 57 const configLogger = new Logger("config"); 58 59 try { 60 const configFile = readFileSync(filePath, "utf8"); 61 const config: Config = configSchema.parse(JSON.parse(configFile)); 62 if (config.app.fullName === "") { 63 if (!config.app.prefix) config.app.fullName = config.app.name; 64 else config.app.fullName = `${config.app.prefix} ${config.app.name}`; 65 } 66 configLogger.info("configuration loaded successfully"); 67 return config; 68 } catch (error) { 69 if (error instanceof z.ZodError) { 70 configLogger.error("invalid configuration"); 71 for (const issue of error.issues) { 72 if (issue.code === z.ZodIssueCode.invalid_type) { 73 configLogger.error( 74 `- ${issue.path.join(".")}: expected ${issue.expected}, received ${issue.received}`, 75 ); 76 } else { 77 configLogger.error(`- ${issue.path.join(".")}: ${issue.message}`); 78 } 79 } 80 } else { 81 configLogger.error("error loading configuration:", error); 82 } 83 process.exit(1); 84 } 85}; 86 87const config = loadConfig(); 88export default config;