diff --git a/packages/core/src/lib/light_push/index.ts b/packages/core/src/lib/light_push/index.ts index a0259b3d12..ce886410ea 100644 --- a/packages/core/src/lib/light_push/index.ts +++ b/packages/core/src/lib/light_push/index.ts @@ -27,6 +27,16 @@ const log = debug("waku:light-push"); export const LightPushCodec = "/vac/waku/lightpush/2.0.0-beta1"; export { PushResponse }; +type PreparePushMessageResult = + | { + query: PushRpc; + error: null; + } + | { + query: null; + error: SendError; + }; + /** * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/). */ @@ -42,26 +52,32 @@ class LightPush extends BaseProtocol implements ILightPush { encoder: IEncoder, message: IMessage, pubSubTopic: string - ): Promise<{ - query: PushRpc | null; - error?: SendError; - }> { - if (!isSizeValid(message.payload)) { - log("Failed to send waku light push: message is bigger than 1MB"); - return { query: null, error: SendError.SIZE_TOO_BIG }; - } + ): Promise { + try { + if (!isSizeValid(message.payload)) { + log("Failed to send waku light push: message is bigger than 1MB"); + return { query: null, error: SendError.SIZE_TOO_BIG }; + } + + const protoMessage = await encoder.toProtoObj(message); + if (!protoMessage) { + log("Failed to encode to protoMessage, aborting push"); + return { + query: null, + error: SendError.ENCODE_FAILED + }; + } + + const query = PushRpc.createRequest(protoMessage, pubSubTopic); + return { query, error: null }; + } catch (error) { + log("Failed to prepare push message", error); - const protoMessage = await encoder.toProtoObj(message); - if (!protoMessage) { - log("Failed to encode to protoMessage, aborting push"); return { query: null, - error: SendError.ENCODE_FAILED + error: SendError.GENERIC_FAIL }; } - - const query = PushRpc.createRequest(protoMessage, pubSubTopic); - return { query }; } async send( @@ -71,33 +87,21 @@ class LightPush extends BaseProtocol implements ILightPush { ): Promise { const { pubSubTopic = DefaultPubSubTopic } = this.options; const recipients: PeerId[] = []; - let error: undefined | SendError = undefined; - - let query: PushRpc | null = null; - - try { - const { query: preparedQuery, error: preparationError } = - await this.preparePushMessage(encoder, message, pubSubTopic); - - if (preparationError) { - return { - recipients, - error: preparationError - }; - } - query = preparedQuery; - } catch (error) { - log("Failed to prepare push message", error); - } + const { query, error: preparationError } = await this.preparePushMessage( + encoder, + message, + pubSubTopic + ); - if (!query) { + if (preparationError || !query) { return { recipients, - error: SendError.GENERIC_FAIL + error: preparationError }; } + let error: undefined | SendError = undefined; const peer = await this.getPeer(opts?.peerId); const stream = await this.newStream(peer);