|
| 1 | +import { Question, StatusBody, QuestionFullBody } from "./structs"; |
| 2 | + |
| 3 | +const questions: { [key: string]: Question } = { |
| 4 | + "0" : { |
| 5 | + "id": 0, |
| 6 | + "difficulty": 2, |
| 7 | + "title": "Two Sum", |
| 8 | + "description": "Given an array of integers, return indices of the two numbers such that they add up to a specific target.", |
| 9 | + "test_cases": { |
| 10 | + "[2, 7, 11, 15], 9" : "[0, 1]", |
| 11 | + "[3, 2, 4], 6" : "[1, 2]", |
| 12 | + "[3, 3], 6" : "[0, 1]" |
| 13 | + } |
| 14 | + }, |
| 15 | + "1" : { |
| 16 | + "id": 1, |
| 17 | + "difficulty": 1, |
| 18 | + "title": "Reverse Integer", |
| 19 | + "description": "Given a 32-bit signed integer, reverse digits of an integer.", |
| 20 | + "test_cases": { |
| 21 | + "123" : "321", |
| 22 | + "1" : "1", |
| 23 | + "22" : "22" |
| 24 | + } |
| 25 | + } |
| 26 | +}; |
| 27 | + |
| 28 | +export async function fetchQuestion(questionId: string): Promise<Question|StatusBody> { |
| 29 | + // remove this when services are up |
| 30 | + if (process.env.DEV_ENV === "dev") { |
| 31 | + return questions[questionId] === undefined |
| 32 | + ? {error: "Question not found", status: 404} |
| 33 | + : questions[questionId]; |
| 34 | + } |
| 35 | + try { |
| 36 | + const response = await fetch(`${process.env.NEXT_PUBLIC_QUESTION_SERVICE}/questions/solve/${questionId}`); |
| 37 | + if (!response.ok) { |
| 38 | + return { |
| 39 | + ...(await response.json()), |
| 40 | + status: response.status |
| 41 | + }; |
| 42 | + } |
| 43 | + return await response.json() as Question; |
| 44 | + } catch (err: any) { |
| 45 | + return { error: err.message, status: 0}; |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +export async function addQuestion(body: QuestionFullBody): Promise<StatusBody> { |
| 50 | + try { |
| 51 | + const response = await fetch( |
| 52 | + `${process.env.NEXT_PUBLIC_QUESTION_SERVICE}/questions`, |
| 53 | + { |
| 54 | + method: "POST", |
| 55 | + body: JSON.stringify(body).replace(/(\"difficulty\":)\"([1-3])\"/, `$1$2`), |
| 56 | + headers: { |
| 57 | + "Content-type": "application/json; charset=UTF-8" |
| 58 | + } |
| 59 | + } |
| 60 | + ); |
| 61 | + if (response.ok) { |
| 62 | + return { |
| 63 | + status: response.status |
| 64 | + }; |
| 65 | + } |
| 66 | + return { |
| 67 | + error: (await response.json())["Error adding question: "], |
| 68 | + status: response.status |
| 69 | + }; |
| 70 | + } catch (err: any) { |
| 71 | + return { error: err.message, status: 0}; |
| 72 | + } |
| 73 | +} |
0 commit comments