A tiny Nuxt.js module for WebSocket interactions

Overview


@deepsource/nuxt-websocket

DeepSource DeepSource

A tiny Nuxt.js module for WebSocket interactions.

This module is only compatible with Nuxt v2 at the moment.

Setup

  1. Add @deepsource/nuxt-websocket dependency to your project.
yarn add @deepsource/nuxt-websocket # or npm install @deepsource/nuxt-websocket
  1. Add @deepsource/nuxt-websocket to the modules section of nuxt.config.js.
{
  modules: [
    '@deepsource/nuxt-websocket',
  ],
  websocket: {
    // module options
  }
}

TypeScript

Add the types to your types array in tsconfig.json after the @nuxt/types (Nuxt 2.9.0+) entry.

{
  "compilerOptions": {
    "types": ["@nuxt/types", "@deepsource/nuxt-websocket"]
  }
}

Options

You can pass different options using the websocket property in your nuxt.config.js.

// nuxt.config.js
export default {
  websocket: {
    url: 'wss://echo.websocket.events/'
    reconnectInterval: 1000
  }
};
Parameter Default Description
url - WebSocket URL to connect
reconnectInterval 1000 The time interval after which a reconnection attempt takes place for a close event. It should be less than 3s.

Runtime Config

You can also provide the URL via runtime config. It always takes precedence over the URL provided via options.

// nuxt.config.js
export default {
  // Via Runtime config
  publicRuntimeConfig: {
    websocket: {
      url: process.env.WEBSOCKET_URL
    }
  }
};

API

The following two plugins are injected into the Vue instance and are accessible across the app:-

$socket

It's a Vue instance that's used as an event bus.

mounted() {
  this.$socket.$on('socket', (data) => {
    console.log(`got ${data} from WebSocket`);
  });
}

beforeDestroy() {
  this.$socket.off('socket');
}

Please refer to the official documentation for the supported instance methods/events.

$socketManager

The WebSocketManager instance has access to the following methods:-

connect(): void

Establishes WebSocket connection. It defines handlers for message, close and error events.

this.$socketManager.connect();

Invoked by the WebSocketManager class constructor function.

ready(): Promise<void>

Returns a promise that resolves straightaway if the WebSocket connection is open. Or else, waits until the open event is fired.

await this.$socketManager.ready();

Invoked by the send method.

send (message: string | Record<string, unknown>): Promise<void>

Waits for the WebSocket connection to be open if not already and transmits the data received.

await this.$socketManager.send({ event: "socket", data: "Hello world" });

close(code?: number | undefined, reason?: string | undefined): void

Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.

this.$socketManager.close();

The message event handler expects data received from the server as either a string or an object of the shape { event: string, data: string }.

// Data received of the type string.
// Emits an event by the name `message`.
this.$socket.on("message", () => {});

// Data received as an object.
// Emits an event based on the value for the 'event' key.
// { event: "socket", data: "Hello world" }
this.$socket.on("socket", () => {});

The close event handler attempts reconnection for a close event that is not normal (connection close code other than 1000).

Development

  1. Clone this repository.
  2. Install dependencies using yarn install.
  3. Start development server using yarn dev.

License

MIT License

