dongtuo3795 2016-04-27 00:45
浏览 56
已采纳

验证数据并将其保存到db for realtime app的正确方法

For example i build chat app based on laravel + node.js server.
What is the best idea for creating new message:

  1. Emit msg to server -> validate it and add it to db via node.js -> return msg to all users
  2. Make api in laravel for validation and db -> using ajax (i think this is not best idea)
  3. Make api in laravel for validation and db -> emit msg to server -> request in node.js to api in laravel -> return msg to all users
  4. Other?
  • 写回答

1条回答 默认 最新

  • douju1997 2016-04-27 01:47
    关注

    I would do like this:

    1 - Validate msg with Node.js and immediately broadcast when valid.

    You can make use of Node.js events and EventsEmitter and react to each new msg. Also with this approach you will be broadcasting the msg to all users as soon as valid.

    2 - Save validated msg to db calling a Laravel API trough Node.js

    Once your message has been broadcasted now you can save to db by calling a Laravel API inside your Node.js app.

    var events = require('events');
    var eventEmitter = new events.EventEmitter();
    
    function saveToDb() {
      // call to api here
    }
    
    function validate(msg) {
      //validate msg
      return valid;
    }
    
    
    eventEmitter.on('msgBroadcasted', saveToDb);
    eventEmitter.on('msgBroadcasted', anotherFunction);
    
    
    socket.on('new message', function (data) {
      if (!validate(data)) { return false }
    
      socket.broadcast.emit('new message', {
        username: socket.username,
        message: data
      });
      return eventEmitter.emit('msgBroadcasted');
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度