Tips for maintaining enum order in graphql

In the server, I have defined an enum called BlocksType.

export enum BlocksType {
    TEXT = "TEXT",
    LINK = "LINK",
    GALLERY = "GALLERY",
    CONTACT = "CONTACT",
    EMAIL = "EMAIL",
    RESIDENCE = "RESIDENCE",
    SNS = "SNS",
}

The ordering of types is important, with TEXT being the first and SNS being the last. (This order must be maintained.)

However, when generated in the client through codegen, the enum appears in alphabetical order:

export enum BlocksType {
  CONTACT = "CONTACT",
  EMAIL = "EMAIL",
  GALLERY = "GALLERY",
  LINK = "LINK",
  RESIDENCE = "RESIDENCE",
  SNS = "SNS",
  TEXT = "TEXT",
}

This raises the question of how to maintain the same order as defined in the server on the client side.

Answer №1

Consider trying this approach

If you happen to be utilizing graphql-code-generator, a recommendation from this fellow contributor proposes opting for a Query structure to ensure data is presented in the correct sequence, as there's no guarantee that Object.values() will consistently maintain order.

In your particular scenario, something similar to the following can be implemented.

type Query {
  blockTypes: [BlockType!]!
}

The answer you've been seeking

Given the caveat regarding Object.values(), it may generally be safe (although not foolproof) to simply turn off sorting:

# codegen.yml
schema: "schema.graphql"
config:
  sort: false
...
// codegen.ts
export default {
  schema: 'schema.graphql',
  config: {
    ...
    sort: false,
  },
  ...
};

Remember that disabling sorting will impact the arrangement of all generated schemas and type files, but in my experience, this adjustment doesn't lead to any negative repercussions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript - Conditional Type and Optional Arguments

My component has various arguments that can be passed to it: interface Props { label: string; children?: React.ReactNode; withoutActions?: boolean; fieldKey?: KeyProperties; corporate: Corporate; } The withoutActions and fieldKey properties are ...

Challenges arise when attempting to share a theme across different repositories within a Storybook monorepo that utilizes

In my unique project setup, I have a singular repository containing atoms, molecules, and organisms along with storybooks to develop a custom components library. This library is based on MUI framework with a customized theme applied, all built with TypeScr ...

Ways to access configuration settings from a config.ts file during program execution

The contents of my config.ts file are shown below: import someConfig from './someConfigModel'; const config = { token: process.env.API_TOKEN, projectId: 'sample', buildId: process.env.BUILD_ID, }; export default config as someCo ...

The Angular Ngrx store function, store.select('selector name'), should ideally provide a list of Books but instead, it is returning a non-iterable list

Can someone help me troubleshoot this issue? It's my first time using state management. The result I get when trying to fetch it from the state is not what I expected. https://i.sstatic.net/QD7o5.png Here is the reducer: import {createReducer, on} ...

Can TypeScript's Zod library be utilized to parse a class instance?

Using the Zod validation library with TypeScript has been a great experience for me so far. I am currently exploring the best pattern to extend Zod Schema with class-like functionality, starting with a Vector3 schema like this: const Vector3Schema = z.obj ...

What is the best return type to use for a TypeScript function that returns an AsyncFunction?

From my experience, this code should work just fine... let DynamicFunction = Object.getPrototypeOf(dynamic function(){}).constructor; export function generateJsFunction(event: string, body: string[]): any { return new DynamicFunction(body.join("\n ...

The Hapi response fails to display JSON data in a nested tree format

Hey there! I've got this object with a specific structure. Here it is: interface FolderWithContent { uuid: string name: string; folders: Array<FolderWithContent>; files: Array<Files>; } Just a heads up, Files is an extens ...

Creating a React component in Typescript to utilize lodash helper functions

I have a component that looks like this: import React, { Component } from 'react'; import throttle from 'lodash.throttle'; interface Props { withScroll: boolean; } class Image extends Component<Props, {}> { throttledWindowS ...

Select a randomly generated number from an array, which dynamically updates every time the browser is refreshed

I recently completed a project in Angular that utilizes the TMDB API. The project is nearly finalized, but I have a desire to implement a change where the background image (backdrop_path) and other elements shift each time the browser is reloaded. Curren ...

Following the execution of the commit, the variable remains in a state of

I'm currently in the process of creating a new task. I was expecting the result to be 'created task with title', but the title is empty because 'formData' is still reactive. Below is an example of the code: // index.vue <form ...

Locate an element within an array of strings to refine the contents of a flatlist

Currently, I have a FlatList that I am attempting to filter using multiple inputs from dropdown selectors. Here is the code snippet for my FlatList component: <FlatList style={styles.list} data={data.filter(filteredUsers)} ...

I am unable to import choices.js using the "import" command in TypeScript

I'm having trouble importing choices.js using the "import" command: import Choices from 'choices.js'; TS2307: Cannot find module 'choices.js' The following attempts didn't work either: import Choices from '../../node_ ...

"Dealing with Angular .map() function returning an empty array or displaying error messages

I'm encountering two issues while attempting to display data from my API call using the following code... API Call: getProducts(id: number) { return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe( switchMap(token => { ...

Dealing with the challenge of having multiple types in a single dynamic type within Typescript when using

I had the idea to use various types under a single 'dynamic' type, so I created: export type ICandidate = | ICandidatePlain | ICandidateTalented | ICandidateExperienced The reason for this is because objects in the candidates array may ha ...

Tips for saving a variable in Angular that is being received through a subscription as JSON:

Below is an example of the json I have: [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}] I am struggling to store the date in a variable using Angular when it is being s ...

Can fields from one type be combined with those of another type?

Is it possible to achieve a similar outcome as shown below? type Info = { category: string } type Product = { code: string, ...Info } Resulting in the following structure for Product: type Product = { code: string, category : string } ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Why is Vite's hot reloading feature displaying unpredictable outcomes?

I have a unique setup consisting of Vite, Typescript, and Vue 3 SPA utilizing "script setup". This app is equipped with Urql to query data from a GraphQL endpoint. An interesting occurrence happens where the query results are only displayed after the comp ...

Ways to rename a sequelize property following a join operation

I am encountering a problem with sequelize ORM. The data returned after joining has a nested object: { "id": 1, "username": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4125342e2f26252e282220 ...

Angular 6 - execute function on either click event OR focus event

I am trying to figure out how to call a function from a component only when it is clicked or focused. Below is a snippet of the components HTML: <div class="form-add-new__input-box"> <input #commentCategories class="for ...