Comments
  • chore: merge url options

    chore: merge url options

    Description

    This PR aims at unifying the development and production WebSocket connection URLs into a single option and other improvements.

    Type of change

    • [x] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [x] This change requires a documentation update

    Changes in this PR

    • Remove urlForDev and urlForProd options.
    • Add url option.
    • Specify WebSocket URL via runtime config with websocket key.
    // nuxt.config.js
    export default {
      // Via Runtime config
      publicRuntimeConfig: {
        websocket: {
          url: process.env.WEBSOCKET_URL
        }
      }
    };
    
    • Update docs to reflect the changes.
    • Update test suite.
    • Update references websocket -> WebSocket.

    Checklist before merging

    • [x] Tests
    • [x] Code and Readme documentation

    Note to reviewers (Optional)

    As suggested by @shivam-deepsource

    opened by james-deepsource 1
  • docs: add additional steps for TypeScript projects

    docs: add additional steps for TypeScript projects

    Description

    This PR aims at adding additional steps required for TypeScript projects to the docs.

    Type of change

    • [x] Docs update.

    Changes in this PR

    • Add a new section under Setup with the title TypeScript as part of the docs.
    opened by james-deepsource 0
  • docs: add compatibility note

    docs: add compatibility note

    Description

    The module is only compatible with Nuxt v2 at the moment. This PR aims at adding this information to the docs.

    Type of change

    • [x] Docs update.
    opened by james-deepsource 0
  • fix: resolve path to templates within the module source

    fix: resolve path to templates within the module source

    Description

    Specify the full path to templates via require.resolve().

    Type of change

    • [x] Bug fix (non-breaking change which fixes an issue)

    Changes in this PR

    • Specify the context while resolving to templates.

    Checklist before merging

    • [x] Tests
    opened by james-deepsource 0
  • chore: prevent injecting plugins if URL is not supplied

    chore: prevent injecting plugins if URL is not supplied

    Description

    Conditionally inject plugins based on the URL availability via options/runtime config.

    Type of change

    • [x] Breaking change (fix or feature that would cause existing functionality to not work as expected)

    Changes in this PR

    • Update example project nuxt.config.js to supply WebSocket connection URL.
    • Remove default value for WebSocket connection URL.
    • Conditionally inject plugins based on URL availability.
    • Notify the user if the URL isn't supplied.

    Checklist before merging

    • [x] Tests
    opened by james-deepsource 0
  • build: update lock file

    build: update lock file

    Description

    This PR updates caniuse-lite version in yarn.lock. More information about why the update is necessary: Browsers Data Updating.

    Changes in this PR

    Update yarn.lock.

    opened by james-deepsource 0
  • fix(example): prevent reconnecting after closing the connection

    fix(example): prevent reconnecting after closing the connection

    Description

    The close method invocation without any arguments resulted in a code of 1005 -> No status received. This PR aims at preventing the reconnect behavior on closing the connection with a code other than 1000.

    • Specify the close code as 1000 -> normal close event.
    • Disable the send button while the connection is closed.

    https://user-images.githubusercontent.com/87924230/157421238-2cc4d381-efd8-4524-ba87-ad2d2290427d.mov

    opened by james-deepsource 0
  • Add .deepsource.toml

    Add .deepsource.toml

    This pull request adds a .deepsource.toml.

    Merging it will successfully integrate DeepSource with this repository. On every subsequent pull request, it will run analysis and report any issues that need to be fixed. Good work!

    opened by deepsource-autofix[bot] 0
  • chore: update example and other improvements

    chore: update example and other improvements

    • Add close method.
    • Update example project.
    • Update docs.
    • Supply emitter as an arg while instantiating the WebSocketManager class.

    Preview

    https://user-images.githubusercontent.com/87924230/156514724-94b7def3-4afe-4c63-922b-d06ab4ac9d73.mov

    opened by james-deepsource 0
  • feat: update options and other improvements

    feat: update options and other improvements

    • Updates to options:-
      • Supply dev/prod URL's via urlForDev and urlForProd in module options and webSocketUrlForDev and webSocketUrlForProd in public runtime config.
      • Supply reconnect interval via reconnectInterval in module options.
    • Remove emitter argument for WebSocketManager class constructor.
    • Update test suite (rewrite in TS).
    • Add JSDoc comments.

    Usage

    // nuxt.config.js
    export default {
      // Via Runtime config
      // Takes priority over options
      publicRuntimeConfig: {
        webSocketUrlForDev: process.env.WEBSOCKET_URL_FOR_DEV,
        webSocketUrlForProd: process.env.WEBSOCKET_URL_FOR_PROD
      },
      // Via module options
      websocket: {
        reconnectInterval: 2000,
        urlForDev: '<url>',
        urlForProd: '<url>'
      }
    }
    
    
    opened by james-deepsource 0
  • fix: module implementation

    fix: module implementation

    • Use the addTemplate method to render the WebSocketManager template.
    • Remove defu and upath dependencies.
    • Ignore the CI jobs aimed at running tests and collecting coverage reports for the time being (will add tests as a follow-up).
    opened by james-deepsource 0
  • Bug: i find socket connect twice , and server get twice regsiter request

    Bug: i find socket connect twice , and server get twice regsiter request

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    What version of the module are you facing this issue on?

    all

    Please specify the Nuxt.js version

    2.15.8

    A link (CodeSandbox) that reproduces this error or a GitHub repository

    No response

    Current Behavior

    server get twice register request,like as: image

    i find code func construction use socket.connect and func connect use again . image

    if this is bug.i wish bigwigs can optimization it

    Expected Behavior

    No response

    Steps To Reproduce

    No response

    Checklist

    • [X] I have tested with the latest module version and the issue still occurs
    • [X] I have searched the issue tracker and this issue hasn't been reported yet
    opened by brcmask7 1
  • TypeError: can't access property

    TypeError: can't access property "send" of undefined

    resim

        async mounted() {
          const OPCODES = {
            INFO: 0,
            HELLO: 1,
            INIT: 2,
            HEARTBEAT: 3,
          };
          this.$socket.$on("message", ({ data }) => {
            const JSONdata = JSON.parse(data);
            if(JSONdata.op == OPCODES.HELLO)  {
              this.$socketManager.send(
              JSON.stringify({
                op: OPCODES.INIT,
                d: {
                    subscribe_to_id: "539843855567028227",
                }
              })
              )
            setInterval(function() { //HERE IS LINE 402
            this.$socketManager.send( 
                JSON.stringify({
                  op: OPCODES.HEARTBEAT,
                })
            )
            , JSONdata.d.heartbeat_interval})
            }else if(JSONdata.op == OPCODES.INFO){
            const colors = {
              online: "#57F287",
              idle: "#faa61a",
              dnd: "#ED4245",
              offline: "#99aab5"
            };
            if(JSONdata.t == "INIT_STATE"){
              const u = JSONdata.d;
    
              document.getElementById("platform").className = `text-[15px] font-bold text-[${colors[u.discord_status]}]`
            }
            }
          })
         },
    
    opened by falsisdev 0
  • Add a max retry count for websocket

    Add a max retry count for websocket

    Is your feature request related to a problem? Please describe.

    In case the socket server is not available, the library keeps retrying indefinitely we can add a max retry count to limit it

    Describe the solution you'd like to see

    Adding a max retry count as an option available to the user, with the default being infitie

    Describe alternatives you've considered

    None

    Additional context

    None

    opened by shivam-deepsource 0
Releases(v1.0.0)
  • v1.0.0(Mar 14, 2022)

    A tiny Nuxt.js module for WebSocket interactions.

    What's Changed

    • fix: module implementation by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/1
    • feat: update options and other improvements by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/3
    • docs: add API and usage information by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/4
    • Add .deepsource.toml by @deepsource-autofix in https://github.com/deepsourcelabs/nuxt-websocket/pull/6
    • chore: update DeepSource config by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/9
    • chore: update metadata by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/10
    • chore: update example and other improvements by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/5
    • test: increase coverage by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/11
    • fix(example): prevent reconnecting after closing the connection by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/13
    • build: update lock file by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/15
    • chore: update templates by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/14
    • chore: add code owners by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/17
    • chore: merge url options by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/16
    • chore: prevent injecting plugins if URL is not supplied by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/19
    • chore: bump version by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/20
    • fix: resolve path to templates within the module source by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/22
    • feat: add community health files by @shivam-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/21
    • docs: add compatibility note by @james-deepsource in https://github.com/deepsourcelabs/nuxt-websocket/pull/23

    Full Changelog: https://github.com/deepsourcelabs/nuxt-websocket/commits/v1.0.0

    Source code(tar.gz)
    Source code(zip)
Owner
DeepSource
Automated code reviews for developers and engineering teams.
DeepSource
A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

WebSocket Client & Server Implementation for Node Overview This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and

Brian McKelvey 3.6k Dec 30, 2022
WebSocket emulation - Node.js server

SockJS-node SockJS for enterprise Available as part of the Tidelift Subscription. The maintainers of SockJS and thousands of other packages are workin

SockJS 2.1k Dec 29, 2022
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

ws: a Node.js WebSocket library ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Passes the quit

WebSockets 19.2k Jan 4, 2023
Standards-compliant WebSocket client and server

faye-websocket This is a general-purpose WebSocket implementation extracted from the Faye project. It provides classes for easily building WebSocket s

null 588 Dec 23, 2022
Lightweight WebSocket lib with socket.io-like event handling, requests, and channels

ws-wrapper Lightweight and isomorphic Web Socket lib with socket.io-like event handling, Promise-based requests, and channels. What? Much like Socket.

Blake Miner 70 Dec 23, 2022
The cutest little WebSocket wrapper! 🧦

Sockette The cutest little WebSocket wrapper! ?? Sockette is a tiny (367 bytes) wrapper around WebSocket that will automatically reconnect if the conn

Luke Edwards 2.4k Jan 2, 2023
A Develop Tool to Test WebSocket, Socket.IO, Stomp, Bayeux, HTTP, TCP, UDP, WebRTC, DNS API.

A Develop Tool to Test WebSocket, Socket.IO, Stomp, Bayeux, HTTP, TCP, UDP, WebRTC, DNS API.

York Yao 24 Sep 6, 2022
WebSocket cat

WebSocket cat

WebSockets 1.6k Jan 2, 2023
How to build a chat using Lambda + WebSocket + API Gateway? (nodejs)

Description Source code for the lambda function from the screencast How to build a chat using Lambda + WebSocket + API Gateway? (nodejs) The reactjs c

Alex 21 Dec 28, 2022
Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js

CHAT-APP-WEBSOCKET Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js Obs o intuito deste projeto não é o fronten

Vinicius dos Santos Rodrigues 4 Jul 14, 2022
A websocket-based reverse shell for XSS attacks.

CrossSiteShell A javascript/nodejs "reverse shell" that makes it easier to interact with the victim's browser during XSS attacks. Usage Run the follow

Rafael 13 Oct 7, 2022
Um bot feito utilizando a API baileys em WebSocket para o Whatsapp Multi-Devices.

Informação ?? O BaileysBot foi feito utilzando a API Baileys Caso encontre algum BUG, faça um Novo Issue! Requisitos ?? NodeJS Git Instalação ?? Para

null 12 Dec 3, 2022
This Repository implements an Authenticated Websocket Server built in Node Js along ws library.

websockets-authentication-server This Repository implements an Authenticated Websocket Server built in Node Js along ws library. Features Authenticate

M.Abdullah Ch 7 May 5, 2023
Localtunnel module for Nuxt to allow remote/external access to your Nuxt development server.

Nuxt Localtunnel A Nuxt module for automatically running localtunnnel to externally expose your development instance of Nuxt to the outside world. All

null 14 Sep 7, 2022
it is websocket-store for using easily websocket

Socket-Store It is Websocket Store How to use 1. Install # npm npm install socket-store # yarn yarn add socket-store 2. Create MessageHandler and

nerdchanii 4 Sep 13, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
🌉 Experience Nuxt 3 features on existing Nuxt 2 projects

?? Nuxt Bridge Experience Nuxt 3 features on existing Nuxt 2 projects. Bridge is a forward-compatibility layer that allows you to experience many of t

Nuxt 180 Jan 5, 2023
A node.js module for websocket server and client

Nodejs Websocket A nodejs module for websocket server and client How to use it Install with npm install nodejs-websocket or put all files in a folder

Guilherme Souza 719 Dec 13, 2022