Giter Site home page Giter Site logo

Comments (11)

eddeee888 avatar eddeee888 commented on May 25, 2024

Hello 👋

I've got a few questions about your setup:

  1. Do we need a mix of schema file, in both TypeScript and GraphQL? I'd migrate to one style. My personal preference is .graphql
  2. Could you help me understand what you mean by "I want to customize enum with internal string substitution," please?
  3. I think the server preset setup in codegen.ts is slightly off. If you'd like a GraphQL with server preset setup, you could take a look at this example: https://github.com/eddeee888/graphql-server-template

If you still see errors, please help provide specific expectation and errors you are seeing. 🙂

from graphql-code-generator.

MichaelRando avatar MichaelRando commented on May 25, 2024
  1. I don't know how to implement graphql enum internal values using SDL. All the examples are in code: https://learning.atheros.ai/blog/how-to-use-graphql-enum-type-and-its-best-practices

The enum class allows us to map enum values to internal values represented by integers (or different strings etc.). By defining enumerated values to an integer leads you to design your schema in the most efficient way in terms of performance.

  1. If you looking in my example; the enums work like typescript enums, rather than string constants. Some references for supporting this:
  1. Could you be more specific? Let me copy your codegen in and see what happens...
    same output I was getting:
✔ Parse Configuration
❯ Generate outputs
✔ Parse Configuration
⚠ Generate outputs
  ❯ Generate to schema
    ✔ Load GraphQL schemas
    ✔ Load GraphQL documents
    ✖ Location is invalid
Running lifecycle hook "afterStart" scripts...
[CLI] Loading Schemas
[CLI] Loading Documents
[CLI] Generating output
error Command failed with exit code 1.

Because this project is moving an existing api into a codegen one; I don't necessarily have the freedom to change it to meet needs. With graphql, changing types breaks signatures and clients error out, it's really brittle with respect to type values.

I'm trying both techniques to achieve the goal: typescript enum type definition as well as enumValues codegen config. The typescript stuff breaks easy, so that's this ticket at a minimum. The enumValues works in an empty project, but stops working in a nontrival context or when your server preset is used.

from graphql-code-generator.

eddeee888 avatar eddeee888 commented on May 25, 2024

Thanks for the details, I think I understand now that you want to migrate enum in TypeScript to use SDL.

If that's the case, here's the steps I can recommend right now:

  1. Migrate all TypeScript to SDL. It'd look something like this:
type Query {
  colors: [Color]
  user(id: String): User
}

type User {
  id: String
  name: String
  language: ISOLanguage
}

enum ISOLanguage {
  EN
  ES
  RU
}

enum Color {
  RED
  GREEN
  BLUE
}
  1. Fix codegen setup. It'd look something like this:
import type { CodegenConfig } from "@graphql-codegen/cli";
import { defineConfig } from "@eddeee888/gcg-typescript-resolver-files";

const config: CodegenConfig = {
  schema: ["**/*.graphql"],
  require: ["ts-node/register"],
  generates: {
    "src/schema": defineConfig(),
  },
};

export default config;
  1. Follow the server preset guide to set up file structure:
src
  -- schema/
      -- base/
          -- schemaFile.graphql
  1. Run codegen

  2. Now, whenever you need to return language enum, you can. For example:

// src/schema/base/resolvers/User.ts

import type { UserResolvers } from "./../../types.generated";
export const User: UserResolvers = {
  /* Implement User resolver logic here */
  language: () => {
    return "EN"; // Can also be "ES", "RU"
  },
};

from graphql-code-generator.

MichaelRando avatar MichaelRando commented on May 25, 2024

Your example does not appear to be type compatible with the codebase. We're not talking about typescript, we're talking about graphql. I have an existing codebase, it's SDL is a megabyte already. I cannot generate types compatible with the existing types. The existing type is:

const languageType = new GraphQLEnumType({
  name: "ISOLanguage",
  values: {
    EN: {
      value: "en",
    },
    ES: {
      value: "es",
    },
    RU: {
      value: "ru",
    },
  },
});

The reason it's incompatible is the internal representation is a mismatch between what you're doing, and what's needed for compatibility.

Please review my links again:

from graphql-code-generator.

MichaelRando avatar MichaelRando commented on May 25, 2024

I found a codegen that "works", in that it accepts the parameters I'm passing

const config: CodegenConfig = {
  schema: files,
  generates: {
    schema: defineConfig({
      typesPluginsConfig: {
        enumValues: {
          ISOLanguage: {
            EN: "en",
            ES: "es",
            RU: "ru",
          },
        },
      },
    }),
  },
};

without server presets the codegen spits:

export enum IsoLanguage {
  En = 'en',
  Es = 'es',
  Ru = 'ru'
}

which compiles to javascript:

"use strict";
exports.__esModule = true;
exports.IsoLanguage = void 0;
var IsoLanguage;
(function (IsoLanguage) {
    IsoLanguage["En"] = "en";
    IsoLanguage["Es"] = "es";
    IsoLanguage["Ru"] = "ru";
})(IsoLanguage = exports.IsoLanguage || (exports.IsoLanguage = {}));

with the server preset and the enumValues it spits

export type ISOLanguage =
  | 'en'
  | 'es'
  | 'ru';

compiling both these down to javascript with tsc:

"use strict";
exports.__esModule = true;

I'm blocked until I can get the server preset to generate the code I'm looking for which transforms SDL uppercase to database lowercase.

from graphql-code-generator.

MichaelRando avatar MichaelRando commented on May 25, 2024

typescript defined types (re: issue title) also seem to work when not defineConfig @eddeee888/gcg-typescript-resolver-files as a config, so I suspect the issues I'm having apply specifically to server presets; without which, the documented codegen stuff is working.

from graphql-code-generator.

eddeee888 avatar eddeee888 commented on May 25, 2024

If you need to use TypeScript enum, you can set typesPluginsConfig.enumsAsTypes = false. e.g.

defineConfig({
      typesPluginsConfig: {
        enumsAsTypes: false,
        enumValues: {
          ISOLanguage: {
            EN: "en",
            ES: "es",
            RU: "ru",
          },
        },
      },
    })

from graphql-code-generator.

MichaelRando avatar MichaelRando commented on May 25, 2024

Yup, I figured out that part; and changed the codegen repo to purely represent the fact that typescript schema don't work at all with server preset. In particular it early outs on

const sources = schemaAst.extensions.extendedSources;
        if (!Array.isArray(sources) || sources.length === 0) {
            throw new Error('Empty Sources. Make sure schema files are parsed correctly.');
        }

and so my existing typescript is not useful and has to be ported to SDL to work with the server config. I'm unblocked now, so that's good; but only allowing SDL schema definition should be documented, as I lost much time trying to get it to work. (And it's fine w/o the config preset in the way)

from graphql-code-generator.

eddeee888 avatar eddeee888 commented on May 25, 2024

typescript schema don't work at all with server preset

Ah, gotcha, this is something I wasn't aware of. Thanks! I can look into improving the preset by adding this support.

Do you have other questions? Otherwise we can close this issue 🙂

from graphql-code-generator.

MichaelRando avatar MichaelRando commented on May 25, 2024

no other questions, this issue is represented by "adding typescript support to preset". If that's tracked elsewhere, this is now done.

from graphql-code-generator.

eddeee888 avatar eddeee888 commented on May 25, 2024

Thank you @MichaelRando , I have created an issue in Server Preset repo: eddeee888/graphql-code-generator-plugins#264

I'll look into adding support for your request in the future.

from graphql-code-generator.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.