我有一个外部API将数据发布到我的项目。我想将项目移至Strapi。但是,当然,该外部POST的形状与Strapi模型的数据创建端点不匹配。它也是XML格式,因此我需要首先对其进行解析,并且需要对传入的数据进行突变以更好地与模型匹配。应该怎么去。
我的想法包括:
strapi.query('myModel').create({})
我很想听听熟悉Strapi的人的一些想法和概念。
所以是这个问题的答案。
您将必须使用此概念-https://strapi.io/documentation/3.0.0-beta.x/concepts/controllers.html#core-controllers
自定义create
控制器功能。
并且在函数开始时,您将必须检查ctx.request.body
的格式。
如果内容具有XML格式,在这种情况下,您将必须将其转换为JSON。
Path — api/**/controllers/**.js
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Create a record.
*
* @return {Object}
*/
async create(ctx) {
// if ctx.request.body is XML
// ctx.request.body = convertXMLtoJSON(ctx.request.body);
// you will have to find a code that convert XML to JSON
// and simply add id in this function
let entity;
if (ctx.is('multipart')) {
const { data, files } = parseMultipartData(ctx);
entity = await strapi.services.restaurant.create(data, { files });
} else {
entity = await strapi.services.restaurant.create(ctx.request.body);
}
return sanitizeEntity(entity, { model: strapi.models.restaurant });
},
};