Enums should not be sorted alphabetically by default
Problem
When you use the codegen tool to generate your types, enums are by default ordered alphabetically. I think this might be ok for the most cases, but for example if you have an enum of months like this:
enum Month {
JANUARY
FEBRUARY
MARCH
APRIL
MAY
JUNE
JULY
AUGUST
SEPTEMBER
OCTOBER
NOVEMBER
DECEMBER
}
And you want to use them in a dropdown or address them by index, it is pretty useless to have it sorted by codegen like this;
export enum Month {
APRIL = "APRIL",
AUGUST = "AUGUST",
DECEMBER = "DECEMBER",
FEBRUARY = "FEBRUARY",
JULY = "JULY",
JUNE = "JUNE",
JANUARY = "JANUARY",
MARCH = "MARCH",
MAY = "MAY",
NOVEMBER = "NOVEMBER",
OCTOBER = "OCTOBER",
SEPTEMBER = "SEPTEMBER",
}
Expectation
My suggestion would be to reflect the type definition in the schema by default and implement a possibility to set custom sorting via the config file. So that the outcome will be by default:
export enum Month {
JANUARY = "JANUARY",
FEBRUARY = "FEBRUARY",
MARCH = "MARCH",
APRIL = "APRIL",
MAY = "MAY",
JUNE = "JUNE",
JULY = "JULY",
AUGUST = "AUGUST",
SEPTEMBER = "SEPTEMBER",
OCTOBER = "OCTOBER",
NOVEMBER = "NOVEMBER",
DECEMBER = "DECEMBER",
}
Workaround
As a (dirty) workaround for anyone who is also experiencing this issue you can open npm/node_modules/apollo/node_modules/apollo-codegen-core/lib/utilities/graphql.js from your global npm directory and perform the following replacement:
4: function sortEnumValues(values) {
5: //return values.sort((a, b) => a.value < b.value ? -1 : a.value > b.value ? 1 : 0);
6: return values;
7: }
But keep in mind that this will only work until you make the next update, or this is solved ;-)
I was surprised to see this too. Having enum keys generated in the same order as they are defined in the schema would seem more intuitive to me personally.
Using Object.keys(MyEnum) to feed forms is great for lazy devs :)
If I wanted this to be sorted, I could easily add a sort function myself.
having the same issue
I have this enum :
export enum LongPayment {
twoMonth = 1,
threeMonth,
fourMonth,
fiveMonth,
sixMonth,
sevenMonth,
eightMonth,
nineMonth,
tenMonth,
elevenMonth,
twelveMonth,
eighteenMonth,
twentyFourMonth
}
and get this output:
export enum LongPayment {
eightMonth = "eightMonth",
eighteenMonth = "eighteenMonth",
elevenMonth = "elevenMonth",
fiveMonth = "fiveMonth",
fourMonth = "fourMonth",
nineMonth = "nineMonth",
sevenMonth = "sevenMonth",
sixMonth = "sixMonth",
tenMonth = "tenMonth",
threeMonth = "threeMonth",
twelveMonth = "twelveMonth",
twentyFourMonth = "twentyFourMonth",
twoMonth = "twoMonth",
}
Same issue, wonder why te do this. for instance I cannot get the value by using index:
MyEnum.values()[index] 😕
Having problems with Enums values being shuffled because of this...
Having problems with Enums values being shuffled because of this...
and is there update so its not alpabeticaly sorted anymore that you have it shuffled? I would love to have that feature tho