diff --git a/src/index.ts b/src/index.ts index b3f1647..9c7c3ec 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,7 @@ export { useCreateRelayNode, } from "./useCreateWaku"; export { useFilterMessages } from "./useFilterMessages"; +export { useLightPush } from "./useLightPush"; export { useStoreMessages } from "./useStoreMessages"; export { FullNodeProvider, diff --git a/src/useLightPush.ts b/src/useLightPush.ts new file mode 100644 index 0000000..49599f1 --- /dev/null +++ b/src/useLightPush.ts @@ -0,0 +1,56 @@ +import React from "react"; +import type { + IEncoder, + ILightPush, + IMessage, + ProtocolOptions, + SendResult, + Waku, +} from "@waku/interfaces"; + +type AbstractLightPushNode = Waku & { + lightPush: ILightPush; +}; + +type UseLightPushParams = { + encoder: undefined | IEncoder; + node: undefined | AbstractLightPushNode; +}; + +type PushFn = ( + message: IMessage, + opts?: ProtocolOptions, +) => Promise; + +type UseLightPushResult = { + push: undefined | PushFn; +}; + +/** + * Returns light push methods bound to node and encoder + * @param {Object} params.node - node that implements ILightPush, hook does nothing if empty + * @param {Object} params.encoder - encoder for processing messages, hook does nothing if empty + * @returns {Object} methods of ILightPush such as push + */ +export const useLightPush = ( + params: UseLightPushParams, +): UseLightPushResult => { + const { node, encoder } = params; + + const push = React.useCallback( + (message, opts = undefined) => { + return node!.lightPush.push(encoder as IEncoder, message, opts); + }, + [node, encoder], + ); + + if (!node && !encoder) { + return { + push: undefined, + }; + } + + return { + push, + }; +};