npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@api.global/typedsocket

v3.0.1

Published

A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.

Downloads

226

Readme

@api.global/typedsocket

a typedrequest extension supporting websockets

Install

To install @api.global/typedsocket in your project, run the following command using npm:

npm install @api.global/typedsocket --save

For Yarn users:

yarn add @api.global/typedsocket

Usage

To utilize @api.global/typedsocket effectively, let's explore how to integrate it into a project with TypeScript. This guide provides comprehensive usage scenarios, highlighting all features of the module. @api.global/typedsocket extends the capabilities of typedrequest by integrating websocket support, allowing for real-time, bidirectional communication between a client and server.

Getting Started

Prerequisites

Before diving into examples, ensure you have the following:

  • A basic understanding of TypeScript and Node.js.
  • An existing project set up with TypeScript.
  • @api.global/typedrequest and its dependencies installed in your project.

Initialization

First, let's import the required modules and initialize our server and client instances.

Server Side:

Within your server-side code, import and set up TypedSocket to create a websocket server.

import { TypedSocket } from '@api.global/typedsocket';
import * as typedrequest from '@api.global/typedrequest';

// Initialize your TypedRouter
const typedRouter = new typedrequest.TypedRouter();

// Create the TypedSocket server
const server = await TypedSocket.createServer(typedRouter);

// Optionally, you can provide a smartexpressServerArg if you have an existing SmartExpress server

Client Side:

On the client side, initialize TypedSocket to connect to the websocket server.

import { TypedSocket } from '@api.global/typedsocket';

// Assuming server is at http://localhost:3000
const client = await TypedSocket.createClient(typedRouter, 'http://localhost:3000');

Defining Typed Requests

@api.global/typedsocket leverages typedrequest for type-safe requests and responses. Here's how you can define and handle typed requests:

Defining a Typed Request Interface:

Define an interface for the request and its corresponding response.

interface ExampleRequest extends typedrequestInterfaces.ITypedRequest {
  method: 'exampleMethod';
  request: {
    message: string;
  };
  response: {
    reply: string;
  };
}

Handling Requests on the Server:

Add a typed handler for the request in your TypedRouter.

typedRouter.addTypedHandler<ExampleRequest>(
  new typedrequest.TypedHandler('exampleMethod', async (requestData) => {
    return {
      reply: `Server received: ${requestData.message}`,
    };
  })
);

Sending Requests from the Client

Use the client instance to send a request to the server and await a response.

const exampleRequest = client.createTypedRequest<ExampleRequest>('exampleMethod');
const response = await exampleRequest.fire({
  message: 'Hello from client!',
});

console.log(response.reply); // "Server received: Hello from client!"

Advanced Usage

Tagging Connections

For more refined control, especially in scenarios with multiple clients, you can tag connections for targeted communication.

// Add a tag to a client
client.addTag('role', 'admin');

// On the server, find connections with the tag
const adminConnections = await server.findAllTargetConnectionsByTag('role', 'admin');

// Send a message to all admin connections
for (const adminConnection of adminConnections) {
  const request = server.createTypedRequest<ExampleRequest>('exampleMethod', adminConnection);
  await request.fire({
    message: 'Message to admins',
  });
}

Handling Reconnections

TypedSocket automatically attempts to reconnect in the event of connection loss. Ensure your server and client logic accounts for reconnection, especially for maintaining state or re-subscribing to necessary events.

Conclusion

Implementing @api.global/typedsocket provides a type-safe, real-time communication layer for your TypeScript applications, extending the functionality of typedrequest into the realm of websockets. This guide covered initialization, defining typed requests, sending requests, and advanced usage patterns like tagging connections and handling reconnections.

Integrating @api.global/typedsocket into your project harnesses the power of websockets with the benefits of type safety and structured request/response patterns, enabling more reliable and maintainable real-time applications.

License and Legal Information

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

Company Information

Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at [email protected].

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.