redis-smq-rest-api
Version:
REST API for RedisSMQ: OpenAPI 3 schema and Swagger UI for managing queues, messages, and consumers.
159 lines • 7.97 kB
JavaScript
"use strict";
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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__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.RedisSMQRestApi = void 0;
const bodyparser_1 = require("@koa/bodyparser");
const cors_1 = __importDefault(require("@koa/cors"));
const awilix_1 = require("awilix");
const bluebird_1 = __importDefault(require("bluebird"));
const http = __importStar(require("http"));
const koa_1 = __importDefault(require("koa"));
const koa_mount_1 = __importDefault(require("koa-mount"));
const koa_static_1 = __importDefault(require("koa-static"));
const path_1 = require("path");
const redis_smq_1 = require("redis-smq");
const redis_smq_common_1 = require("redis-smq-common");
const swagger_ui_dist_1 = require("swagger-ui-dist");
const tmp_1 = __importDefault(require("tmp"));
const constants_js_1 = require("./config/constants.js");
const index_js_1 = require("./config/index.js");
const Container_js_1 = require("./container/Container.js");
const swagger_ui_js_1 = require("./helpers/swagger-ui.js");
const errorHandlerMiddleware_js_1 = require("./lib/errors/middlewares/errorHandlerMiddleware.js");
const builder_js_1 = require("./lib/openapi-spec/builder.js");
const index_js_2 = require("./lib/router/index.js");
const routing_js_1 = require("./router/routing.js");
const RedisSMQAsync = bluebird_1.default.promisifyAll(redis_smq_1.RedisSMQ);
const tmpAsync = bluebird_1.default.promisifyAll(tmp_1.default);
class RedisSMQRestApi {
constructor(config = {}, runHttpServer = true) {
this.bootstrapped = false;
this.app = new koa_1.default();
this.runHttpServer = runHttpServer;
this.config = (0, index_js_1.parseConfig)(config);
Container_js_1.Container.registerServices();
const container = Container_js_1.Container.getInstance();
container.register({ config: (0, awilix_1.asValue)(this.config) });
this.logger = (0, redis_smq_common_1.createLogger)(this.config.logger, 'RedisSMQRestApi');
this.httpServer = http.createServer(this.app.callback());
}
initApplicationMiddlewares() {
return __awaiter(this, void 0, void 0, function* () {
this.app.use((ctx, next) => {
ctx.scope = Container_js_1.Container.getInstance().createScope();
return next();
});
this.app.use(errorHandlerMiddleware_js_1.errorHandlerMiddleware);
this.app.use((0, bodyparser_1.bodyParser)());
this.app.use((0, cors_1.default)({
origin: '*',
}));
});
}
initOpenApi() {
return __awaiter(this, void 0, void 0, function* () {
const { basePath } = this.config.apiServer;
const openApiFilename = constants_js_1.constants.openApiDocumentFilename;
this.logger.info('Initializing OpenAPI...');
const spec = yield (0, builder_js_1.generateOpenApiDocument)(routing_js_1.routing, basePath);
const tmpDir = yield tmpAsync.dirAsync();
yield (0, builder_js_1.saveOpenApiDocument)(spec, tmpDir);
const uiAssetsFsPath = (0, swagger_ui_dist_1.getAbsoluteFSPath)();
this.app.use((0, koa_mount_1.default)((0, path_1.join)(basePath, '/swagger/ui'), (0, koa_static_1.default)(uiAssetsFsPath)));
this.app.use((0, koa_mount_1.default)((0, path_1.join)(basePath, '/swagger/assets'), (0, koa_static_1.default)(tmpDir)));
const specUrl = (0, path_1.join)(basePath, '/swagger/assets', openApiFilename);
const uiAssetsUrl = (0, path_1.join)(basePath, '/swagger/ui');
const html = (0, swagger_ui_js_1.buildSwaggerUiHtml)(specUrl, uiAssetsUrl);
this.app.use((0, koa_mount_1.default)((0, path_1.join)(basePath, '/swagger'), (ctx) => {
if (ctx.path === '/' || ctx.path === '') {
ctx.type = 'text/html; charset=utf-8';
ctx.body = html;
}
}));
});
}
initRouting() {
return __awaiter(this, void 0, void 0, function* () {
this.logger.info('Registering routes...');
const appRouter = yield (0, index_js_2.registerResources)(routing_js_1.routing);
this.app.use(appRouter.routes());
this.app.use(appRouter.allowedMethods());
});
}
bootstrap() {
return __awaiter(this, void 0, void 0, function* () {
if (this.bootstrapped)
return;
yield RedisSMQAsync.initializeAsync(this.config.redis);
yield this.initApplicationMiddlewares();
yield this.initRouting();
yield this.initOpenApi();
this.bootstrapped = true;
});
}
run() {
return __awaiter(this, void 0, void 0, function* () {
yield this.bootstrap();
if (!this.runHttpServer)
return;
const { port, basePath } = this.config.apiServer;
yield new Promise((resolve) => this.httpServer.listen(port, () => resolve()));
this.logger.info(`RedisSMQ REST API server is running on http://localhost:${port}...`);
const baseURL = `http://127.0.0.1:${port}${basePath === '/' ? '' : basePath}`;
this.logger.info(`OpenAPI specs are available at ${baseURL}/swagger/assets/${constants_js_1.constants.openApiDocumentFilename}`);
this.logger.info(`SWAGGER UI is accessible from ${baseURL}/swagger`);
});
}
getApplication() {
return __awaiter(this, void 0, void 0, function* () {
yield this.bootstrap();
return this.app.callback();
});
}
shutdown() {
return __awaiter(this, void 0, void 0, function* () {
if (this.httpServer.listening) {
yield new Promise((resolve) => this.httpServer.close(resolve));
}
yield Container_js_1.Container.getInstance().dispose();
yield RedisSMQAsync.shutdownAsync();
this.logger.info('RedisSMQ HTTP API has been shutdown.');
});
}
}
exports.RedisSMQRestApi = RedisSMQRestApi;
//# sourceMappingURL=index.js.map