【问题标题】:Nodejs sequelize reader/writer async actionsNodejs 续集读取器/写入器异步操作
【发布时间】:2021-11-07 18:41:52
【问题描述】:

我正在寻找 nodejs 上的异步操作的解决方案 -> sequelize (mysql)

我有一个接收消息的端点(webhook),并执行以下操作:

[1]

sequelize.query(查找消息是否存在...)

[2]

如果 [1] 不存在,则 conversationsModel.create(....) 并返回 'X' 否则返回 'Y'(不创建对象)

而我的经验是,我的读者/作家之间就像一场“竞赛”。

我发现一些参考资料说“事务”在这种情况下可能会有所帮助,但如果我们不在同一个请求上下文中(不同的传入 API 请求) - 它是否应该有所帮助?

** 请注意,对于“读取”操作,我使用的是内联查询:

SELECT xxx FROM conversations where context="yyy" AND phoneNumber=:phoneNumber AND createdAt LIKE :time,`

对于“写”动作,我使用了 sequelize 模型:

await conversationsModel.create({phoneNumber: to.phoneNumber,context: "team",displayName: "xxx",externalId,message,type: "media",});

你们能建议一个合适的解决方案吗?

提前致谢。

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    这看起来像是在sequelize 中使用.upsert 静态方法的一个很好的例子(请参阅the docs here)。这里是 a link 到手册。在sequelize 中的Conversation 模型上必须有一个唯一键或主键才能使用此方法。例如,假设contextphoneNumber 属性上有一个唯一索引。那么 upsert 语句会是这样的,

    let [instance, created] = await ConversationsModel.upsert({
            phoneNumber: to.phoneNumber,
            context: "team",
            displayName: "xxx",
            externalId,
            message,
            type: "media",
        })
    
    if (created) {
        // New conversation instance was created in database...
        //  Access the instance here...
    } else {
        // New conversation instance was not created in database,
        //  but the existing instance was updated...
        //  Access the instance here...
    }
    

    重要提示: 正如上面的链接所指出的,created 的值仅在使用 MySQLMSSQL 时设置为非空值,但由于原始问题状态 MySQL 正在使用中,这个解决方案应该足够了。

    免责声明:如果 select 语句和 insert/update 语句确实在单独的 api 请求中完成,那么如果不让这两个请求与以某种方式彼此。也许客户端程序可能有某种机制在不同的请求之间进行通信,以避免以某种方式通过数据库进行通信。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 2015-10-30
      • 2016-10-29
      • 1970-01-01
      相关资源
      最近更新 更多