Refactored config
This commit is contained in:
parent
0750485e4b
commit
48dcd43f63
@ -1 +1,2 @@
|
||||
PORT=80
|
||||
HOST=127.0.0.1 # set 0.0.0.0 if you don't use reverse proxy
|
||||
PORT=8080
|
||||
|
@ -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);
|
||||
});
|
||||
}
|
||||
|
@ -1,3 +0,0 @@
|
||||
export interface IConfigService {
|
||||
get(key: string): string;
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user