This repository was archived by the owner on Nov 9, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcreateEngineStream.ts
More file actions
48 lines (44 loc) · 1.27 KB
/
createEngineStream.ts
File metadata and controls
48 lines (44 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { JsonRpcEngine } from '@metamask/json-rpc-engine';
import type { JsonRpcRequest } from '@metamask/utils';
import { Duplex } from 'readable-stream';
type EngineStreamOptions = {
engine: JsonRpcEngine;
};
/**
* Takes a JsonRpcEngine and returns a Duplex stream wrapping it.
*
* @param opts - Options bag.
* @param opts.engine - The JsonRpcEngine to wrap in a stream.
* @returns The stream wrapping the engine.
*/
export default function createEngineStream(opts: EngineStreamOptions): Duplex {
if (!opts?.engine) {
throw new Error('Missing engine parameter!');
}
const { engine } = opts;
const stream = new Duplex({ objectMode: true, read: () => undefined, write });
// forward notifications
if (engine.on) {
engine.on('notification', (message) => {
stream.push(message);
});
}
return stream;
/**
* Write a JSON-RPC request to the stream.
*
* @param req - The JSON-rpc request.
* @param _encoding - The stream encoding, not used.
* @param streamWriteCallback - The stream write callback.
*/
function write(
req: JsonRpcRequest,
_encoding: unknown,
streamWriteCallback: (error?: Error | null) => void,
) {
engine.handle(req, (_err, res) => {
stream.push(res);
});
streamWriteCallback();
}
}