Skip to content
This repository was archived by the owner on Apr 17, 2023. It is now read-only.

Commit 8fe30a1

Browse files
committed
feat(BrokerUtil): support sending bigints
1 parent d53973f commit 8fe30a1

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

libs/brokers/src/brokers/BrokerUtil.ts

+19-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { randomBytes } from 'crypto';
22
import { getMissingProps } from '@cordis/common';
3-
import { encode, decode } from '@msgpack/msgpack';
3+
import { encode, decode, ExtensionCodec } from '@msgpack/msgpack';
44
import { CordisBrokerTypeError } from '../error';
55
import type * as amqp from 'amqplib';
66
import type { Broker } from './Broker';
@@ -88,7 +88,21 @@ export class BrokerUtil {
8888
* Broker instance
8989
*/
9090
public readonly broker: Broker
91-
) {}
91+
) {
92+
this.packBigintExtensionCodec.register({
93+
type: 0,
94+
encode: (input: unknown) => {
95+
if (typeof input === 'bigint') {
96+
return encode(input.toString());
97+
}
98+
99+
return null;
100+
},
101+
decode: (data: Uint8Array) => BigInt(decode(data) as string)
102+
});
103+
}
104+
105+
public readonly packBigintExtensionCodec = new ExtensionCodec();
92106

93107
/**
94108
* Generates a base64 string with the given length using Node.js' Crypto
@@ -118,7 +132,7 @@ export class BrokerUtil {
118132
}
119133

120134
try {
121-
await cb(decode(msg.content) as T, msg);
135+
await cb(decode(msg.content, { extensionCodec: this.packBigintExtensionCodec }) as T, msg);
122136
} catch (e) {
123137
this.broker.emit('error', e);
124138
this.broker.channel.reject(msg, true);
@@ -145,7 +159,7 @@ export class BrokerUtil {
145159
public sendToQueue<T>(options: SendToQueueOptions<T>) {
146160
const { to, content, options: amqpOptions } = options;
147161

148-
const encoded = encode(content);
162+
const encoded = encode(content, { extensionCodec: this.packBigintExtensionCodec });
149163
const data = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);
150164
return this.broker.channel.sendToQueue(to, data, amqpOptions);
151165
}
@@ -158,7 +172,7 @@ export class BrokerUtil {
158172
public sendToExchange<T>(options: SendToExchangeOptions<T>) {
159173
const { to, content, key, options: amqpOptions } = options;
160174

161-
const encoded = encode(content);
175+
const encoded = encode(content, { extensionCodec: this.packBigintExtensionCodec });
162176
const data = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);
163177
return this.broker.channel.publish(to, key, data, amqpOptions);
164178
}

0 commit comments

Comments
 (0)