#3.0: Best way to have Enum in a field?

6 messages · Page 1 of 1 (latest)

noble ruin
#

using Mongo db, so it seems like enumName has no effect :(

I want to have a field which is enum in the database, i thought "select" type is the natural choice, but it fails to create typescript type

{
name: 'resources',
type: 'array',
fields: [
{
name: 'fieldIndex',
type: 'number',
required: true,
},
{
name: 'EResource',
type: 'select',
options: enumToArray(EResources),
enumName: 'EResources',
required: true,
},
{
name: 'ETier',
type: 'select',
options: enumToArray(ETier),
enumName: 'ETier',
required: true,
},
],
required: true,
}

but when generate types i get:
resources: {
fieldIndex: number;
EResource: '0' | '1' | '2' | '3';
ETier: '0' | '20' | '40' | '60' | '80' | '100';
id?: string | null;
}[];

what would be the option instead of select that could link the enum type correctly so i dont have to map my objects when reading and writing?

here are enums mentioned above:
export enum EResources {
None = 0,
Pebbles = 1,
Wood = 2,
Water = 3,
}
export enum ETier {
'NONE' = 0,
't1' = 20,
't2' = 40,
't3' = 60,
't4' = 80,
't5' = 100,
}

green relic
#

do you mean that you want the generated type to be enum from select? i don't think Payload has this ability, i also haven't seen for a while someone uses enums 😄 though it could be easy to add support for it https://github.com/bcherny/json-schema-to-typescript/issues/60#issuecomment-275895336

The question here would be also, for example this line
'NONE' = 0, - if 0 is the value, then how'd you define NONE?

And also outside of this, stored value of a select field is always string, you cannot have number like 0 | 20 | 40

noble ruin
#

i dont know, enum just seemed like right tool for a job... what would you suggest instead for a case like this?

regarding "NONE", i would like to store "0"
and yes, i understand numbers wont work with mongo, i would be willing to compromise on that and make enum use string for values

green relic
#

what about something like this? so you store it as a string, but then you can access to the transformed value by ETier[selectValue]

const selectOptions = ['NONE', 't1', 't2', 't3', 't4', 't5'];

type Generated = {
  ETier: 'NONE' | 't1' | 't2' | 't3' | 't4' | 't5';
};

export const ETier: Record<Generated['ETier'], number> = {
  NONE: 0,
  t1: 20,
  t2: 40,
  t3: 60,
  t4: 80,
  t5: 100,
};
winged juniperBOT