Skip to main content

Enums

Enums can be configured in three different ways.

strings

This is the default behavior for enum types because it's easy and not complicated. It's configured as follows:

  Rainbow: EnumType({
hideFromGraphQL: true,
values: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'],
})

This adds a string column of type rainbow to the table and enforces when saving that field that the only acceptable values are the provided values.

Since the recommended values for GraphQL Enums are all caps, it transforms the provided values into a graphql enum type with all caps.

postgres enum type

Postgres has support for built in enum type which may be preferred to using strings. This provides database validation/enforcement that only valid values can be input as opposed to leaving it to the ent-or data layer.

These types can't be changed easily so we don't currently support changing this.

Configured as follows:

  Rainbow: EnumType({
hideFromGraphQL: true,
values: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'],
createEnumType: true, // magic line
}),

results in the following db change:

ent-test=# \dT+ rainbow
List of data types
Schema | Name | Internal name | Size | Elements | Owner | Access privileges | Description
--------+---------+---------------+------+----------+-------+-------------------+-------------
public | rainbow | rainbow | 4 | red +| ola | |
| | | | orange +| | |
| | | | yellow +| | |
| | | | green +| | |
| | | | blue +| | |
| | | | indigo +| | |
| | | | violet | | |
(1 row)

lookup tables

src/schema/request_status_schema.ts
const RequestStatusSchema = new EntSchema({
fields: {
status: StringType({
primaryKey: true,
}),
},

enumTable: true;

dbRows: [
{
status: "OPEN",
},
{
status: "PENDING_FULFILLMENT",
},
{
status: "CLOSED",
},
],
});
export default RequestStatusSchema;

The schema above generates the following: database table named request_statuses with 3 rows: OPEN, PENDING_FULFILLMENT, CLOSED

ent-test=# \d+ request_statuses;
Table "public.request_statuses"
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
--------+------+-----------+----------+---------+----------+--------------+-------------
status | text | | not null | | extended | |
Indexes:
"request_statuses_status_pkey" PRIMARY KEY, btree (status)

ent-test=# select * from request_statuses;
status
---------------------
OPEN
PENDING_FULFILLMENT
CLOSED
(3 rows)

ent-test=#

TypeScript enum RequestStatus:

export enum RequestStatus {
OPEN = "OPEN",
PENDING_FULFILLMENT = "PENDING_FULFILLMENT",
CLOSED = "CLOSED",
}

and the following GraphQL enum

enum RequestStatus {
OPEN
PENDING_FULFILLMENT
CLOSED
}

To reference this enum in a different schema, use as follows:

  Status: EnumType({
foreignKey: ["RequestStatus", "status"],
})