{"by":"bperel","descendants":17,"id":44288643,"kids":[44291569,44289307,44290517,44290164,44290296,44289322],"score":44,"text":"Hello HN,<p>I built a Typescript library (named socket-call, for lack of a more sexy name) whose goal is to be able to call socket.io events as regular functions.<p>So you declare your server-side like so:<p><pre><code>  ...\n  const listenEvents = (services: UserServices) =&gt; ({\n    &#x2F;&#x2F; Add your events here, the name of the event is the name of the function\n    login: async (username: string) =&gt; {\n      services._socket.data.user = { username };\n      console.log(`User ${username} logged in`);\n      setInterval(() =&gt; {\n        &#x2F;&#x2F; Calling an event that&#x27;s handled client-side\n        services.showServerMessage(`You&#x27;re still logged in ${username}!`)\n      }, 1000);\n      return `You are now logged in ${username}!`;\n    },\n  });\n</code></pre>\nand then on the client side you call them like normal async Javascript functions (and you can also create client-side event handlers):<p><pre><code>  ...\n  const user = socket.addNamespace&lt;UserEmitEvents, UserListenEvents&gt;(\n    &#x27;&#x2F;user&#x27;\n  );\n  \n  &#x2F;&#x2F; Calling an event that&#x27;s declared server-side\n  user.login(username.value).then((message) =&gt; {\n    console.log(&#x27;Server acked with&#x27;, message);\n  });\n  \n  &#x2F;&#x2F; Handling an event that is sent by the server\n  user.showServerMessage = (message) =&gt; {\n    console.log(&#x27;Server sent us the message&#x27;, message);\n  }\n\n</code></pre>\nI use this library for my own projects and would be interested to receive feedback about it :-)","time":1750074054,"title":"Show HN: Socket-call – Call socket.io events like normal JavaScript functions","type":"story","url":"https://github.com/bperel/socket-call"}