Sunday, 30 April 2017

Right way to implement file upload for WebSocket chat application

I have a chat application, backend is written with help of Socket.io (based on Node.js server), and client is pure vanilla JavaScript, with JWT token generation from PHP, chat loads all data on load from REST API written on PHP also, and i am stuck with file upload.

I have two variants, first is REST API, just send data with help of XMLHTTPRequest, and i already implemented this, it's a simple FormData POST to REST, it works fine, but i am not sure of "rightness" of this solution, because for now REST have only GET routes for simple users (there is admin routes also) and by design of my project, it's set to get data for user chat, and its looks not right for me to make POST route for them, but what worries me most is what i already have another mechanism/solution where user sending their messages, it is socket.io-node.js server, with all permission checks (does this user have permission to join this chat, send information to it, and so on), so REST will take part of Socket.io task. Also beside role distribution problem, REST solution is also a logic duplication, where all permission checks written on Node.js side, must be duplicated on PHP side. As a result i already started to rewrite file sending to Node.js via Socket.io. Socket.io from version 1 is accepting binary data, so it's was pretty easy, i just sending a File and Node.js gets Buffer, which is easily stored to filesystem like this

require('fs').writeFileSync(filePath, Buffer);

but here i have problem what i don't have upload progress, and most importantly despite all projects part are now perfectly distributed by their roles (client is sending data to socket.io, and reads from rest), and i have no role duplication, i am still not 100% sure i solved this problem right.

So question is, how and where would you send your files, in case of your chat application.



via Nerfair

No comments:

Post a Comment