count.ts47 lines · main
| 1 | import { paths } from 'api-types' |
| 2 | import { NextApiRequest, NextApiResponse } from 'next' |
| 3 | |
| 4 | import apiWrapper from '@/lib/api/apiWrapper' |
| 5 | import { getSnippets } from '@/lib/api/snippets.utils' |
| 6 | |
| 7 | const wrappedHandler = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler) |
| 8 | |
| 9 | async function handler(req: NextApiRequest, res: NextApiResponse) { |
| 10 | const { method } = req |
| 11 | |
| 12 | switch (method) { |
| 13 | case 'GET': |
| 14 | return handleGetAll(req, res) |
| 15 | default: |
| 16 | res.setHeader('Allow', ['GET']) |
| 17 | res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } }) |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | type GetRequestData = paths['/platform/projects/{ref}/content/count']['get']['parameters']['query'] |
| 22 | |
| 23 | const handleGetAll = async (req: NextApiRequest, res: NextApiResponse) => { |
| 24 | const params = req.query as GetRequestData |
| 25 | |
| 26 | try { |
| 27 | const { snippets } = await getSnippets({ |
| 28 | searchTerm: params?.name, |
| 29 | }) |
| 30 | if (params?.name) { |
| 31 | return res.status(200).json({ |
| 32 | count: snippets.length, |
| 33 | }) |
| 34 | } else { |
| 35 | return res.status(200).json({ |
| 36 | shared: snippets.filter((s) => s.visibility === 'project').length, |
| 37 | favorites: snippets.filter((s) => s.favorite).length, |
| 38 | private: snippets.filter((s) => s.visibility === 'user').length, |
| 39 | }) |
| 40 | } |
| 41 | } catch (error: any) { |
| 42 | console.error('Error fetching snippets:', error) |
| 43 | return res.status(500).json({ message: error?.message ?? 'Failed to get count' }) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | export default wrappedHandler |