async create(ctx) {
const data = ctx.request.body;
const requester = ctx.state.user;
const storeID = data.store
try {
if (!storeID) {
// If the requester does not provide store, return 403 Forbidden
return { error: "To create a product you must provide a storeID as param", status: 403 };
}
// Retrieve the current store data
const store = await strapi.entityService.findOne("api::store.store", storeID, {
populate: "deep"
});
if (!store) {
throw new Error(`Store with id ${storeID} not found`);
}
// Check if the requester is authorized to create products for that store
if (!requester || !store.storeKeeper || store.storeKeeper.id !== requester.id) {
// If the requester is not associated with the store, return 403 Forbidden
return { error: "You are not authorized to create products for this store", status: 403 };
}
// This Section Generates Product SKU
let SKU = '';
while (true) {
SKU = 'AFR-P' + generateAlphaNumeric(10);
const productsWithSKU = await strapi.entityService.findMany('api::product.product', {
filters: {
SKU: SKU,
},
});
if (productsWithSKU.length === 0) {
break;
}
}
const productCategory = await getProductCategory(strapi, data?.productCategory);
// This Section createsthe products
const createdProduct = await strapi.entityService.create(
"api::product.product",
{
data: {
...data,
images: data.images?.map((id) => ({ id })),
SKU,
product_category: productCategory,
discount: {
"percentageDiscount": data.discount,
"discount": parseInt(data.discount, 10) > 0
},
...(data.status !== "draft" && { publishedAt: new Date() })
}
}
);
return { status: 200, message: `Product with ID - ${createdProduct.id} was successfully created` };
} catch (error) {
error?.details?.errors?.map((e) => {
console.log(e)
})
console.error(`Error creating Product: ${error.message}`);
throw new Error(`Failed to create Product: ${error.message}`);
}
},
I wrote a custom create service as above. It works fine. I now want to have a new feature where users can save drafts of incomplete products that they would want to come back to.
Please I need help