Skip to content

Commit

Permalink
refactor: better type for 'constructor', 'create' and 'call' of AppCo…
Browse files Browse the repository at this point in the history
…ntext
  • Loading branch information
ma-efremoff committed Apr 3, 2023
1 parent e804097 commit 9a1bcd4
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions src/lib/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,28 @@ import {AppError} from './app-error';
import {extractErrorInfo} from './error-parser';
import {IncomingHttpHeaders} from 'http';

interface ContextParams {
type ContextParams = ContextInitialParams | ContextParentParams;

interface ContextInitialParams {
contextId?: string;
config?: AppConfig;
logger?: pino.Logger;
tracer?: JaegerTracer;
parentContext?: AppContext;
config: AppConfig;
logger: pino.Logger;
tracer: JaegerTracer;
parentSpanContext?: SpanContext;
utils?: NodeKit['utils'];
utils: NodeKit['utils'];
loggerPostfix?: string;
tags?: Dict;
}

interface ContextParentParams
extends Pick<ContextInitialParams, 'parentSpanContext' | 'loggerPostfix' | 'tags'> {
parentContext: AppContext;
}

function isContextParentParams(v: ContextParams): v is ContextParentParams {
return Boolean((v as ContextParentParams).parentContext);
}

type ContextCallbackFunction<T> = (ctx: AppContext) => T;

export class AppContext {
Expand All @@ -40,7 +50,7 @@ export class AppContext {
this.name = name;
this.startTime = Date.now();

if (params.parentContext) {
if (isContextParentParams(params)) {
this.config = params.parentContext.config;
this.logger = params.parentContext.logger;
this.tracer = params.parentContext.tracer;
Expand Down Expand Up @@ -102,20 +112,24 @@ export class AppContext {
);
}

create(name: string, params?: ContextParams) {
create(name: string, params?: Omit<ContextParentParams, 'parentContext'>) {
return new AppContext(name, {parentContext: this, ...params});
}

call<T>(name: string, fn: ContextCallbackFunction<T>, params?: ContextParams): T;
call<T>(
name: string,
fn: ContextCallbackFunction<T>,
params?: Omit<ContextParentParams, 'parentContext'>,
): T;
call<T>(
name: string,
fn: ContextCallbackFunction<Promise<T>>,
params?: ContextParams,
params?: Omit<ContextParentParams, 'parentContext'>,
): Promise<T>;
call<T>(
name: string,
fn: ContextCallbackFunction<T | Promise<T>>,
params?: ContextParams,
params?: Omit<ContextParentParams, 'parentContext'>,
): T | Promise<T> {
const ctx = this.create(name, params);

Expand Down

0 comments on commit 9a1bcd4

Please sign in to comment.