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

one-socket

v1.0.9

Published

simple socket server and client for NodeJS

Downloads

43

Readme

Introduction

OneSocket is a simple, lightweight socket server and socket client library written in TypeScript for NodeJS.

Under the hood OneSocket uses:

  • NodeJS native net module
  • Zod for schema validation
  • JSON for data serialization

Installation

npm i -D one-socket

Usage

OneSocket is designed to be used in a microservice architecture as RPC or IPC. In comparison to gRPC and protobuf OneSocket uses JavaScript and JSON which makes it very easy to start working with. OneSocket is not designed to be used in a browser, because it doesn't use HTTP.

Getting Started

Schema

OneSocket uses Zod Schema to parse all incoming and outgoing parameters. The Schema is defined as follows:

 const schema = {
  "-=Method Name=-": {
    request: z.object({
      // incoming object schema
    }),
    response: z.object({
      // outgoing object schema
    }),
  },
}

For example, a simple authorization method's Schema can look like this:

import { z } from 'zod';

const schema = {
  SignUp: {
    request: z.object({
      username: z.string().email().min(5),
      password: z.string().min(8),
    }),
    response: z.object({
      userId: z.number(),
    }),
  },

  SignIn: {
    request: z.object({
      username: z.string().email().min(5),
      password: z.string().min(8),
    }),
    response: z.object({
      access: z.string(),
      refresh: z.string(),
    }),
  },
};

This Schema should be shared between your server and client.

OneSocket Client <> Server communication

OneSocket uses JSON to communicate between client and server. To call a server method the client should send a JSON object with a following structure:

const requestMessage = {
  type: '-=Method Name=-',
  payload: {
    // request object
  },
}

The server will parse the request object using the Schema and call the corresponding handler function. The handler function should return a response object that will be validated using the Schema and sent back to the client with a following structure:

const responseMessage = {
  success: true,
  payload: {
    // response object
  },
} | {
  success: false,
  errorMsg: 'error message'
}

If there has been any error during the request parsing or handling, the server will put the error message into the errorMsg field and set success to false. If the request has been handled successfully, the server will put the response object into the payload field and set success to true.

Handlers

Handlers are defined as an object with method names as keys and handler functions as values. For example:

const SignUp: (params: z.infer<typeof schema.SignUp.request>) => Promise<z.infer<typeof schema.SignUp.response>> = async (params) => {
  // all handler functions should be asynchronios (return a Promise) 
  return Promise.resolve({ 
    userId: 1,
  });
};

const SignIn: (params: z.infer<typeof schema.SignIn.request>) => Promise<z.infer<typeof schema.SignIn.response>> = async (params) => {
  // all handler functions should be asynchronios (return a Promise) 
  return Promise.resolve({
    access: 'access token',
    refresh: 'refresh token',
  });
};

const handlers = {
  SignUp: SignUp,
  SignIn: SignIn,
}

Server instance

Both Schema and Handlers should be supplied to the OneSocket server instance (after the host port).

OneSocketServer(8123, schema, handlers);

Client instance

Client instance is a function that takes a host, port and a JSON object as parameters and returns a promise that resolves to a stringified JSON object.

OneSocketClient('127.0.0.1', 8123, { type: 'SignUp', payload: { username: 'admin', password: '123' } });

Since all requests and responses will be parsed using Zod on the Server, the client can safely infer the response type from the schema and return a typed response.

import { OneSocketClient, type TResponse } from 'one-socket';

// wrapper type
type SignUpResponse = TResponse<z.infer<typeof schema.SignUp.response>>;

const SignUpSend: (params: z.infer<typeof schema.SignUp.request>) => Promise<SignUpResponse> = async (params) => {
  const resp = await OneSocketClient('127.0.0.1', 8123, { type: 'SignUp', payload: params });

  return JSON.parse(resp) as SignUpResponse;
};

Examples

you can find examples under /examples folder

Feature Plans

  • Change message format to have proper signature
  • Integrate authentication
  • Handle binary data
  • Add tests
  • Add more examples