Refactored config

This commit is contained in:
DarkCat09 2023-08-16 18:10:05 +04:00
parent 0750485e4b
commit 48dcd43f63
No known key found for this signature in database
GPG Key ID: 4785B6FB1C50A540
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 path from "path";
@ -19,7 +18,7 @@ import publicConfig from "./publicConfig";
import errorHandler from "./errors/handler";
class App {
config: IConfigService;
config: ConfigService;
constructor() {
this.config = new ConfigService();
@ -59,7 +58,7 @@ class App {
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);
});
}

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