| 15 | }); |
| 16 | |
| 17 | async function handler(req: NextApiRequest, res: NextApiResponse) { |
| 18 | if (req.method === 'OPTIONS') { |
| 19 | return preflight(req, res, ['GET']); |
| 20 | } |
| 21 | cors(req, res); |
| 22 | |
| 23 | const parsed = schema.safeParse(req.query); |
| 24 | if (!parsed.success) { |
| 25 | return res.status(400).send(JSON.stringify(parsed.error)); |
| 26 | } |
| 27 | |
| 28 | const { query, accountId, limit, offset = 0 } = parsed.data; |
| 29 | |
| 30 | const account = await prisma.accounts.findUnique({ |
| 31 | where: { id: accountId }, |
| 32 | select: { anonymizeUsers: true, anonymize: true, type: true }, |
| 33 | }); |
| 34 | |
| 35 | if (!account) { |
| 36 | return res.status(404).json({}); |
| 37 | } |
| 38 | if (account.type === AccountType.PRIVATE) { |
| 39 | const permissions = await PermissionsService.get({ |
| 40 | request: req, |
| 41 | response: res, |
| 42 | params: { |
| 43 | communityId: accountId, |
| 44 | }, |
| 45 | }); |
| 46 | |
| 47 | if (!permissions.access) { |
| 48 | return res.status(403).json({}); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // Search messages |
| 53 | const messagesResult = await prisma.$queryRaw<{ id: string }[]>`SELECT m."id", |
| 54 | ts_rank(textsearchable_index_col,websearch_to_tsquery('english', ${query})) AS rank |
| 55 | FROM "public"."messages" as m |
| 56 | INNER JOIN "public"."channels" AS c ON (c."id") = (m."channelId") |
| 57 | WHERE |
| 58 | c."accountId" = ${accountId} |
| 59 | AND m."id" IS NOT NULL |
| 60 | and m."threadId" is not null |
| 61 | and c.hidden is false |
| 62 | and c.type = 'PUBLIC' |
| 63 | AND textsearchable_index_col @@ websearch_to_tsquery('english', ${query}) |
| 64 | ORDER BY rank DESC |
| 65 | LIMIT ${Number(limit)} |
| 66 | OFFSET ${Number(offset)}`; |
| 67 | |
| 68 | const response = await prisma.messages |
| 69 | .findMany({ |
| 70 | where: { |
| 71 | id: { in: messagesResult.map((m) => m.id) }, |
| 72 | }, |
| 73 | include: { |
| 74 | author: true, |