Sailsjs MVC将来自外部API的参数映射到多个模型

我需要创build一个Shopify订单数据库,以便我可以运行高级查询和销售报告,这是shopifypipe理员区域中不能完成的。 我正在build立在帆.12和MySQL。 Shopify允许您注册一个webhook,以便每次下订单时,都会为指定的URL创build一个POST,并将正文中的订单数据作为JSON。 订购的产品是作为POST中值之一的JSON对象的数组:

{ "id": 123456, "email": "jon@doe.ca", "created_at": "2017-01-10T14:26:25-05:00", ...//many more entires "line_items": [ { "id": 24361829895, "variant_id": 12345, "title": "T-Shirt", "quantity": 1, "price": "140.00", }, { "id": 44361829895, "variant_id": 42345, "title": "Hat", "quantity": 1, "price": "40.00", }, ] } 

我需要将订单保存到订单表中,并将订单保存到line_items表中,这是一对多的关系。 一个订单可以有很多line_items(产品订购)。 有超过100个键值对由webhook发送,我保存了所有的。 我创build了我定义数据types的两个模型,所以现在我有非常长的Order.js和Line_item.js文件,而且我正在使用

  line_items: { collection: 'line_item', via: 'order_id' }, 

在我的Order.js和

 order_id: { model: 'order' }, 

在我的Line_item.js模型中关联它们。 这是定义我的两个表的正确方法吗? 另外,我会在哪里放置将JSON映射到模型参数的代码? 如果我把这个代码放在控制器中,我是否需要input另外100行代码才能将每个json值映射到正确的参数。 我将如何保存到两个不同的模型/表格? 例如:

  var newOrder = {}; newOrder.id =req.param('id'); newOrder.email = req.param('email'); newOrder.name = req.param('name'); ...//over 100 lines more, then Order.create(newOrder, ...) var newLine_items = req.params('line_items'); //an array _.forEach(newLine_items, function(line_item){ var newLine_item = {}; newLine_item.id = line_item.id; newLine_item.order_id = newOrder.id; newLine_item.title = line_item.title; //etc for over 20 more lines, then Line_item.create(newLine_item, ...) }); 

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的forms检索和使用它,而不是试图手动计算每个属性,如果这是你在那里做的?

这实际上取决于你的用例,以及你将如何使用数据,但我认为如果格式改变你可能有问题,而不是如果它只是被存储和parsing为JSON对象?

Also, where would I put the code that maps the JSON to the model parameters

在v0.12.x中看看服务 。

在v1中,服务仍然可以工作,但是将这个逻辑转换为Helpers可能是一个不错的select,但是,看起来自定义模型方法会更好。

这里是你的代码的一个更短的版本:

 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 }); }); 

Order模型中的生命周期callback:

 beforeCreate: function (values, cb) { delete(values.line_items); cb(); } 

但是你真的应该看看蓝鸟的承诺,因为风帆版本之一的模型方法已经select支持它们,它有助于否定以我的例子开始的厄运金字塔,也是你想要避免的东西:P