Skip to content

Commit 3ed7c83

Browse files
committed
feat(mokapi): Added support for providing a function to dynamically decide whether a handler should be tracked.
1 parent 76c0f41 commit 3ed7c83

3 files changed

Lines changed: 160 additions & 31 deletions

File tree

types/mokapi/index.d.ts

Lines changed: 145 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
/**
22
* Mokapi JavaScript API
3-
* https://mokapi.io/docs/welcome
3+
*
4+
* This module exposes the core scripting API for Mokapi.
5+
* It allows you to intercept and manipulate protocol events (HTTP, Kafka, LDAP, SMTP),
6+
* schedule jobs, generate mock data, and share state between scripts.
7+
*
8+
* Documentation:
9+
* https://mokapi.io/docs/javascript-api/overview
410
*/
511

612
import "./faker";
@@ -14,10 +20,14 @@ import "./file";
1420

1521
/**
1622
* Attaches an event handler for the given event.
23+
*
24+
* Event handlers are executed in priority order whenever the event occurs.
25+
* Multiple handlers can be registered for the same event.
26+
*
1727
* https://mokapi.io/docs/javascript-api/mokapi/on
18-
* @param event Event type such as http
19-
* @param handler An EventHandler to execute when the event is triggered
20-
* @param args EventArgs object contains additional event arguments.
28+
* @param event Event type such as `http`, `kafka`, `ldap`, or `smtp`
29+
* @param handler Function executed when the event is triggered
30+
* @param args Optional event configuration such as priority, tracking, or tags
2131
* @example
2232
* export default function() {
2333
* on('http', function(request, response) {
@@ -30,7 +40,7 @@ import "./file";
3040
* })
3141
* }
3242
*/
33-
export function on<T extends keyof EventHandler>(event: T, handler: EventHandler[T], args?: EventArgs): void;
43+
export function on<T extends keyof EventHandler>(event: T, handler: EventHandler[T], args?: TypedEventArgs[T]): void;
3444

