Client guide
Installation
npm install @jcbuisson/express-x-client socket.io-client
Example
import io from 'socket.io-client'
import expressXClient from '@jcbuisson/express-x-client'
const socket = io({ debug: true })
const app = expressXClient(socket)
const user = await app.service('user').findUnique({
where: {
id: 22,
},
})
app.service('user').on('create', (user) => {
console.log('CREATE USER event', user)
})
...
Configuration
Creation options
path: '/myapp-socket-io/', // default: '/socket-io/'
transports: ["websocket"],
reconnectionDelay: 1000,
reconnectionDelayMax: 10000,
extraHeaders: {
"bearer-token": "mytoken"
},
debug: true
Service options
timeout (integer)
An exception is thrown if a service request doesn't get an answer after timeout
; default: 20000 ms
app.service(name, { timeout: 10000 })
volatile (boolean)
When volatile
option is set, a service request isn't buffered if connection is down - it will simply not be emitted. Default: false
Handling exceptions
When an exception occurs during a service method execution on the server, the error is sent back to the client.
try {
const { userId } = await app.service('auth').login(email, password)
...
} catch(err) {
if (err === 'wrong-credentials') {
...
}
}
Publish-subscribe
Service events callbacks
When an service event is sent by the server, the client can set a callback. In the following example, the callback is executed when the client receives a 'create' event from the 'User' service. Its only argument is the data returned by the method called - here the created User.
app.service('user').on('create', (createdUser) => {
...
})
Application event callbacks
When an application event is sent by the server, the client can set a callback with app.on()
. In the following example, the callback is executed whenever the application-wide event 'expireAt' is sent to the client
app.on('expireAt', (date) => {
...
})