我有一些来自以前版本的 Strapi 的代码可以运行,而 beta 版本的 Controller 有很大不同。添加了多部分/ sanitizer 样板,并且某些内容发生了变化。不明白如何集成我的订单对象和条纹费用。
这是添加的样板:
module.exports = {
async create(ctx) {
// New Boilerplate added with Strapi Beta - how to integrate this with custom stuff below?
let entity;
if (ctx.is('multipart')) {
const { data, files } = parseMultipartData(ctx);
entity = await service.create(data, { files });
} else {
entity = await service.create(ctx.request.body);
}
return sanitizeEntity(entity, { model });
}
}
这是我的自定义代码( Controller 名称是 Order.js)
const { address, amount, products, postalCode, token, city } = ctx.request.body;
// Send charge to Stripe
const charge = await stripe.charges.create({
amount: amount * 100,
currency: 'usd',
description: `Order ${new Date(Date.now())} - User ${ctx.state.user.id}`,
source: token
});
// Create order in database
const order = await strapi.services.order.add({
user: ctx.state.user.id,
address,
amount,
products,
postalCode,
city
});
看起来我会将我的代码添加到 if 语句的第二部分,因为它不是多部分,但如果“实体”是 Strapi 需要的真实变量名或占位符变量(我重命名为“order”),则不是用户代码有效在 Alpha 中很好,但阅读 Strapi 文档,没有解释如何使用此结构与“实体”、{model} 和“数据”变量。
最佳答案
在以前版本的 Strapi 中,要将文件上传到新条目,您必须首先创建条目,然后上传图像并指定要链接该图像的条目。 现在,通过多部分,您可以在发送条目属性的同时发送图像。
现在关于您的用例,在您的案例中,service.
必须替换为 strapi.api.order.service.order
。
我同意文档不清楚!我会立即更新。
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
module.exports = {
async create(ctx) {
// New Boilerplate added with Strapi Beta - how to integrate this with custom stuff below?
let entity;
if (ctx.is('multipart')) {
const { data, files } = parseMultipartData(ctx);
entity = await strapi.api.order.services.order.create(data, { files });
} else {
const { address, amount, products, postalCode, token, city } = ctx.request.body;
// Send charge to Stripe
const charge = await stripe.charges.create({
amount: amount * 100,
currency: 'usd',
description: `Order ${new Date(Date.now())} - User ${ctx.state.user.id}`,
source: token
});
entity = await strapi.api.order.services.order.create({
user: ctx.state.user,
address,
amount,
products,
postalCode,
city
});
}
return sanitizeEntity(entity, { model: strapi.query('order').model });
}
}
关于javascript - Strapi Beta (3.0) 的自定义 Controller 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434316/