t8101
t8101

Reputation: 395

How to get enums in prisma client?

can I get a list of enums values of a model on the client-side like for select option?

Sample enum

enum user_type {
    superadmin
    admin
    user
}

I want this as a select-option on the client-side. How can I get them as JSON data?

Upvotes: 39

Views: 66444

Answers (3)

Re9iNee
Re9iNee

Reputation: 620

And in case anyone still couldn't access to their enums, even though your schema has been generated.

It's because prisma won't generate enum types if you don't use it in other table columns. "For GraphQL reasons"

see this issue

How did I solve it?!

  • Since I hate having duplicates in my code, I've created another sooner. and put that enum column in there. generated my schema prisma generate and I'm good to go.

Upvotes: 0

ben
ben

Reputation: 480

When you generate Prisma Client, it generates TypeScript interfaces for your models and enum types.

you can do

import { PrismaClient, user_type } from '@prisma/client'

and this will give you the user_type types declarations

Upvotes: 6

Tasin Ishmam
Tasin Ishmam

Reputation: 7218

You can access the user_type enum in your application code like this:

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

let foo: user_type = "superadmin";
// use like any other type/enum

How you plan to connect this to the client-side or send it there is up to you. Typically Prisma types reside in the server-side of your code, not the client-side, so it might be difficult to import prisma types in your client code directly.

This is how Prisma defines the user_type enum under the hood.

// file: node_modules/.prisma/client/index.d.ts
export const user_type: {
  superadmin: 'superadmin',
  admin: 'admin',
  user: 'user'
};

You could just copy and paste this into your client-side code if you like.

Upvotes: 61

Related Questions