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

zilaws-server

v2.2.1

Published

ZilaWS is a blazingly fast and very lightweight library that provides an extremely easy-to-use way to transmit data via websockets between client-side and server-side using eventhandlers and async waiters.

Downloads

40

Readme

ZilaWS Server

ZilaWS is a blazingly fast and very lightweight library that provides an extremely easy-to-use way to transmit data via websockets between client-side and server-side using eventhandlers and async waiters

Test status badge MIT License coverage label for branches coverage label for functions coverage label for lines of code coverage label for statements

Documentation

Looking for the zilaws-client package?

The ZilaWS Server can accept WS connections from non-ZilaWS clients but won't work as expected.

Waiters

ZilaWS has a unique function called waiter. Waiters (as their name suggests) can be awaited. They resolve when the client side MessageHandler resolves or returns thus making it perfect for retrieving data from a client. However if the client does not respond in time, waiters will resolve as undefined. There are also broadcastWaiters.

Parameters

Regular waiters

Regular waiters wait for a response for the amount of time specified by the maxWaiterTime property. This is a property of the ZilaServer class. This property can be set while creating the server through the options object or anytime with its property.

  • identifier: The name of the MessageHandler on the other side of the connection.
  • ...data: A waiter (or a send) can be given any number of any data.
socket.waiter<T>(identifier: string, ...data: any[]): Promise<T | undefined>

Timeout Waiters

  • maxWaitingTime: This paramater overrides the maximum waiting time for the corresponding waiter or broadcastWaiter. The value is in miliseconds.
socket.waiterTimeout<T>(identifier: string, maxWaitingTime: number, ...data: any[]): Promise<T | undefined>

Example

Client

const client = await connectTo("wss://yourhost.com:6589");

console.log(await client.waiter("GetValueOfPI", "Some string") as number); // --> 3.141592653589793
console.log(await client.waiterTimeout("GetValueOfPI", 1200, "Some string") as number); // --> 3.141592653589793

Server

const server = new ZilaServer({
    port: 6589,
    https: {
        pathToCert: "cert/fullchain.pem",
        pathToKey: "cert/privkey.pem"
    }
});

server.setMessageHandler("GetValueOfPI", (param1: string) => {
    console.log(param1); // --> Some string
    return Math.PI;
});

Extending the ZilaClient class

You have the ability to extend the ZilaClient which is a class for storing server side data and functions of a WS connection. Extending is good for storing extra data (or even declaring functions) associated with a client thus making it the best way to handle authentication.

/*You should not use the WebSocketClient constructor since it's a part of the `ws` npm package,
and is only exported to make the extending easier.*/
import { ZilaServer, ZilaClient, WebSocketClient, IncomingHttpHeaders } from "zilaws-server";

class MyClient extends ZilaClient {
    public clientData: {
        rank: "admin" | "user";
        username: string;
    }

    //In order to get access to the cookies, sadly you need to define the constructor by hand.
    constructor(
        socket: WebSocketClient,
        ip: string | undefined,
        server: ZilaServer,
        isBrowser: boolean,
        headers: IncomingHttpHeaders,
        cookies?: Map<string, string>
    ) {
        super(socket, ip, server, isBrowser, headers, cookies);
        
        //This is the best place to authenticate the user.
        if(isBrowser && !AuthUserByBrowser(cookies?.get("loginToken"))) {
            this.kick("Wrong token");
            return;
        }else if (!AuthUserByHeader(headers["authorization"])) {
            this.kick("Wrong token");
            return;
        }

        this.clientData = {
            rank: "admin",
            username: "SomeUsername"
        }
    }
}

//Defining both the generic type and the clientClass is needed.
const server = new ZilaServer<MyClient>({
    port: 6589,
    logger: true,
    verbose: true,
    clientClass: MyClient
});

server.onceMessageHandler("Anything", (socket) => {
    socket.clientData.rank == "admin"; //--> true
    socket.clientData.username == "SomeUsername"; //--> true
});

Extending the ZilaServer class

You also have the ability to extend the ZilaServer class if you need to. This comes in handy if for example you need to convert data automatically.

import { IServerSettings, ZilaClient, ZilaServer, ZilaWSCallback } from "zilaws-server";

enum MessageHandlers {
    Register,
    Login,
    //...
}

class MyServer<T extends ZilaClient> extends ZilaServer<T> {
    constructor(settings: IServerSettings) {
        super(settings);
    }

    setMessageHandler(identifier: MessageHandlers | string, callback: ZilaWSCallback<T>): void {
        super.setMessageHandler(identifier.toString(), callback);
    }
}

const server = new MyServer<MyClient>({
    port: 80,
    clientClass: MyClient
});

server.setMessageHandler(MessageHandlers.Login, async (socket: MyClient, username: string, password: string) => {
    //Logging in a user
    const dbUser = await CheckLoginCredentials(username, password);
    
    if(dbUser) {
        const loginToken = generateToken();
        socket.setCookie({
            name: "LoginToken",
            value: loginToken,
            expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30)
        });

        socket.clientData = dbUser;

        return "SUCCESS";
    }else{
        return "BAD_CREDENTIALS";
    }
});

More

ZilaWS offers much more. Check out the documentation!