问题
I have some code from the previous version of Strapi that works, and the beta version of controllers is much different. There is multipart / santization boilerplate added and something has changed. Do not understand how to integrate my order object and stripe charge.
Here is the boilerplate added:
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 });
}
}
Here is my custom code (The controller name is 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
});
It looks like I would add my code to the second part of the if statement since it's not multipart, but not user if "entity" is a real variable name Strapi needs or a placeholder variable I rename to "order" Code works fine in Alpha, but read the Strapi docs and there is no explanation to how to use this structure with "entity", {model} and "data" variables.
回答1:
In the previous version of Strapi, to upload a file to a new entry you had to first, create your entry and two, upload the image and specify the entry you want to link this image. Now with the multipart, you can send your image at the same time as your entry attributes.
Now about your use-case, service.
has to be replaced by strapi.api.order.service.order
in your case.
I agree the doc is not clear! I will update that right now.
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 });
}
}
来源:https://stackoverflow.com/questions/58434316/custom-controller-code-for-strapi-beta-3-0