Skip to content
This repository has been archived by the owner on Nov 9, 2023. It is now read-only.

Add destroy method #106

Merged
merged 7 commits into from
May 18, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions src/JsonRpcEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,15 @@ export type JsonRpcEngineEndCallback = (
error?: JsonRpcEngineCallbackError,
) => void;

export type JsonRpcMiddleware<Params, Result> = (
req: JsonRpcRequest<Params>,
res: PendingJsonRpcResponse<Result>,
next: JsonRpcEngineNextCallback,
end: JsonRpcEngineEndCallback,
) => void;
export interface JsonRpcMiddleware<Params, Result> {
(
req: JsonRpcRequest<Params>,
res: PendingJsonRpcResponse<Result>,
next: JsonRpcEngineNextCallback,
end: JsonRpcEngineEndCallback,
): void;
destroy?: () => void | Promise<void>;
}

/**
* A JSON-RPC request and response processor.
Expand All @@ -57,6 +60,26 @@ export class JsonRpcEngine extends SafeEventEmitter {
this._middleware.push(middleware as JsonRpcMiddleware<unknown, unknown>);
}

/**
* Calls the `destroy()` function of any middleware with that property and clears
* the middleware array.
*/
cleanup(): void {
this._middleware.forEach(
(middleware: JsonRpcMiddleware<unknown, unknown>) => {
if (
// `in` walks the prototype chain, which is probably the desired
// behavior here.
'destroy' in middleware &&
typeof middleware.destroy === 'function'
) {
middleware.destroy();
}
},
);
this._middleware = [];
}

/**
* Handle a JSON-RPC request, and return a response.
*
Expand Down
26 changes: 25 additions & 1 deletion src/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
isJsonRpcSuccess,
} from '@metamask/utils';
import { ethErrors } from 'eth-rpc-errors';
import { JsonRpcEngine } from '.';
import { JsonRpcEngine, JsonRpcMiddleware } from '.';

const jsonrpc = '2.0' as const;

Expand Down Expand Up @@ -528,4 +528,28 @@ describe('JsonRpcEngine', () => {

await expect(engine.handle([{}] as any)).rejects.toThrow('foo');
});

it('cleanup middleware test', async () => {
const engine = new JsonRpcEngine();

engine.push((_req, res, next, _end) => {
res.result = 42;
next();
});

const destroyMock = jest.fn();
const destroyableMiddleware: JsonRpcMiddleware<unknown, unknown> = (
_req,
_res,
_next,
end,
) => {
end();
};
destroyableMiddleware.destroy = destroyMock;
engine.push(destroyableMiddleware);

engine.cleanup();
expect(destroyMock).toHaveBeenCalledTimes(1);
});
});