Skip to content

Commit

Permalink
feat(transport): add 'silent' emit options
Browse files Browse the repository at this point in the history
  • Loading branch information
unadlib committed Nov 3, 2023
1 parent a0b4ce2 commit a99af90
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,21 @@ export interface EmitParameter<T> {
*/
name: T;
/**
* Whether a response is required.
* Whether a response is required, true by default.
*/
respond?: boolean;
/**
* Timeout for the emitting event.
* Timeout for the emitting event, 60s by default.
*/
timeout?: number;
/**
* Extra data for the emitting event.
*/
_extra?: Record<string, any>;
/**
* silent for timeout error, false by default.
*/
silent?: boolean;
}

export type EmitOptions<T> = T | EmitParameter<T>;
Expand Down
6 changes: 5 additions & 1 deletion src/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import type {
import { generateId } from './utils';

const DEFAULT_TIMEOUT = 60 * 1000;
const DEFAULT_RESPOND = true;
const DEFAULT_SILENT = false;
const DEFAULT_PREFIX = 'DataTransport';

export const getAction = (prefix: string, name: string) =>
Expand Down Expand Up @@ -252,7 +254,8 @@ export abstract class Transport<T extends BaseInteraction = any> {
): Promise<Response<T['emit'][K]>> {
const params =
typeof options === 'object' ? options : ({} as EmitParameter<K>);
const hasRespond = params.respond ?? true;
const hasRespond = params.respond ?? DEFAULT_RESPOND;
const isSilent = params.silent ?? DEFAULT_SILENT;
const timeout = params.timeout ?? this[timeoutKey];
const name = params.name ?? options;
const transportId = generateId();
Expand Down Expand Up @@ -305,6 +308,7 @@ export abstract class Transport<T extends BaseInteraction = any> {
clearTimeout(timeoutId as NodeJS.Timeout);
this[requestsMapKey].delete(transportId);
if (typeof error === 'undefined') {
if (isSilent) return;
console.warn(
`The event '${action}' timed out for ${timeout} seconds...`
);
Expand Down
10 changes: 10 additions & 0 deletions test/dispose.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,14 @@ test('dispose in base transport', async () => {
expect(warn.mock.calls[0][0]).toBe(
"The event 'DataTransport-hello' timed out for 1001 seconds..."
);
expect(warn.mock.calls.length).toBe(1);


const result1 = await internal.emit(
{ name: 'hello', timeout: 1002, silent: true },
{ num: 42 },
'Universe'
);
expect(result1).toBeUndefined();
expect(warn.mock.calls.length).toBe(1);
});

0 comments on commit a99af90

Please sign in to comment.