Converting RT hook functions to generics for type support

Hello!
I figured it’d be interesting to see a conversion of the typedefs for the functions registerRtBefore and registerRtAfter

The issue I encountered was typing hook callbacks specifically to fit the Realtime channel I wanted to hook onto. The code from the docs for example throws a type error without narrowing the types upstream.

My proposal is to convert the realtime functions to generics as to infer the types based on the RtBeforeHookFunction type or the type passed to the generic on the hook functions themselves. Please see below!

/**
         * Register a hook function to be run before an RPC function is invoked.
         * The RPC call is identified by the id param.
         *
         * @param id - The ID of the RPC function.
         * @param func - The Hook function logic to execute before the RPC is called.
         */
        registerRtBefore<T extends Envelope>(id: RtHookMessage, func: RtBeforeHookFunction<T>): void;

        /**
         * Register a hook function to be run after an RPC function is invoked.
         * The RPC call is identified by the id param.
         *
         * @param id - The ID of the RPC function.
         * @param func - The Hook function logic to execute after the RPC is called.
         */
        registerRtAfter<T extends Envelope>(id: RtHookMessage, func: RtAfterHookFunction<T>): void;

I suppose the second stage to this would be typeguards on RtHookMessage that narrow the rest of the function as well haha.

Please let me know what you think! Thanks all :slight_smile:

Hello @Noita,

I think is is a good suggestion, would you like to contribute by opening a PR at GitHub - heroiclabs/nakama-common: The runtime framework for Nakama server.?

Best.

Sure thing! I’ll see about making a PR!
PR submitted Genericize realtime before and after hooks by Noitabara · Pull Request #127 · heroiclabs/nakama-common · GitHub