Is there a way to store the type defined with enum...
# orm-help
h
Is there a way to store the type defined with enum as array in client
Copy code
enum Gender{
M
F
Other
}
I want this in the client as
Copy code
const genders = ["M","F","Other"]
without hardcoding.
1
i
Why does it need to be stored in the database? Seems like an enumeration that belongs in code
h
So I have student model //schema
Copy code
model student {
gender : Gender!
}
enum Gender { M F Other}
In the frontend I want to use it the gender them , Basically update profile I will be providing a dropdown to select the gender. That's why I need to store them in an array client side. I am looking If there is a way to do it rather hard coding it.
r
Enums are one of the top-level exports of the Prisma Client. If you have a
Gender
enum you can grab it (in object form) with
import { Gender } from "@prisma/client"
and if you really need it in an array form you can use any method like
Object.values
to get an array of the values.
i
Still doesn't seem like a problem you need to solve. You've probably got a front end that is controlling the valid values you can store. I'd just store gender as an integer value, 0=F,1=M, anything else is other
then just define the enum in code
r
@Ian Ray Having a single source of truth for such valid values is far preferable to defining the values in multiple places. Imagine in the future you create a mobile app and add additional gender options but forget to update the options on the web frontend. This case would be automatically handled by defining the enum in Prisma and generating the valid values from that enum. This is one of the main reasons I use Prisma in the first place - avoiding needing to maintain multiple copies of schema definitions, which is always error prone.
1
🙌 1
i
that sounds like a good solution too 🙂
of course, you've still got an API to pass through, where you've got to define types, ie how you serialize gender as an input
h
Thanks @Roryl. and yes having single source of truth is why I am wanted in the first place
b
Doing the same with nexus:
Copy code
import { enumType, extendType } from 'nexus';
import { Gender } from '@necom/lib/prismaAdmin';

export const GenderEnum = enumType({
    name: 'Gender',
    members: Gender,
});

export const getGenderEnum = extendType({
    type: 'AllEnum',
    definition: (t) => {
        t.list.field('Gender', {
            type: 'Gender',
            resolve: () => {
                return Object.values(Gender);
            },
        });
    },
});
AllEnum Type is used by a Query as result. The client can request all enums needed with the Prisma definition. So database -> backend -> client use the same values.