Add data validation to the config

This commit is contained in:
Oliver Akins 2022-06-23 11:40:09 -06:00
parent 4506b97101
commit be25b95789
No known key found for this signature in database
GPG key ID: 3C2014AF9457AF99
2 changed files with 68 additions and 10 deletions

View file

@ -2,19 +2,11 @@
import "module-alias/register";
import startWebsocketServer from "./websocket";
import { loadConfig } from "./utils/config";
import { GameDB } from "./objects/GameDB";
import { Logger } from "tslog";
import toml from "toml";
import fs from "fs";
// load the config
try {
var configData = toml.parse(fs.readFileSync("config.toml", "utf-8"));
} catch {
console.error("Can't find config file. Exiting");
process.exit(1);
};
export const config: IConfig = configData;
export const config: IConfig = loadConfig();
// Define the logger
export const log = new Logger({

View file

@ -0,0 +1,66 @@
import { readFileSync } from "fs";
import { log } from "@/main";
import toml from "toml";
import Joi from "joi";
const schema = Joi.object({
game: Joi.object({
type: Joi
.string()
.allow(
`file:json`,
// `file:csv`,
// `web:json`,
// `web:csv`
)
.required()
.message(`Invalid deck type`),
location: Joi
.string()
.required()
.message(`The deck location must be a string`),
}),
server: Joi.object({
port: Joi
.number()
.port()
.required()
.message(`Invalid port number`),
cors: Joi.object({
origins: Joi
.array()
.items(Joi.string())
.message(`The CORS origins must be an array of strings`),
}),
}),
log: Joi.object({
level: Joi
.string()
.allow(
`silly`,
`trace`,
`debug`,
`info`,
`warn`,
`error`,
`fatal`
)
.optional()
.default(`info`)
.message(`Invalid log level`),
}),
});
export function loadConfig(): IConfig {
const data = toml.parse(readFileSync("config.toml", "utf-8"));
const { value, error } = schema.validate(data, {
abortEarly: false,
});
if (error) {
log.error(`Configuration object failed to validate`)
log.error(error);
process.exit(1);
};
return value;
};