直接在 Strapi 中使用书架时如何清理数据

How to sanitize data when using bookshelf directly in Strapi

由于 Strapi 似乎还不支持 OR 子句(https://github.com/strapi/strapi/issues/3194),我直接使用 Bookshelf,如:

const result = await strapi.query('friendship')
    .find({
        where: { user1: 1 },
        orWhere: { user2: 1 }
    })
    .fetchAll()

现在,通常您可以使用以下方法清理数据:

sanitizeEntity(entities, { model: strapi.models.friendship });

但这在这里行不通,因为我们基本上离开了 Strapi 的抽象,对吧?我还能通过将数据与模型或类似的东西进行比较来以某种方式清理数据吗?

由于您是直接访问书架,因此需要将结果集转换为 json。 Bookshelf 有一个 toJSON 帮助程序。 sanitizeEntity顾名思义,只能用在单个实体结果上。

const { sanitizeEntity } = require('strapi-utils');

module.exports = {
  async findFriends(){
    const entities = await strapi.query('friendship')
        .find({
            where: { user1: 1 },
            orWhere: { user2: 1 }
        })
        .fetchAll()
        .then(results => results.toJSON());

    return entities.map(entity => sanitizeEntity( { 
      model: strapi.models.friendship 
    } ))
  }
}

如果你想深入挖掘,你可以检查你的 node_modules 这个文件 node_modules/strapi/packages/strapi-connector-bookshelf/lib/queries.js。这就是 strapi 为您的模型设置 find 服务助手的方式。

  function find(params, populate, { transacting } = {}) {
    const filters = convertRestQueryParams(params);

    return model
      .query(buildQuery({ model, filters }))
      .fetchAll({
        withRelated: populate,
        transacting,
      })
      .then(results => results.toJSON());
  }