3545
/**
3646
* Schedules a new periodic job with interval.
@@ -110,16 +120,18 @@ export interface EventHandler {
110120
}
111121

112122
/**
113-
* HttpEventHandler is a function that is executed when an HTTP event is triggered.
123+
* HttpEventHandler is invoked for every incoming HTTP request.
124+
*
125+
* Handlers may modify the response object to influence the outgoing response.
126+
* The return value is ignored.
127+
*
114128
* https://mokapi.io/docs/javascript-api/mokapi/eventhandler/httpeventhandler
115129
* @example
116130
* export default function() {
117131
* on('http', function(request, response) {
118132
* if (request.operationId === 'time') {
119133
* response.body = date()
120-
* return true
121134
* }
122-
* return false
123135
* })
124136
* }
125137
*/
@@ -189,19 +201,27 @@ export interface HttpResponse {
189201
data: any;
190202

191203
/**
192-
* Rebuilds the entire HTTP response using the OpenAPI response definition for the given status code and content type
193-
* @example
194-
* import { on } from 'mokapi'
204+
* Rebuilds the entire HTTP response using the OpenAPI response definition.
205+
*
206+
* This resets the status code, headers, and response body/data
207+
* based on the OpenAPI specification.
208+
*
209+
* - If `statusCode` is omitted, the OpenAPI `default` response is used.
210+
* - If `contentType` is omitted, the first defined content type for the
211+
* selected status code is used.
212+
*
213+
* Use this when switching to a different response (e.g. error handling)
214+
* while keeping the response schema valid.
215+
*
216+
* @throws Error if the status code or content type is not defined in the OpenAPI spec
195217
*
196-
* export default function() {
197-
* on('http', (request, response) => {
198-
* if (request.path.petId === 10) {
199-
* // Switch to a different OpenAPI response.
200-
* response.rebuild(404, 'application/json')
201-
* response.data.message = 'Pet not found'
202-
* }
203-
* })
204-
* }
218+
* @example
219+
* on('http', (request, response) => {
220+
* if (request.path.petId === 10) {
221+
* response.rebuild(404)
222+
* response.data.message = 'Pet not found'
223+
* }
224+
* })
205225
*/
206226
rebuild: (statusCode?: number, contentType?: string) => void;
207227
}
@@ -465,6 +485,55 @@ export interface EventArgs {
465485
*/
466486
tags?: { [key: string]: string };
467487

488+
/**
489+
* Defines the execution order of the event handler.
490+
*
491+
* Event handlers are executed in descending priority order.
492+
* Handlers with the same priority are executed in registration order.
493+
*
494+
* Handlers with higher priority values run first.
495+
* Handlers with lower priority values run later.
496+
*
497+
* Use negative priorities (e.g. -1) to run a handler after
498+
* the response has been fully populated by other handlers,
499+
* such as for logging or recording purposes.
500+
*/
501+
priority?: number;
502+
}
503+
504+
/**
505+
* TypedEventArgs provides strongly typed argument objects
506+
* for each supported event type.
507+
*
508+
* It is mainly used internally to map event names
509+
* (e.g. `http`, `kafka`) to their corresponding argument types.
510+
*/
511+
export interface TypedEventArgs {
512+
/**
513+
* Arguments for HTTP event handlers.
514+
*/
515+
http: HttpEventArgs;
516+
/**
517+
* Arguments for Kafka event handlers.
518+
*/
519+
kafka: KafkaEventArgs;
520+
/**
521+
* Arguments for LDAP event handlers.
522+
*/
523+
ldap: LdapEventArgs;
524+
/**
525+
* Arguments for SMTP event handlers.
526+
*/
527+
smtp: SmtpEventArgs;
528+
}
529+
530+
/**
531+
* Configuration options for HTTP event handlers.
532+
*
533+
* These arguments control execution behavior such as
534+
* priority, tagging, and dashboard tracking.
535+
*/
536+
export interface HttpEventArgs extends EventArgs {
468537
/**
469538
* Controls whether this event handler is tracked in the dashboard.
470539
*
@@ -473,19 +542,61 @@ export interface EventArgs {
473542
* - undefined: Mokapi determines tracking automatically based on
474543
* whether the response object was modified by the handler
475544
*/
476-
track?: boolean;
545+
track?: boolean | ((request: HttpRequest, response: HttpResponse) => boolean);
546+
}
477547

548+
/**
549+
* Configuration options for Kafka event handlers.
550+
*
551+
* These arguments control execution behavior such as
552+
* priority, tagging, and dashboard tracking.
553+
*/
554+
export interface KafkaEventArgs extends EventArgs {
478555
/**
479-
* Defines the execution order of the event handler.
556+
* Controls whether this event handler is tracked in the dashboard.
480557
*
481-
* Handlers with higher priority values run first.
482-
* Handlers with lower priority values run later.
558+
* - true: always track this handler
559+
* - false: never track this handler
560+
* - undefined: Mokapi determines tracking automatically based on
561+
* whether the message was modified or acknowledged by the handler
562+
*/
563+
track?: boolean | ((message: KafkaEventMessage) => boolean);
564+
}
565+
566+
/**
567+
* Configuration options for LDAP event handlers.
568+
*
569+
* These arguments control execution behavior such as
570+
* priority, tagging, and dashboard tracking.
571+
*/
572+
export interface LdapEventArgs extends EventArgs {
573+
/**
574+
* Controls whether this event handler is tracked in the dashboard.
483575
*
484-
* Use negative priorities (e.g. -1) to run a handler after
485-
* the response has been fully populated by other handlers,
486-
* such as for logging or recording purposes.
576+
* - true: always track this handler
577+
* - false: never track this handler
578+
* - undefined: Mokapi determines tracking automatically based on
579+
* whether the response object was modified by the handler
487580
*/
488-
priority?: number;
581+
track?: boolean | ((request: LdapSearchRequest, response: LdapSearchResponse) => boolean);
582+
}
583+
584+
/**
585+
* Configuration options for SMTP event handlers.
586+
*
587+
* These arguments control execution behavior such as
588+
* priority, tagging, and dashboard tracking.
589+
*/
590+
export interface SmtpEventArgs extends EventArgs {
591+
/**
592+
* Controls whether this event handler is tracked in the dashboard.
593+
*
594+
* - true: always track this handler
595+
* - false: never track this handler
596+
* - undefined: Mokapi determines tracking automatically based on
597+
* whether the message was processed or modified by the handler
598+
*/
599+
track?: boolean | ((record: SmtpEventMessage) => boolean);
489600
}
490601

