github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/kat/src/lib/request-handlers.ts (about)

     1  // Copyright © 2021 Kaleido, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  import { NextFunction, Request, Response } from 'express';
    16  import { nanoid } from 'nanoid';
    17  import * as utils from './utils';
    18  const log = utils.getLogger('lib/request-handlers.ts');
    19  
    20  export default class RequestError extends Error {
    21  
    22    responseCode: number;
    23  
    24    constructor(message: string, responseCode = 500) {
    25      super(message);
    26      this.responseCode = responseCode;
    27    }
    28  
    29  }
    30  
    31  export const errorHandler = (err: Error, req: Request, res: Response, _next: NextFunction) => {
    32    const statusCode = err instanceof RequestError?err.responseCode : 500;
    33    log.error(`!<-- ${req.method} ${req.url} [${statusCode}]`, statusCode === 404 ? undefined : err.stack);
    34    res.status(statusCode).send({ error: err.message });
    35  };
    36  
    37  interface ATRequest extends Request {
    38    entryTime: number
    39    requestId: string
    40  }
    41  
    42  export function requestLogger(req: Request, _: Response, next: NextFunction): void {
    43    const r: ATRequest = req as ATRequest;
    44    r.entryTime = Date.now();
    45    r.requestId = nanoid(10);
    46    log.info(`[${r.requestId}] --> ${req.method} ${req.path}`);
    47    next();
    48  }
    49  
    50  export function responseLogger(req: Request, res: Response, next: NextFunction): void {
    51    const r: ATRequest = req as ATRequest;
    52    const timing = (Date.now() - r.entryTime).toFixed(1);
    53    log.info(
    54      `[${r.requestId}] <-- ${req.method} ${req.path} [${res.statusCode}] (${timing}ms)`
    55    );
    56    next();
    57  }