From 2d51f3cff877a9b7619b06c4f83057b4f9b07933 Mon Sep 17 00:00:00 2001 From: Naseem Ullah <24660299+naseemkullah@users.noreply.github.com> Date: Fri, 22 Dec 2023 14:05:09 -0500 Subject: [PATCH] make typesafe custom level loggers great again pass in logger's generic based on value of customLevels and/or logger.customLevels option TS does not like what I did here so I added a ts-expect-error to silence it but it does work as expected, this is covered in the tests fixes #317 and supersedes https://github.com/pinojs/pino-http/pull/318 if merged --- index.d.ts | 12 ++++++++---- index.test-d.ts | 23 +++++++++++++++++------ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/index.d.ts b/index.d.ts index 57a3383..9b8c08b 100644 --- a/index.d.ts +++ b/index.d.ts @@ -12,13 +12,17 @@ import { IncomingMessage, ServerResponse } from 'http'; import pino from 'pino'; import { err, req, res, SerializedError, SerializedRequest, SerializedResponse } from 'pino-std-serializers'; -declare function PinoHttp(opts?: Options, stream?: pino.DestinationStream): HttpLogger; +declare function PinoHttp< IM = IncomingMessage, SR = ServerResponse, Opts = Options>(opts?: Opts, stream?: pino.DestinationStream): HttpLogger; declare function PinoHttp(stream?: pino.DestinationStream): HttpLogger; -export interface HttpLogger { - (req: IM, res: SR, next?: () => void): void; - logger: pino.Logger; +export interface HttpLogger> { + (req: IM, res: SR, next?: () => void): void; + logger: pino.Logger< + // this makes custom level loggers typesafe, but TS complains + // @ts-expect-error + keyof Opts["customLevels"] | keyof Opts["logger"]["customLevels"] + >; } export type ReqId = number | string | object; diff --git a/index.test-d.ts b/index.test-d.ts index 31b1bcd..2a54c1a 100644 --- a/index.test-d.ts +++ b/index.test-d.ts @@ -206,10 +206,21 @@ const httpServerListener: RequestListener = (request, response) => { response.end("Hello world"); }; -// custom levels added in the options should be available +// custom levels added in the options should be available/typesafe // on the logger returned by pino-http -pinoHttp({ - customLevels: { - bark: 25, - } -}).logger.bark("arf arf"); +pinoHttp({ customLevels: { bark: 25 } }).logger.bark("arf arf"); + +// custom levels added to the logger passed in the options should be available/typesafe +pinoHttp({ logger: pino({ customLevels: { bark: 35 } }) }).logger.bark( + "arf arf" +); + +// if custom levels are passed in both the customLevels option and via the logger +// all the levels should be available/typesafe +const { logger: customLevelsLogger } = pinoHttp({ + logger: pino({ customLevels: { meow: 35 } }), + customLevels: { bark: 25 }, +}); + +customLevelsLogger.meow("meow meow"); +customLevelsLogger.bark("arf arf");