这也破坏了我们的管理。以中间件的形式创建了一个棘手的权宜之计解决方案,也许对其他人同时有用。
- 它将过滤器参数更改为 $containsi
- 它使用查询字符串作为结果前缀,这样它们就不会在客户端上被过滤掉
/src/middlewares/fix-search-middleware.js
const { prop, flow } = require("lodash/fp");
// Not pretty, but it seems to work and allows our content team to continue to work
module.exports = (config, { strapi }) => {
return async (context, next) => {
const isRelationSearch = context.request.url.startsWith(
"/content-manager/relations"
);
const hasQuery = !!context.query._q;
// Only run fix if we're searching a relation and there's a query
if (!isRelationSearch || !hasQuery) {
return await next();
}
// Update query to $containsi instead of $startsWith in:
// https://github.com/strapi/strapi/commit/b39586bf8d6885ecb23ecd22a9136a8675348d67
context.query._filter = "$containsi";
// Perform rest of middlewares and the actual query
await next();
// Update results to prefix mainField with the query string so it actually shows up and not filtered out client-side with "startsWith"
// https://github.com/strapi/design-system/blob/0c8968cd9b9c22ed565b17c8de9120e8b4779abc/packages/primitives/src/components/Combobox/Combobox.tsx#L970-L974
try {
const mainField = await getMainField(context, strapi);
context.response.body.results = context.response.body.results.map(
(r) => ({
...r,
[mainField]: `${context.query._q} ➡ ${r[mainField]}`,
})
);
} catch (error) {
console.error("Failed patching the search results");
console.error(error);
}
};
};
const getMainField = async (context, strapi) => {
// Exstracted from: https://github.com/strapi/strapi/blob/b39586bf8d6885ecb23ecd22a9136a8675348d67/packages/core/content-manager/server/controllers/relations.js
const { targetField, model } = context.params;
const modelSchema = strapi.getModel(model);
const isComponent = modelSchema.modelType === "component";
const modelConfig = isComponent
? await strapi
.plugin("content-manager")
.service("components")
.findConfiguration(modelSchema)
: await strapi
.plugin("content-manager")
.service("content-types")
.findConfiguration(modelSchema);
const mainField = flow(
prop(`metadatas.${targetField}.edit.mainField`),
(mainField) => mainField || "id"
)(modelConfig);
return mainField;
};
添加"global::fix-search-middleware",
到 的末尾/config/middlewares.js
。