Skip to content
This repository has been archived by the owner on Jan 16, 2024. It is now read-only.

Commit

Permalink
feat(api:search): add endpoint /api/search/[searchStr]
Browse files Browse the repository at this point in the history
  ## what
  - add endpoint `/api/search/[searchStr]`

  ## how
  - check if the `searchStr` is valid (using zod schema)
    - must be a string length of 1
  - if `searchStr` is not valid, return 400
  - if username exists, add SearchResult to an array
    - title: `User: [username]`
    - href: `/users/[username]`
  - if problem number exists, add SearchResult to an array
    - title: `Problem: [problem number] [problem title]`
    - href: `/problems/[problem number]`
  - return response using the SearchResult array

  ## why
  - this endpoint will be used to search for a problem number or a
    username

  ## where
  - ./src/app/api/search/[searchStr]/route.ts

  ## usage
  • Loading branch information
Clumsy-Coder committed Jan 16, 2024
1 parent 3b38b93 commit bf15e83
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions src/app/api/search/[searchStr]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { NextResponse } from "next/server";
import { z } from "zod";

import { searchSchema as schema } from "@/schema";
import {
uhuntProblemNumUrl,
uhuntUsername2UidUrl,
} from "@/utils/constants";
import { Problem, SearchResultType } from "@/types";

type getParamsType = {
params: z.infer<typeof schema>;
};

export const GET = async(_request: Request, {params}: getParamsType) => {
const { searchStr } = params;
const responseData: SearchResultType[] = []

// validate params
const schemaResponse = await schema.safeParseAsync(params);
if (!schemaResponse.success) {
const message = {
message: schemaResponse.error.issues[0].message,
};

return NextResponse.json(message, {
status: 400,
});
}

//----------------------------------------------------------------------------------------------//

// fetch username ID
const usernameUrl = uhuntUsername2UidUrl(searchStr);
const usernameResponse = await fetch(usernameUrl);
const usernameData: number = await usernameResponse.json();

// add search result to array if user exists
if (usernameData !== 0) {
responseData.push({
title: `User: '${searchStr}'`,
href: `/users/${searchStr}`
})
}

//----------------------------------------------------------------------------------------------//

// fetch problem number
const problemNumUrl = uhuntProblemNumUrl(searchStr)
const problemNumResponse = await fetch(problemNumUrl)
const problemNumData: Problem = await problemNumResponse.json()

if(Object.entries(problemNumData).length !== 0) {
const {num, title} = problemNumData
responseData.push({
title: `Problem: ${num} '${title}'`,
href: `/problems/${num}`
})
}

return Response.json(responseData)

}

0 comments on commit bf15e83

Please sign in to comment.