express-service-bootstrap
Version:
This is a convenience package for starting a express API with security, health checks, process exits etc.
179 lines • 9.51 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Convenience = void 0;
const bootstrap_constructor_1 = require("./bootstrap-constructor");
const helmet_1 = __importDefault(require("helmet"));
const express_1 = __importStar(require("express"));
const swaggerUi = __importStar(require("swagger-ui-express"));
const compression_1 = __importDefault(require("compression"));
/**
* A convenience class that provides a way to create middleware instances without the need to manually create them.
*/
class Convenience {
/**
* Creates a new instance of the convenience class.
* @param DIConstructor The dependency injection constructor to use to create instances of middleware.
*/
constructor(customConstructor = new bootstrap_constructor_1.BootstrapConstructor()) {
this.customConstructor = customConstructor;
}
/**
* Creates a new instance of the body parser middleware for url encoding.
* @param urlEncodingOptions The options to use for the url encoding middleware.
* @param urlEncodingOptions.extended Whether to use the extended query string parsing. Default is true.
* @param urlEncodingOptions.limit The maximum size of the url encoded payload to parse. Can be a string (e.g., "1mb") or a number (in bytes). Default is '100kb'.
* @param urlEncodingOptions.parameterLimit The maximum number of parameters to parse in the url encoded payload. Default is 1000.
* @returns {ApplicationBuilderMiddleware} A new instance of the body parser middleware for url encoding.
*/
bodyParserURLEncodingMiddleware(urlEncodingOptions = { extended: true }) {
return this.customConstructor.createInstanceWithoutConstructor(express_1.default.urlencoded, [urlEncodingOptions]);
}
/**
* Creates a new instance of the body parser middleware for JSON encoding.
* @param jsonOptions The options to use for the JSON encoding middleware.
* @param jsonOptions.limit The maximum size of the JSON payload to parse. Can be a string (e.g., "1mb") or a number (in bytes). Default is '1mb'.
* @param jsonOptions.strict If true, only objects and arrays will be parsed. Default is true.
* @param jsonOptions.type The media type(s) to parse. Can be a string, an array of strings, or a function that returns a boolean. Default is 'application/json'.
* @returns {ApplicationBuilderMiddleware} A new instance of the body parser middleware for JSON encoding.
*/
bodyParserJSONEncodingMiddleware(jsonOptions = { limit: '1mb' }) {
return this.customConstructor.createInstanceWithoutConstructor(express_1.default.json, [jsonOptions]);
}
/**
* Creates a new instance of the body parser middleware for raw encoding.
* @param helmetOptions The options to use for the raw encoding middleware.
* @returns {ApplicationBuilderMiddleware} A new instance of the helmet middleware.
*/
helmetMiddleware(helmetOptions) {
return this.customConstructor.createInstanceWithoutConstructor(helmet_1.default, [helmetOptions]);
}
/**
* Creates a new instance of the swagger API documentation middleware.
* @param swaggerDocument The swagger document to use for the API documentation, typically a json object.
* @param hostPath The host path to use for the swagger API documentation.
* @returns {ApplicationRouter} A new instance of the swagger API documentation middleware.
*/
swaggerAPIDocs(swaggerDocument, hostPath = '/api-docs') {
const swaggerRouter = this.customConstructor.createInstanceWithoutConstructor(express_1.Router);
swaggerRouter.use(swaggerUi.serve, swaggerUi.setup(swaggerDocument));
return { hostingPath: hostPath, router: swaggerRouter };
}
/**
* Injects a specified object into the request under a given property name.
* @param requestPropertyName - The name of the property to add to the request object.
* @param object - The object to inject into the request.
* @returns {ApplicationBuilderMiddleware} A middleware function that injects the object into the request.
*/
injectInRequestMiddleware(requestPropertyName, object) {
const middleware = (req, res, next) => {
req[requestPropertyName] = object;
next();
};
return this.customConstructor.createInstanceWithoutConstructor(() => middleware);
}
/**
* Creates a new instance of the compression middleware.
* @param compressionOptions The options to use for the compression middleware.
* @returns {ApplicationBuilderMiddleware} A new instance of the compression middleware.
*/
compressionMiddleware(compressionOptions) {
return this.customConstructor.createInstanceWithoutConstructor((options) => (0, compression_1.default)(options), [compressionOptions]);
}
/**
* Creates a new instance of the static file serving middleware.
* @param staticPath The path to the static files to serve.
* @returns {ApplicationBuilderMiddleware} A new instance of the static file serving middleware.
*/
staticMiddleware(staticPath) {
return this.customConstructor.createInstanceWithoutConstructor(express_1.static, [staticPath]);
}
/**
* Encodes a string payload into a ReadableStream.
* @param payload The string payload to encode.
* @returns An object containing the ReadableStream and the size of the encoded payload.
*/
encodeBodyStream(payload) {
const encoder = new TextEncoder();
const encodedPayload = encoder.encode(payload);
return {
stream: new ReadableStream({
start(controller) {
controller.enqueue(encodedPayload);
controller.close();
}
}),
size: encodedPayload.length
};
}
/**
* Sends an HTTP request with GZIP compression if specified.
* @param httpVerb "GET", "POST", "PUT", "DELETE", etc.
* @param url The URL to send the request to.
* @param headers The headers to include in the request.
* @param bodyStream The body stream to send with the request, Default undefined.
* @param shouldCompress Whether to compress the request body using GZIP. Default is true when body is present.
* @returns A promise that resolves to the response of the HTTP request.
*/
compressibleRequestGZIP(httpVerb_1, url_1, headers_1) {
return __awaiter(this, arguments, void 0, function* (httpVerb, url, headers, bodyStream = undefined, shouldCompress = bodyStream !== undefined, context = globalThis) {
const fetchOptions = {
method: httpVerb,
headers: headers,
body: bodyStream
};
fetchOptions.duplex = "half"; //For some odd reason TypesDef RequestInit type does not include duplex yet.
if (shouldCompress === true && bodyStream !== undefined) {
headers["content-encoding"] = "gzip";
fetchOptions.body = bodyStream.pipeThrough(new context.CompressionStream("gzip"));
}
return context.fetch(url, fetchOptions);
});
}
}
exports.Convenience = Convenience;
//# sourceMappingURL=convenience.js.map