import { rejectionErrors } from "../errors"
import sendError, { API } from "./sendError"

async function getUserFromBody<T>(context: API<T>) {
  const body = JSON.parse(context.req.body)
  if (
    typeof body !== "object" ||
    !body ||
    !("username" in body) ||
    typeof body.username !== "string"
  )
    throw sendError(context, rejectionErrors.noUsername)
  const { username } = body
  if (!("password" in body) || typeof body.password !== "string")
    throw sendError(context, rejectionErrors.noPassword)
  const { password } = body

  return { username, password }
}

export default getUserFromBody
