|
1 | 1 | import { factories } from '@strapi/strapi' |
2 | 2 |
|
3 | | -export default factories.createCoreController('api::post.post') |
| 3 | +interface PostFilters { |
| 4 | + type?: { $contains?: string; $containsi?: string } |
| 5 | + [key: string]: unknown |
| 6 | +} |
| 7 | + |
| 8 | +interface PostQuery { |
| 9 | + filters?: PostFilters |
| 10 | + pagination?: { page?: number; pageSize?: number } |
| 11 | + [key: string]: unknown |
| 12 | +} |
| 13 | + |
| 14 | +export default factories.createCoreController('api::post.post', ({ strapi }) => ({ |
| 15 | + async find(ctx) { |
| 16 | + const query = ctx.query as PostQuery |
| 17 | + |
| 18 | + const { type, ...restFilters } = query.filters ?? {} |
| 19 | + |
| 20 | + // Support both $contains and $containsi from the frontend |
| 21 | + const typeFilter = type?.$contains ?? type?.$containsi |
| 22 | + |
| 23 | + if (!typeFilter) return super.find(ctx) |
| 24 | + |
| 25 | + // strapi-plugin-multi-select stores `type` as jsonb in PostgreSQL. |
| 26 | + // LIKE/ILIKE fail on jsonb ("operator does not exist: jsonb ~~ unknown"). |
| 27 | + // We resolve matching IDs via a raw ::text cast, then hand off to super.find() |
| 28 | + // so that populate, pagination, fields, and sort all work normally. |
| 29 | + // |
| 30 | + // Hyphens in the search term are replaced with underscores because _ is a |
| 31 | + // single-char wildcard in LIKE patterns, making %crypto_pro% match both |
| 32 | + // "Crypto_pro" and "crypto-pro" regardless of separator convention. |
| 33 | + const pattern = `%${String(typeFilter).replace(/-/g, '_')}%` |
| 34 | + |
| 35 | + const rows = await strapi.db |
| 36 | + .connection('posts') |
| 37 | + .whereNotNull('published_at') |
| 38 | + .whereRaw('type::text ILIKE ?', [pattern]) |
| 39 | + .select<{ id: number }[]>('id') |
| 40 | + |
| 41 | + if (rows.length === 0) { |
| 42 | + return ctx.send({ |
| 43 | + data: [], |
| 44 | + meta: { pagination: { page: 1, pageSize: query.pagination?.pageSize ?? 25, pageCount: 0, total: 0 } }, |
| 45 | + }) |
| 46 | + } |
| 47 | + |
| 48 | + ctx.query = { |
| 49 | + ...query, |
| 50 | + filters: { |
| 51 | + ...restFilters, |
| 52 | + id: { $in: rows.map((r) => r.id) }, |
| 53 | + }, |
| 54 | + } |
| 55 | + |
| 56 | + return super.find(ctx) |
| 57 | + }, |
| 58 | +})) |
0 commit comments