Last active
March 5, 2020 15:57
-
-
Save gabrielsaints/de775ab8534612a39663813278bbe757 to your computer and use it in GitHub Desktop.
ts-api credentials
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Server from "express"; | |
import bodyParser from "body-parser"; | |
import cors from "cors"; | |
import http, { HttpBase } from "http"; | |
import https from "https"; | |
import { readFileSync } from "fs"; | |
import errors from "./middlewares/error"; | |
import secured from "./middlewares/secured"; | |
import checkoutRoutes from "./routes/checkout"; | |
interface AppCredentials { | |
keyPath: string; | |
certPath: string; | |
caPath?: string; | |
} | |
class App { | |
private server: Server.Express; | |
private credentials: https.ServerOptions | null; | |
private unprotectedServer: http.Server | null; | |
private protectedServer: https.Server | null; | |
constructor() { | |
this.server = Server(); | |
this.unprotectedServer = null; | |
this.protectedServer = null; | |
this.credentials = null; | |
} | |
private middlewares(): void { | |
this.server.use(cors()); | |
this.server.use(bodyParser.urlencoded({ extended: true })); | |
this.server.use(bodyParser.json()); | |
} | |
private routes(): void { | |
this.server.use(checkoutRoutes); | |
} | |
private listeners(): void { | |
this.server.use(errors.notFound); | |
this.server.use(errors.exception); | |
} | |
private createCredentials({ | |
keyPath, | |
certPath, | |
caPath | |
}: AppCredentials): void { | |
const key = readFileSync(keyPath); | |
const cert = readFileSync(certPath); | |
this.credentials = { | |
cert, | |
key | |
}; | |
if (caPath) { | |
const ca = readFileSync(caPath); | |
this.credentials.ca = ca; | |
} | |
} | |
public listen( | |
port: number, | |
portSSL?: number, | |
credentials?: AppCredentials | |
): void { | |
if (credentials) { | |
this.createCredentials(credentials); | |
this.server.use(secured); | |
this.protectedServer = https.createServer(this.credentials!, this.server); | |
this.protectedServer?.listen(portSSL); | |
} | |
this.unprotectedServer = http.createServer(this.server); | |
this.middlewares(); | |
this.routes(); | |
this.listeners(); | |
this.unprotectedServer.listen(port); | |
} | |
} | |
export default new App(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment