Rest API Framework

WebSocket and Subscriptions

Overview

Below are all files and directories in the REST API Framework related to this section

├── src/
│   ├── pages/
│   │   └── posts.js
│   └── hooks/
│       └── useSubscription.js
└── server/
    ├── utils/
    │   └── websocket.js
    └── index.js

Basic Usage

Server

Go to the /server/utils/websocket.js file, you will see there are 2 classes

WSServer: a wrapper class of WS Native Server, will create a WebSocket Server on init and also implement event-based behavior like Socket.io using EventEmitter

WSServer once created will have 2 exposed methods: on() method to add listeners to a specific event emitted by the client and handleUpgrade() to pass to the server upgrade request handler

SubscriptionWSServer: extended WSServer class, add a listener to subscribe event by default and have an exposed method called notify() to emit notify events to the clients

The subscribe event is expecting 3 fields from the received data sent by the client:

  • tags: a list of database operations the client wants to watch. Valid values are: ["create", "update", "delete"]
  • collection: name of the collection the client wants to watch for changes
  • recordId: the id of a specific record the client wants to watch

The MongoDB ODM is already hooking into the database CRUD operations, so when createOne, updateOne or deleteOne operations are executed, the notify() method will be called and a notify event will be emitted and sent to the clients.

Client

On the API Framework client side, there is a built-in React Hook called useSubscription that allows you to send a subscribe event to the server on loaded and listen to a notify event from the server to trigger a refetch() function passed in.

// Calling signature
useSubscription({ refetch, collection, tags, recordId })
  • refetch: the function will be called when receiving notify event from the server. This is usually the mutate function returned from useQuery hook.
  • collection, tags and recordId: data to be sent to the server, you can see the subscribe event in the server section above for more information.
Previous
API Endpoints and Controllers