Home > Back-end >  Sending Enum Value with spaces using Prisma and MySQL
Sending Enum Value with spaces using Prisma and MySQL

Time:08-20

I am going to try my best to explain this issue...

I am working on building a request tracker App in NextJS using Prisma as the ORM and MySQL as the Database.

I am wanting to be able to send the Status to the Database without having to add the Underscores into it.

Is this possible?

Here is my Prisma Schema

generator client {
  provider = "prisma-client-js"
  binaryTargets = ["native", "darwin"]
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model requests {
  id                Int                    @id @default(autoincrement())
  project_id        String                 @db.VarChar(255)
  request_type      requests_request_type?
  name              String?                @db.VarChar(255)
  account_name      String?                @db.VarChar(255)
  legacy_org        requests_legacy_org?
  total_hours_spent Int?
  status            requests_status?
  updated_on        DateTime?              @default(now()) @db.DateTime(0)
  comment           String?                @db.Text
}

enum requests_request_type {
  Rem
  Add_on    @map("Add on")
  New_Logo  @map("New Logo")
  Migration
}

enum requests_legacy_org {
  CSC
  ES
}

enum requests_status {
  To_be_Started                  @map("To be Started")
  Work_in_Progress               @map("Work in Progress")
  Awaiting_Customer_Confirmation @map("Awaiting Customer Confirmation")
  Completed
}

This function creates the entry in the Database

import type {NextApiRequest, NextApiResponse} from 'next';
import prisma from '../../../../lib/prisma';

export default async function handle(
    req: NextApiRequest,
    res: NextApiResponse
) {
    const {name, projectID, accountName, status, requestType, totalHours} =
        req.body;
    const result = await prisma.requests.create({
        data: {
            name: name,
            project_id: projectID,
            account_name: accountName,
            status: status,
            request_type: requestType,
            total_hours_spent: totalHours,
        },
    });
    res.json(result);
}

This is my page to add the request

import React, {useState} from 'react';
import Router from 'next/router';

const AddRequest = () => {
    const [name, setName] = useState('');
    const [projectID, setProjectID] = useState('');
    const [accountName, setAccountName] = useState('');
    const [status, setStatus] = useState('To_be_Started');
    const [requestType, setRequestType] = useState('');
    const [totalHours, setTotalHours] = useState(0);

    const submitData = async (e: React.SyntheticEvent) => {
        e.preventDefault();
        try {
            const data = {
                name,
                projectID,
                accountName,
                status,
                requestType,
                totalHours,
            };
            await fetch('/api/requests/add', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data),
            });
            await Router.push('/requests');
        } catch (error) {
            console.log(error);
        }
    };
    return (
        <>
            <div className="container flex-auto">
                <form onSubmit={submitData}>
                    <h1 className="text-3xl">New Request</h1>
                    <div className="text-center grid grid-cols-2 gap-3">
                        <input
                            className="border border-black"
                            type="text"
                            placeholder="Name"
                            value={name}
                            onChange={(e) => {
                                setName(e.target.value);
                            }}
                        />
                        <input
                            className="border border-black"
                            type="text"
                            placeholder="Project ID"
                            onChange={(e) => {
                                setProjectID(e.target.value);
                            }}
                            value={projectID}
                        />
                        <input
                            className="border border-black"
                            type="text"
                            placeholder="Account Name"
                            onChange={(e) => {
                                setAccountName(e.target.value);
                            }}
                            value={accountName}
                        />
                        <input
                            className="border border-black"
                            type="text"
                            placeholder="Request Type"
                            onChange={(e) => {
                                setRequestType(e.target.value);
                            }}
                            value={requestType}
                        />
                        <button
                            className="border border-black bg-red-100"
                            disabled={!name || !projectID}
                            type="submit">
                            Create
                        </button>
                    </div>
                </form>
            </div>
        </>
    );
};
export default AddRequest;

CodePudding user response:

Enum Identifiers having embedded spaces are not supported yet.

We have a Feature Request for adding support to allow arbitrary enum values here: #4954. Please feel free to add a comment to the Feature Request so that we can prioritise it.

For this enum:

enum requests_status {
  To_be_Started                  @map("To be Started")
  Work_in_Progress               @map("Work in Progress")
  Awaiting_Customer_Confirmation @map("Awaiting Customer Confirmation")
  Completed
}

The generated types for now would be:

export const requests_status: {
  To_be_Started: 'To_be_Started',
  Work_in_Progress: 'Work_in_Progress',
  Awaiting_Customer_Confirmation: 'Awaiting_Customer_Confirmation',
  Completed: 'Completed'
};

The @map only applies to the schema and right at query time.

  • Related