Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@yomo/presencejs

Package Overview
Dependencies
Maintainers
4
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@yomo/presencejs

@yomo/presencejs ⚡️ made realtime web applications edge-aware by YoMo

  • 1.0.0-alpha.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
8
decreased by-20%
Maintainers
4
Weekly downloads
 
Created
Source

presencejs logo
NPM version License

🧬 Introduction

Presencejs is a JavaScript library that allows you to build real-time web applications quickly, the server is built atop of YoMo, which provide secure, low-latency, and high-performance geo-distributed services.

...and a lot more.

With presencejs, components will get data flow in real time. Thus, the UI will be always fast and reactive.

🌟 Showcase

🥷🏼 Quick Start

1. Add presencejs to your web app

Using npm

$ npm i --save @yomo/presencejs

Using yarn

$ yarn add @yomo/presencejs

Using pnpm

$ pnpm i @yomo/presencejs

For CDN, you can use skypack: https://cdn.skypack.dev/@yomo/presencejs

<script type="module">
    import Presence from 'https://cdn.skypack.dev/@yomo/presencejs';
</script>

2. Connect to presence server

The client need to authenticate with YoMo to establish a realtime connection. The following code sample uses a demo YoMo's server(https://prsc.yomo.dev) and token to authenticate and print the message Connected to YoMo! when you’ve successfully connected.

How do I get a token?

If you build your application using Next.js, then you can use API Routes to get the access token. For example, the following API route pages/api/presence-auth.js returns a json response with a status code of 200:

export default async function handler(req, res) {
    if (req.method === 'GET') {
        try {
            const response = await fetch('https://prsc.yomo.dev/api/v1/auth', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    app_id: process.env.PRESENCE_APP_ID,
                    app_secret: process.env.PRESENCE_APP_SECRET,
                }),
            });
            const data = await response.json();
            const token = data.data;
            if (token) {
                res.status(200).json(token);
            } else {
                res.status(400).json({ msg: data.message });
            }
        } catch (error) {
            if (typeof error === 'string') {
                res.status(500).json({ msg: error });
            } else if (error instanceof Error) {
                res.status(500).json({ msg: error.message });
            }
        }
    } else {
        // Handle any other HTTP method
        res.status(405).json({})
    }
}

Response data:

{
    "token": "eyJhbGciOiJIUzI1..."
}
Create a Presence instance
import Presence from '@yomo/presencejs';

// create an instance.
const yomo = new Presence('https://prsc.yomo.dev', {
    auth: {
        // Certification Type
        type: 'token',
        // Api for getting access token
        endpoint: '/api/presence-auth',
    },
});

yomo.on('connected', () => {
    console.log('Connected to server: ', yomo.host);
});

3. Subscribe to messages from the server

Call the toRoom('001') function to enter room 001, without it, you are in the default room.The client receives a message with the name online through the on callback function, and can also subscribe to a message with the name mousemove by returning an observable object through on$.

yomo.on('connected', () => {
    // Enter a room
    yomo.toRoom('001');

    // Function to handle response for given event from server
    yomo.on('online', data => {
        console.log('online:', data);
    });

    // Same as the `on` method, returns an observable response
    yomo.on$('mousemove').subscribe(data => {
        console.log('mousemove:', data);
    });

    // If you want to display the latency, you can get the value of the latency like this
    yomo.on('latency', data => {
        const { id, latency, meshId } = data;
        console.log('latency:', latency);
    });
});

4. Send messages to the server

The following example code send a message to the quickstart room with the name online and the contents pixel position. You can use rxjs to get an observable sequence of browser event transitions,then send the data to the signal channel with the name mousemove in room 001 via ofRoom('001', 'mousemove').

import { fromEvent } from 'rxjs';
import { map } from 'rxjs/operators';

const ID = '34a1dbb5-c031-4680-926c-84a789d251e0';

yomo.on('connected', () => {
    // Function for sending data to the server
    yomo.send('online', {
        id: ID,
        x: 10,
        y: 10,
    });

    // Converting browser events into observable sequences.
    const mousemove$ = fromEvent(document, 'mousemove').pipe(
        map(event => {
            return {
                id: ID,
                x: event.clientX,
                y: event.clientY,
            };
        })
    );

    // Sending data streams to the server
    mousemove$.subscribe(yomo.ofRoom('001', 'mousemove'));
});

5. Close a connection

A connection to YoMo can be closed once it is no longer needed.

yomo.close();
yomo.on('closed', () => {
    console.log('Closed the connection');
});

🤹🏻‍♀️ API

Methods of instanceDescriptionType
onFunction to handle response for given event from serveron<T>(event: string, cb: (data: T) => void): void
on$Same as the on method, returns an observable responseon$<T>(event: string): Observable<T>
sendFunction for sending data to the serversend<T>(event: string, data: T)
toRoomEnter a roomtoRoom(roomName: string): Presence
ofRoomFunction for sending data streams to the serverofRoom(roomName: string, event: string)
closeA connection to YoMo can be closed once it is no longer needed.close(): void

⛷ Contributors

License

The MIT License.

Keywords

FAQs

Package last updated on 23 Feb 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc