Merge pull request #19 from TxtDot/refactor-config

Refactored config
This commit is contained in:
Artemy Egorov 2023-08-16 17:44:06 +03:00 committed by GitHub
commit 27484be9c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 11 additions and 27 deletions

View File

@ -1 +1,2 @@
PORT=80 HOST=127.0.0.1 # set 0.0.0.0 if you don't use reverse proxy
PORT=8080

View File

@ -1,4 +1,3 @@
import { IConfigService } from "./config/config.interface";
import { ConfigService } from "./config/config.service"; import { ConfigService } from "./config/config.service";
import path from "path"; import path from "path";
@ -19,7 +18,7 @@ import publicConfig from "./publicConfig";
import errorHandler from "./errors/handler"; import errorHandler from "./errors/handler";
class App { class App {
config: IConfigService; config: ConfigService;
constructor() { constructor() {
this.config = new ConfigService(); this.config = new ConfigService();
@ -59,7 +58,7 @@ class App {
fastify.setErrorHandler(errorHandler); fastify.setErrorHandler(errorHandler);
fastify.listen({ port: Number(this.config.get("PORT")) }, (err) => { fastify.listen({ host: this.config.host, port: this.config.port }, (err) => {
err && console.log(err); err && console.log(err);
}); });
} }

View File

@ -1,3 +0,0 @@
export interface IConfigService {
get(key: string): string;
}

View File

@ -1,30 +1,17 @@
import { config, DotenvParseOutput } from "dotenv"; import { config } from "dotenv";
import { IConfigService } from "./config.interface";
export class ConfigService implements IConfigService { export class ConfigService {
private config: DotenvParseOutput; public readonly host: string;
public readonly port: number;
constructor() { constructor() {
const { error, parsed } = config(); const parsed = config().parsed;
if (error) {
throw new Error(".env file not found");
}
if (!parsed) { if (!parsed) {
throw new Error("Invalid .env file"); throw new Error("Invalid .env file");
} }
this.config = parsed; this.host = process.env.HOST || 'localhost';
} this.port = Number(process.env.PORT) || 8080;
get(key: string): string {
const res = this.config[key];
if (!res) {
throw new Error(`Key ${key} not found`);
}
return res;
} }
} }