【发布时间】:2020-10-28 22:43:07
【问题描述】:
我正在开发一个具有 Loopback Rest API 的反应应用程序。我正在尝试创建一个将文章数组作为参数的 post 方法。函数已创建,但它们不起作用。不幸的是,我不知道如何调试,我想看看我的调用是否进入了函数,如果是的话,对象/数组的外观如何。
在 remote-cart.js 中
Cart.addArticles = (id, articles, cb) => {
console.log(articles);
articles.map(article => {
let error;
if (article.qty <= 0) {
error = new Error('Quantity can\'t be negative or null!');
error.statusCode = 400;
error.code = 'cant_be_negative_or_null'.toUpperCase();
return cb(error);
}
Promise
.all([Cart.findById(id), Article.findById(article.articleId)])
.then((all) => {
const article = all[1];
if (!article) {
error = new Error('Article doesn\'t exist');
error.statusCode = 400;
error.code = 'Article_doesnt_exist'.toUpperCase();
cb(error);
}
const cart = all[0];
let articles = [];
if (cart.articles) {
// articles exist
articles = JSON.parse(cart.articles);
const articleIndex = _findIndex(articles, (item) =>
item.articleId === article.id);
if (articles[articleIndex]) {
const oldQty = articles[articleIndex].qty ?
articles[articleIndex].qty : 0;
const newQty = oldQty + article.qty;
articles[articleIndex].qty = newQty;
articles[articleIndex].total = calculateSubTotal(article, newQty);
} else {
articles.push({
articleId: article.articleId,
qty: article.qty,
total: calculateSubTotal(article, article.qty),
});
}
} else {
// articles doesn't exit
articles.push({
articleId: article.articleId,
qty: article.qty,
total: calculateSubTotal(article, article.qty),
});
}
cart.articles = JSON.stringify(articles);
cart.total = calculateTotal(articles);
return cart;
})
.then(cart => {
cart.save({}, (err, data) => {
if (err) {
return err;
}
cb(null, cart);
});
})
.catch(err => cb(err));
});
};
Cart.remoteMethod('addArticles', {
description: [
'Add or increase the quantity of any Article in cart',
' model instance by {{id}} from the data source',
],
accepts: [{
arg: 'id',
type: 'number',
required: true,
}, {
arg: 'articles',
type: 'array',
required: true,
}],
returns: [
{arg: 'id', type: 'number', root: true},
{arg: 'clientId', type: 'number', root: true},
{arg: 'articles', type: 'string', root: true},
{arg: 'total', type: 'number', root: true},
{arg: 'lines', type: 'array', root: true},
{arg: 'lineCount', type: 'number', root: true},
{arg: 'created_at', type: 'Date', root: true},
{arg: 'updated_at', type: 'Date', root: true},
],
http: {path: '/:id/add-articles', verb: 'post'},
});
【问题讨论】:
标签: reactjs react-redux loopback