Repository URL to install this package:
|
Version:
0.0.7 ▾
|
import { Request as ExpressRequest, Response as ExpressResponse } from 'express'
import { isObj } from 'exotic'
import { LoggingMetaType } from './typings'
import { Timer } from './Timer'
import { trace } from './trace'
// put in typings...
export interface OneUrl {
full: string
host: string
}
export type ExpressRequestWithMeta = ExpressRequest & {
timer?: Timer
meta?: LoggingMetaType
oneUrl: OneUrl
}
export type ExpressResponseWithMeta = ExpressResponse & {
meta?: LoggingMetaType
}
/**
* @todo move to own filee
*/
export class Tracer {
static init(req: ExpressRequestWithMeta, appName: string) {
const tracer = new Tracer(req, appName)
return tracer
}
req: ExpressRequestWithMeta
spans: Map<string, any> = new Map()
appName: string
constructor(req: ExpressRequestWithMeta, appName: string) {
this.appName = appName
this.req = req
}
get meta() {
return this.req.meta
}
get headers() {
return {
...this.req.headers,
...this.req.res!.getHeaders(),
} as any
}
start(spanName: string) {
const timer = Timer.init()
this.spans.set(spanName, { timer })
return this
}
finish(spanName: string) {
const span = this.spans.get(spanName)
const { timer } = span
// @todo `get url` to fallback?
const url = isObj(this.req.oneUrl) === true ? this.req.oneUrl.full : '@@EMPTY'
trace({ appName: this.appName, spanName, timer, url, headers: this.headers, meta: this.req.meta })
}
}