2

I have created my rest application in Loopback 4 and now I want to implement socket in it. Is there any way to do so in RestApplication?

export class MyApplication extends BootMixin(
    ServiceMixin(RepositoryMixin(RestApplication)),
) {

    constructor(
        options: ApplicationConfig = {}
    ) {
        super(options);
    }

    ....

    async start() {
        await super.start();

        const io = socketio(this.restServer);
        io.on('connection', (socket: any) => {
            console.log('connected');
        });

    }
}

const io = socketio(this.restServer); isn't working for me

2 Answers2

2

Here is a Official Loopback 4 example with socket.io integration. This example is created to explore how to expose Websocket (socket.io) endpoints in conjunction with LoopBack controllers.

https://github.com/raymondfeng/loopback4-example-websocket

Manish Balodia
  • 1,863
  • 2
  • 23
  • 37
  • 4
    the example you mentioned is implemented using HttpServer class, but my application using RestApplication class and restServer, so I am unable to use it in my current project. – Muhammad Ali Shahzad Jul 26 '19 at 22:07
1

I have created my rest application in Loopback 4 and now I want to implement socket in it.

What is your demand? After Customer A successfully calls a REST API, and the result of this call will be sent to the specified client via websocket?

You can created both rest server and websocket server at the same time in application.ts (how to creat websocket server). Then you can create Interceptor to send message via websocket after each controller method is called.

Zhikai Xiong
  • 357
  • 2
  • 9