使用 Sails.js 的事务 SQL [英] Transactional SQL with Sails.js
问题描述
所以我现在一直在使用 NodeJS/Express,我真的很想尝试使用完整的 JavaScript 堆栈重写一个相对较大的副项目,只是为了看看它是如何工作的.对于支持 Web 套接字的 REST API 的 NodeJS 后端,Sails.js 似乎是一个不错的选择,这正是我正在寻找的,但是我正在寻求解决的另一个问题,那就是 NodeJS 中的事务性 SQL.
So I have been playing with NodeJS/Express for a little with now and I would really like to try to rewrite a relatively large side project using a full JavaScript stack just to see how it will work. Sails.js seems to be a pretty good choice for a NodeJS backend for a REST API with support for web sockets which is exactly what I am looking for however is one more issue I am looking to resolve and that is transactional SQL within NodeJS.
我在 NodeJS 方面看到的大多数数据层/orms 在处理 MySQL 时似乎都不支持事务.Sails.js (Waterline) 提供的 ORM 似乎也不支持事务,这很奇怪,因为我见过提到它的地方,尽管这些评论已经很老了.Knex.js 支持事务,所以我想知道用这个替换 ORM is Sails.js 是否容易(或者如果 Sails.js 在核心框架中假设 Waterline).
Most data layer/orms I have seen on the NodeJS side of things don't seem to support transactions when dealing with MySQL. The ORM provided with Sails.js (Waterline) also does not seem to support transactions which is weird because I have seen places where is mentioned it did though those comments are quite old. Knex.js has support for transactions so I was wondering if it is easy to replace the ORM is Sails.js with this (or if Sails.js assumes Waterline in the core framework).
我还想知道除了 Bookshelf 之外是否有一个基于 Knex.js 构建的 ORM,因为我不喜欢 Backbones 模型/集合系统?
I was also wondering if there is an ORM built on top of Knex.js besides Bookshelf as I am not a fan of Backbones Model/Collection system?
推荐答案
您仍然可以直接使用 Model.query()
编写 SQL 查询.由于这是一个异步函数,您必须使用 promises 或 async
来重新序列化它.例如,使用 MySQL 适配器、async
和名为 User
的模型:
You can still write SQL queries directly using Model.query()
. Since this is an asynchronous function, you'll have to use promises or async
to reserialize it. For instance, using the MySQL adapter, async
, and a model called User
:
async.auto({
transaction: function(next){
User.query('BEGIN', next);
},
user: ['transaction', function(next) {
User.findOne(req.param('id')).exec(next);
}],
// other queries in the transaction
// ...
}, function(err, results) {
if (err) {
User.query('ROLLBACK', next);
return next(err);
}
User.query('COMMIT', next);
// final tasks
res.json(results.serialize);
});
这篇关于使用 Sails.js 的事务 SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!