nest-local-https-proxy
Version:
A simple library to add HTTPS support to your HTTP NestJS application for local develoment, debugging, and testing.
53 lines • 2.3 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalHttpsProxy = void 0;
const https = require("https");
const events_1 = require("events");
class LocalHttpsProxy extends events_1.EventEmitter {
constructor(nestApp, httpsOptions, errorCallback, listeningCallback) {
super();
if (!httpsOptions || !httpsOptions.cert || !httpsOptions.key)
throw new Error('Invalid httpsOptions provided');
this.httpsProxyServer = this.initHttpsServer(httpsOptions, nestApp);
if (errorCallback && errorCallback instanceof Function)
this.on('error', errorCallback);
if (listeningCallback && listeningCallback instanceof Function)
this.on('listening', listeningCallback);
}
start(listeningPort) {
if (!this.httpsProxyServer?.listening) {
this.httpsProxyServer.listen(listeningPort);
}
else if (this.httpsProxyServer.listening) {
const address = this.httpsProxyServer.address();
this.onError(new Error(`Unable to start ${LocalHttpsProxy.name} on port ${listeningPort} because it is already listening on port ${address.port}`));
}
}
close() {
if (this.httpsProxyServer?.listening)
this.httpsProxyServer.closeAllConnections();
}
initHttpsServer(httpsOptions, nestApp) {
const requestListener = this.getNestAppRequestListener(nestApp);
const httpsServer = https.createServer(httpsOptions, requestListener);
httpsServer.on('error', (error) => this.onError(error));
httpsServer.on('listening', () => this.onListening());
return httpsServer;
}
getNestAppRequestListener(nestApp) {
const adapter = nestApp.getHttpAdapter();
const listener = adapter?.getInstance()?.routing ?? adapter?.getInstance();
if (!listener)
throw new Error('Failed to derive HTTP server requestListener from Nest application');
return listener;
}
onError(error) {
this.emit('error', error);
}
onListening() {
const address = this.httpsProxyServer?.address();
this.emit('listening', address?.port);
}
}
exports.LocalHttpsProxy = LocalHttpsProxy;
//# sourceMappingURL=local-https-proxy.js.map
;