|
| 1 | +export default async function handler(req, res) { |
| 2 | + if (req.method !== 'POST') { |
| 3 | + res.status(405).json({ error: 'Method Not Allowed' }); |
| 4 | + return; |
| 5 | + } |
| 6 | + |
| 7 | + try { |
| 8 | + const { indexUid } = req.query || {}; |
| 9 | + if (!indexUid) { |
| 10 | + res.status(400).json({ error: 'Missing indexUid' }); |
| 11 | + return; |
| 12 | + } |
| 13 | + |
| 14 | + const host = process.env.MEILI_HOST || process.env.NEXT_PUBLIC_MEILI_HOST || ''; |
| 15 | + const apiKey = process.env.MEILI_API_KEY || process.env.NEXT_PUBLIC_MEILI_API_KEY || ''; |
| 16 | + if (!host || !apiKey) { |
| 17 | + res.status(500).json({ error: 'Meilisearch host or API key not configured' }); |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + const userIdFromCookie = (() => { |
| 22 | + try { |
| 23 | + const cookie = req.headers['cookie'] || ''; |
| 24 | + const match = cookie.match(/(?:^|;\s*)msUserId=([^;]+)/); |
| 25 | + return match ? decodeURIComponent(match[1]) : undefined; |
| 26 | + } catch { |
| 27 | + return undefined; |
| 28 | + } |
| 29 | + })(); |
| 30 | + |
| 31 | + const url = new URL(`/indexes/${encodeURIComponent(indexUid)}/search`, host); |
| 32 | + const meiliRes = await fetch(url.toString(), { |
| 33 | + method: 'POST', |
| 34 | + headers: { |
| 35 | + 'Content-Type': 'application/json', |
| 36 | + 'Authorization': `Bearer ${apiKey}`, |
| 37 | + 'X-Meilisearch-Client': req.headers['x-meilisearch-client'] || 'StrapiDocs Proxy', |
| 38 | + ...(userIdFromCookie ? { 'X-MS-USER-ID': userIdFromCookie } : {}), |
| 39 | + }, |
| 40 | + body: JSON.stringify(req.body || {}), |
| 41 | + }); |
| 42 | + |
| 43 | + const data = await meiliRes.json(); |
| 44 | + res.status(meiliRes.status).json(data); |
| 45 | + } catch (e) { |
| 46 | + res.status(500).json({ error: e.message || 'Proxy error' }); |
| 47 | + } |
| 48 | +} |
| 49 | + |
0 commit comments