Prisma, Next JS api route prisma.create giving me a bad request

Viewed 530

I have the following prisma schema

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

generator client {
  provider = "prisma-client-js"
}

model FormInput {
  id    String @id @default(uuid())
  name  String
  type  String
  order String
}

and jsx react nextjs file

import Head from "next/head";
import styles from "../styles/Home.module.css";
import { PrismaClient } from "@prisma/client";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { v4 as cuid } from "uuid";
import styled from "styled-components";

const prisma = new PrismaClient();

const FormStyles = styled.form`
  display: grid;
  grid-template-columns: 350px 1fr;
  label {
    //background: red;
  }
  input,
  select {
    //background: aqua;
    border: 1px solid grey;
    border-top: 0;
    border-right: 0;
    border-left: 0;
  }
  input[type="button"] {
    background: green;
    border: none;
    border-radius: 30px;
    color: #fff;
    padding: 15px;
    width: 200px;
    margin: 0 0 25px auto;
    &:hover {
      cursor: pointer;
    }
  }
  button {
    background: lightgray;
    padding: 15px;
    border: none;
    &:hover {
      cursor: pointer;
    }
  }
`;

const GridStyles = styled.div`
  display: grid;
  grid-row-gap: 5px;
  padding: 15px 0;
  width: 600px;
  margin: 0 auto 0 0;
  div {
    display: grid;
    grid-template-columns: 100px 1fr;
    align-items: center;
  }
`;

export async function getServerSideProps() {
  const formInputs = await prisma.formInput.findMany();
  return {
    props: {
      initialFormInputs: formInputs,
    },
  };
}

export default function Home({ initialFormInputs }) {
  const blankFormInput = {
    name: "test",
    id: cuid(),
    type: "text",
  };
  const [formState, setFormState] = useState([blankFormInput]);

  const [inputs, setFormInputs] = useState(initialFormInputs);

  const test = inputs?.reduce((obj, item, idx) => {
    return { ...obj, [`name-${item.id}`]: item.name };
  }, {});

  const { register, handleSubmit, errors } = useForm({ defaultValues: test });

  const onSubmit = async (data) => {
    let hmm = formState.map((ok) => {
      var name = data[`name-${ok.id}`];
      var type = data[`type-${ok.id}`];
      var boogie = { [ok.id]: { name: name, type: type } };
      return boogie;
    });

    const response = await fetch("/api/formSave", {
      method: "POST",
      body: JSON.stringify(hmm),
    });

    if (!response.ok) {
      throw new Error(response.statusText);
    }
  };

  const addInput = async () => {
    const blanktext = {
      name: "Test",
      id: cuid(),
      type: "text",
      order: 0,
    };
    setFormState([...formState, { ...blanktext }]);
    const response = await fetch("/api/addInput", {
      method: "POST",
      body: JSON.stringify(blanktext),
    });

    if (!response.ok) {
      throw new Error(response.statusText);
    }

    console.log(response);
  };

  return (
    <>
      <FormStyles onSubmit={handleSubmit(onSubmit)}>
        <h1>Create Your Form Input Fields</h1>
        <div>
          {formState.map((val, idx) => {
            const nameId = `name-${val.id}`;
            const typeId = `type-${val.id}`;
            return (
              <div key={val.id}>
                {val.type === "text" && (
                  <GridStyles>
                    <div>
                      <label htmlFor={nameId}>Input Name</label>

                      <input
                        type="text"
                        name={nameId}
                        id={nameId}
                        className={val.type}
                        ref={register()}
                      />
                    </div>
                    <div>
                      <label htmlFor={typeId}>Input Type</label>

                      <select name={typeId} ref={register}>
                        <option value="text">text</option>
                        <option value=" image"> image</option>
                      </select>
                    </div>
                  </GridStyles>
                )}
              </div>
            );
          })}
          <GridStyles>
            <input type="button" value="Add Form Input" onClick={addInput} />
            <button type="submit">Save Form</button>
          </GridStyles>
        </div>
      </FormStyles>
    </>
  );
}

I am sending the following object to this api route

{
  name: 'Test',
  id: 'e5b85d84-f21c-4e71-9921-98eb2cdedb3a',
  type: 'text',
  order: 0
}

api route

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default async (req, res) => {
  if (req.method !== "POST") {
    return res.status(405).json({ message: "Method not allowed" });
  }

  try {
    const input = JSON.parse(req.body);
    console.log(input);
    const savedContact = await prisma.formInput.create({ data: input });
    res.status(200).json({ message: "hello" });
  } catch (err) {
    res.status(400).json({ message: "Something went wrong" });
  }
};

I keep getting a bad request I have tried a varying degree of prisma.formInputCreate, and others. This happens when I click the add input button. I am expecting it to add a row to the DB. Thanks for any help

0 Answers
Related