@mdf.js/service-registry
Version:
MMS - API - Service Registry
84 lines • 3.04 kB
JavaScript
;
/**
* Copyright 2024 Mytra Control S.L. All rights reserved.
*
* Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
* or at https://opensource.org/licenses/MIT.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Controller = void 0;
const tslib_1 = require("tslib");
const crash_1 = require("@mdf.js/crash");
const utils_1 = require("@mdf.js/utils");
const cluster_1 = tslib_1.__importDefault(require("cluster"));
const TEXT_CONTENT_TYPE = 'text/plain';
const JSON_CONTENT_TYPE = 'application/json';
/** Controller class */
class Controller {
/**
* Create an instance of Controller class
* @param service - service instance
* @param isCluster - indicates that the instance of this metrics service is running in a cluster
*/
constructor(service, isCluster) {
this.service = service;
this.isCluster = isCluster;
}
/**
* Return all the actual metrics of this artifact
* @param request - HTTP request express object
* @param response - HTTP response express object
* @param next - Next express middleware function
*/
metrics(request, response, next) {
const requestCheck = this.isAcceptable(request);
if (!requestCheck.acceptable) {
next(crash_1.BoomHelpers.notAcceptable('Not valid formats for metrics endpoint are aceptable by the client', request.uuid, {
source: {
pointer: request.path,
parameter: { body: request.body, query: request.query },
},
}));
}
else {
this.service
.metrics(requestCheck.jsonFormat)
.then(result => {
response.set('Content-type', result.contentType);
response.status(200).send(result.metrics);
})
.catch(next);
}
}
/**
* Check if the request is acceptable due to the format
* @param request - HTTP request express object
*/
isAcceptable(request) {
let jsonFormat = (0, utils_1.coerce)(request.query['json'], false);
let acceptable = true;
if (this.isCluster && cluster_1.default.isPrimary) {
jsonFormat = false;
if (!request.accepts(TEXT_CONTENT_TYPE)) {
acceptable = false;
}
}
else {
if (jsonFormat && request.accepts(JSON_CONTENT_TYPE)) {
jsonFormat = true;
}
else if (request.accepts(TEXT_CONTENT_TYPE)) {
jsonFormat = false;
}
else if (request.accepts(JSON_CONTENT_TYPE)) {
jsonFormat = true;
}
if (!request.accepts([TEXT_CONTENT_TYPE, JSON_CONTENT_TYPE])) {
acceptable = false;
}
}
return { acceptable, jsonFormat };
}
}
exports.Controller = Controller;
//# sourceMappingURL=metrics.controller.js.map