WebSockets

If you want to use real-time features, WebSockets are the way to go. We generally recommend using this instead of HTTP connections if you plan to make frequent requests or want to use our pub/sub endpoints.

Please keep in mind that every payload from the server and client is expected to be JSON encoded.


Authenticated connection (Node.js)

      const WebSocket = require('ws')
const ws = new WebSocket('wss://api.nexushub.co/ws', {
  headers: {
    authorization: `bearer ${access_token}`
  }
})

    

For more information on how to get an access token, check out the authentication guide.

Ping/Pong

In order to keep your client alive, it has to respond to pings from the server. If no pong has been sent as a response within 45 seconds, the connection is terminated.

Ping handler

      ws.on('message', payload => {
  payload = JSON.parse(payload)

  if (typeof payload === 'string' && payload.startsWith('primus::ping::')) {
    ws.send(JSON.stringify(payload.replace('ping', 'pong')))
  }
})

    

RESTful requests

Making RESTful requests is fairly straightforward. Set a request id counter and send it alongside the request object. The response will then have the same id.

Depending on your WebSocket implementation, we recommend tracking all requests in an array that is checked in a single message event listener. The examples below create a listener for every request, which is not how you'd want to do things. We merely demonstrate things this way for the sake of clarity.

GET

      let requestIds = 1

// Request
const id = requestIds++
ws.send(JSON.stringify({
  action: 'GET',
  url: '/foo',
  id
}))

// Response
ws.on('message', payload => {
  payload = JSON.parse(payload)
  if (payload.id === id) {
    console.log(payload.body) // 'foo'
  }
})

    

POST

      let requestIds = 1

// Request
const id = requestIds++
ws.send(JSON.stringify({
  action: 'POST',
  url: '/post',
  body: { foo: 'bar' },
  id
}))

// Response
ws.on('message', payload => {
  payload = JSON.parse(payload)
  if (payload.id === id) {
    console.log(payload.body) // { foo: 'bar' }
  }
})

    

Pub/Sub

For real-time data, you'll want to subscribe to Pub/Sub endpoints. Their response format is usually the same as on a normal GET request.

Subscribe

      ws.send(JSON.stringify({
  action: 'SUBSCRIBE',
  room: '/warframe/v1/orders/opm'
}))

ws.on('message', payload => {
  payload = JSON.parse(payload)
  if (payload.room === '/warframe/v1/orders/opm') {
    console.log(payload.data) // Logs orders per minute every time a new order comes in.
  }
})

    

Unsubscribe

      ws.send(JSON.stringify({
  action: 'UNSUBSCRIBE',
  room: '/warframe/v1/orders/opm'
}))

    

Full setup

If you need an overview for a full setup with automated authentication and error handling, check out our implementation for cubic-client.

loading

Connected!