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 { 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);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,3 +0,0 @@
|
|||||||
export interface IConfigService {
|
|
||||||
get(key: string): string;
|
|
||||||
}
|
|
@ -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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user