|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import { animals, type Animal } from "@/configs/data/animals"; |
| 3 | + |
| 4 | +/** |
| 5 | + * @swagger |
| 6 | + * /api/animals/random: |
| 7 | + * get: |
| 8 | + * summary: Get random animal information |
| 9 | + * description: Retrieve information about a random animal from our collection |
| 10 | + * tags: |
| 11 | + * - Animals |
| 12 | + * parameters: |
| 13 | + * - in: query |
| 14 | + * name: type |
| 15 | + * schema: |
| 16 | + * type: string |
| 17 | + * enum: [mammal, bird, reptile, fish, amphibian] |
| 18 | + * description: Filter by animal type (optional) |
| 19 | + * responses: |
| 20 | + * 200: |
| 21 | + * description: Successfully retrieved random animal |
| 22 | + * content: |
| 23 | + * application/json: |
| 24 | + * schema: |
| 25 | + * type: object |
| 26 | + * properties: |
| 27 | + * error: |
| 28 | + * type: null |
| 29 | + * data: |
| 30 | + * type: object |
| 31 | + * properties: |
| 32 | + * status: |
| 33 | + * type: number |
| 34 | + * example: 200 |
| 35 | + * payload: |
| 36 | + * type: object |
| 37 | + * properties: |
| 38 | + * id: |
| 39 | + * type: string |
| 40 | + * example: "lion" |
| 41 | + * name: |
| 42 | + * type: string |
| 43 | + * example: "Lion" |
| 44 | + * type: |
| 45 | + * type: string |
| 46 | + * example: "mammal" |
| 47 | + * image: |
| 48 | + * type: string |
| 49 | + * example: "https://source.unsplash.com/featured/?lion" |
| 50 | + * description: |
| 51 | + * type: string |
| 52 | + * example: "The king of the jungle, known for its majestic mane" |
| 53 | + * 400: |
| 54 | + * description: Bad request - Invalid animal type |
| 55 | + */ |
| 56 | +export async function GET(request: NextRequest) { |
| 57 | + try { |
| 58 | + const searchParams = request.nextUrl.searchParams; |
| 59 | + const type = searchParams.get("type") as Animal["type"] | null; |
| 60 | + |
| 61 | + let filteredAnimals = animals; |
| 62 | + if (type) { |
| 63 | + filteredAnimals = animals.filter((animal) => animal.type === type); |
| 64 | + if (filteredAnimals.length === 0) { |
| 65 | + return NextResponse.json( |
| 66 | + { error: { message: `No animals found of type: ${type}` }, data: null }, |
| 67 | + { status: 400 } |
| 68 | + ); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + const randomIndex = Math.floor(Math.random() * filteredAnimals.length); |
| 73 | + const animal = filteredAnimals[randomIndex]; |
| 74 | + |
| 75 | + return NextResponse.json({ |
| 76 | + error: null, |
| 77 | + data: { |
| 78 | + status: 200, |
| 79 | + payload: animal |
| 80 | + } |
| 81 | + }); |
| 82 | + } catch (error) { |
| 83 | + const errorMessage = error instanceof Error ? error.message : "Internal Server Error"; |
| 84 | + return NextResponse.json({ error: { message: errorMessage }, data: null }, { status: 500 }); |
| 85 | + } |
| 86 | +} |
0 commit comments