491602
/**
@@ -500,6 +611,10 @@ export interface EventArgs {
500611
*/
501612
export type ScheduledEventHandler = () => void | Promise<void>;
502613

614+
/**
615+
* Configuration options for scheduled event handlers
616+
* created via `every` or `cron`.
617+
*/
503618
export interface ScheduledEventArgs {
504619
/**
505620
* Adds or overrides existing tags used in dashboard
@@ -663,7 +778,8 @@ export interface SharedMemory {
663778
* The `mokapi.shared` object provides a way to persist and share
664779
* data between multiple scripts running in the same Mokapi instance.
665780
*
666-
* Values are stored in memory and shared across all scripts.
781+
* Values are stored in memory and shared across all scripts
782+
* within the same Mokapi process.
667783
* This allows you to coordinate state, cache data, or simulate
668784
* application-level variables without using global variables.
669785
* All values are persisted for the lifetime of the Mokapi process.

types/mokapi/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
{
22
"private": true,
33
"name": "@types/mokapi",
4-
"version": "0.34.9999",
4+
"version": "0.35.9999",
55
"nonNpm": true,
66
"nonNpmDescription": "Mokapi",
77
"projects": [
8-
"https://mokapi.io/docs/guides/get-started/welcome"
8+
"https://mokapi.io/docs/welcome"
99
],
1010
"devDependencies": {
1111
"@types/mokapi": "workspace:."

types/mokapi/test/mokapi-tests.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,16 @@ on("http", (request, response) => {
7070
// @ts-expect-error
7171
response.rebuild(200, {});
7272
});
73+
on("http", () => {}, { track: true });
74+
// @ts-expect-error
75+
on("http", () => {}, { track: 123 });
76+
on("http", () => {}, { track: () => true });
77+
// @ts-expect-error
78+
on("http", () => {}, { track: () => 123 });
79+
on("http", () => {}, { track: (req) => req.api === "foo" });
80+
on("http", () => {}, { track: (req, res) => res.body === "foo" });
81+
// @ts-expect-error
82+
on("http", () => {}, { track: (req, res) => res.foo === "foo" });
7383

7484
// @ts-expect-error
7585
every(12, () => {});
@@ -198,6 +208,7 @@ kafka = (record: KafkaEventMessage) => {
198208
record.headers = null;
199209
record.headers = { foo: "bar" };
200210
};
211+
on("kafka", () => {}, { track: (record) => record.key === "foo" });
201212

202213
let ldap: LdapEventHandler = () => {};
203214
// @ts-expect-error
@@ -226,6 +237,7 @@ ldap = (req: LdapSearchRequest, res: LdapSearchResponse) => {
226237
res.message = 12;
227238
res.message = "";
228239
};
240+
on("ldap", () => {}, { track: (request) => request.baseDN === "foo" });
229241

230242
let smtp: SmtpEventHandler = () => {};
231243
// @ts-expect-error
@@ -325,6 +337,7 @@ smtp = (msg: SmtpEventMessage) => {
325337
data: new Uint8Array(2),
326338
}];
327339
};
340+
on("smtp", () => {}, { track: (mail) => mail.subject === "foo" });
328341

329342
const i: number = patch(1, 2);
330343
patch({ x: 1 }, { y: 1 });

0 commit comments

Comments
 (0)