Tweaks to DB Files


Uncategorized

Updated Jan 4th, 2022

import { MongoClient } from "mongodb"
import { Question } from "../pages/index"
import type { NextApiRequest, NextApiResponse } from "next"

export async function connectToDatabase() {
  const uri = process.env.MONGODB_URI
  const client = await MongoClient.connect(uri!)

  return client
} // end connectToDatabase

export async function addQuestionDocument(client: MongoClient, document: Question) {
  const db = client.db()
  await db.collection("questions").insertOne(document)
}

export async function getQuestions(client: MongoClient) {
  const db = client.db()

  const results = await db
    .collection("questions")
    .aggregate([{ $sample: { size: 5 } }])
    .toArray()

  // removes _id from each question object
  const cleanedResults = results.map((questionObj: any) => {
    return {
      category: questionObj.category,
      type: questionObj.type,
      difficulty: questionObj.difficulty,
      question: questionObj.question,
      correct_answer: questionObj.correct_answer,
      incorrect_answers: questionObj.incorrect_answers
    }
  })

  client.close()

  const data = cleanedResults
  return data
}

export async function getQuestionsTwo(client: MongoClient, req: NextApiRequest) {
  const db = client.db()

  let amount: any = 5
  if (req.query.amount) {
    amount = parseInt(`${req.query.amount}`)
  }

  let category: string | string[]
  let categoryMatch = {}
  if (req.query.category) {
    category = req.query.category
    categoryMatch = { category: `${category}` }
  }

  const results = await db
    .collection("questions")
    .aggregate([{ $match: categoryMatch }, { $sample: { size: amount } }])
    .toArray()

  // removes _id from each question object
  const cleanedResults = results.map((questionObj: any) => {
    return {
      category: questionObj.category,
      type: questionObj.type,
      difficulty: questionObj.difficulty,
      question: questionObj.question,
      correct_answer: questionObj.correct_answer,
      incorrect_answers: questionObj.incorrect_answers
    }
  })

  client.close()

  const data = cleanedResults
  return data
}
import type { NextApiRequest, NextApiResponse } from "next"
import { getSession } from "next-auth/client"
import { connectToDatabase, addQuestionDocument, getQuestionsTwo } from "../../lib/db"

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === "POST") {
    // api-route protection from non-logged in users
    const session = await getSession({ req: req })
    if (!session) {
      res.status(401).json({ message: "Not authenticated" })
      return
    }

    // add server-side validation to prevent empty fields
    /*  if (newQuestion.category === "") {
      res.status(422).json({ message: "Invalid category. " })
    } */

    let client
    //error handling for connection to database
    try {
      client = await connectToDatabase()
    } catch (error) {
      res.status(500).json({ message: "There was an error connecting to the data." })
      return
    }

    //error handling for adding a new question
    try {
      await addQuestionDocument(client, {
        category: req.body.category,
        type: req.body.type,
        difficulty: req.body.difficulty,
        question: req.body.question,
        correct_answer: req.body.correct_answer,
        incorrect_answers: req.body.incorrect_answers
      })
      if (client) client.close()
    } catch (error) {
      res.status(500).json({ message: "Inserting data failed." })
      return
    }

    if (client) client.close()

    res.status(201).json({ message: "New question added!" })
  } // end post request

  if (req.method === "GET") {
    let client
    //error handling for connection to database
    try {
      client = await connectToDatabase()
    } catch (error) {
      res.status(500).json({ message: "There was an error connecting to the data." })
      return
    }

    // error handling for getting questions
    let cleanedResults
    try {
      cleanedResults = await getQuestionsTwo(client, req)
      if (client) client.close()
    } catch (error) {
      res.status(500).json({ message: "There was an error retrieving the questions" })
      return
    }

    client.close()

    res.status(200).json(cleanedResults)
  } // end GET request
} // end handler function


Top