/************************************************************************* * * Troven CONFIDENTIAL * __________________ * * (c) 2017-2020 Troven Ventures Pty Ltd * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Troven Pty Ltd and its licensors, * if any. The intellectual and technical concepts contained * herein are proprietary to Troven Pty Ltd * and its suppliers and may be covered by International and Regional Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Troven Pty Ltd. */ import { IOperation, IChassisMiddleware } from "../interfaces"; import * as os from "os"; import { Utils } from "../helpers"; /** * Request UUID * ------------ * Feature generates a UUIDv5 and inject into x-request-id header * * @type {{name: string, title: string, description: string, options: {header: string}, fn: module.exports.fn}} */ export default class request_uuid implements IChassisMiddleware { name = "api.request_uuid"; title = "Inject a 'x-request-id' into request and response headers"; public options = { header: "X-REQUEST-IDd", }; header = function () { return this.options.header; }; fn(operation: IOperation, options: any): Function { let context = operation.context; let seed = os.hostname() + Date.now(); return function (req, res, next) { let ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; let request_uuid = Utils.uuid(seed + ip); // inject a header into both request & response req.header(this.options.header, request_uuid); res.header(this.options.header, request_uuid); // auditing - defaults to true if (!(options.audit === false)) { context.audit({ uuid: context.uuid, request_id: request_uuid, code: "api:request_id", message: req.method + " " + req.path, }); } req.a6s_uuid = request_uuid; // continue processing request ... next(); }; } }