I need to save the order into an Orders table, and the products ordered into a line_items table that is a one to many relation; one order can have many line_items (products ordered).
这听起来完全合理,除了使用牛津逗号:)
There are over 100 key-value pairs sent by the webhook
我不确定我是否确切地理解这是什么,或者它在这个过程中的用途。
也就是说,在您的模型中有一个具有JSON值的单一属性,然后将其作为JSON检索并使用,而不是尝试手动说明每个属性,这可能会有所帮助?
这确实取决于您的用例以及您将如何使用数据,但我认为如果格式发生变化,您可能会遇到问题,而如果只是将其作为JSON对象存储和解析,则不会出现问题?
Also, where would I put the code that maps the JSON to the model parameters
在v0.12.x中,查看
Services
.
在v1中,服务仍将工作,但将此逻辑移入
Helpers
可能是一个不错的选择,但似乎
custom model method
那会更好。
以下是代码的简短版本:
var newOrder = req.allParams();
newLine_items = {};
_.forEach(newOrder.line_items, function(line_item) {
newLine_items.push(line_item);
});
以下是您的逻辑:
var newOrder = req.allParams();
// Store the order
Order
.create(newOrders)
.exec(function (err, result) {
if (err) // handle the error
var newLine_items = {};
_.forEach(newOrder.line_items, function(line_item) {
// Add the order id for association
line_item.order_id = result.id;
// Add the new line item with the orders id
newLine_items.push(line_item);
});
// Store the orders line items
LineItems
.create(newLine_items)
.exec(function (err, result) {
if (err) // handle the error
// Handle success
});
});
以及订单模型中的生命周期回调:
beforeCreate: function (values, cb) {
delete(values.line_items);
cb();
}
但你真的应该看看蓝鸟的承诺,因为第一版sails中的模型方法有选择加入支持,这有助于否定我的例子中开始的末日金字塔,这也是你想要避免的:P