type-graphql icon indicating copy to clipboard operation
type-graphql copied to clipboard

JavaScript support

Open MichalLytek opened this issue 7 years ago • 25 comments
trafficstars

The main goal of TypeGraphQL is to get rid of SDL schema and TS interfaces duplication in favor of one single source of truth (classes with decorators). However, after adding new features like dependency injection, validation, authorization and subscriptions, there are some benefits of using this library instead of pure graphql-js or graph-tools.

Technically, it would be possible to use TypeGraphQL with babel's transform-class-properties and transform-decorators-legacy plugins and some modification in decorators signature and logic.

It also would be nice to support TypeScript compilation with Babel 7 using @babel/preset-typescript and a bunch of decorators/metadata plugins.

However I'm not sure if there's a demand for this feature. So if you are interested, please 👍 so I will know that I should implement it 😉

MichalLytek avatar Mar 31 '18 20:03 MichalLytek

I am thinking about doing this as a POC for babel myself. We're currently starting to migrate our REST api to GQL and babel enabled version would save us a some code repetition. Although benefits such as typechecking in development get lost. I am as unsure :thinking:

capaj avatar May 06 '18 22:05 capaj

Little update: I've tried transform-decorators-legacy and looks like it doesn't support methods params decorators, so it doesn't evaluate @Arg or @Root decorators.

If someone knows how to make this work, please let me know 😉 Otherwise we will have to wait for a new decorators proposal: https://github.com/tc39/proposal-decorators

When TypeScript supports the new syntax, I will update TypeGraphQL for it and it should work with new babel plugin.

MichalLytek avatar May 22 '18 16:05 MichalLytek

@19majkel94 I've converted our whole app from flowtype to typescript in the end, so I don't really care anymore. Thanks for following through on this anyway!

capaj avatar May 22 '18 16:05 capaj

I am interested at this topic. Now that Babel supports typescript, I'm more keen to use Babel as compiler and use typescript as just type checker. Although I hit a bump and this cannot be done at moment.

I was wondering if there was, at moment, an alternative way to use decorators like @Arg or @Root?

ematipico avatar Jan 27 '19 18:01 ematipico

and use typescript as just type checker

So no reflection from TypeScript compiler? Doesn't sound like a good idea. Why babel for a node app?

I was wondering if there was, at moment, an alternative way to use decorators like @Arg or @Root?

Just call it as a function below your class definition:

Arg("argName", type => ArgType, { nullable: true })(ObjectTypeClass.prototype, "methodName", parameterIndex)

MichalLytek avatar Feb 07 '19 18:02 MichalLytek

@ematipico Use @babel/preset-typescript and this plugin https://github.com/leonardfactory/babel-plugin-transform-typescript-metadata

vjpr avatar Apr 28 '19 10:04 vjpr

@vjpr can you share more details how you were able to get this to work with babel-loader? Are you using @Args() or @Ctx()?

tzarger avatar Mar 11 '20 15:03 tzarger

I was working on an example using type-graphql with next.js and I had an issue when I add the @Args(). I used the babel plugin who @vjpr recommended and solve the problem. This is my .babelrc config if someone needed.

  "presets": ["next/babel"],
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    "babel-plugin-parameter-decorator"
  ]
}

herreraemanuel avatar Aug 24 '20 00:08 herreraemanuel

I was working on an example using type-graphql with next.js and I had an issue when I add the @Args(). I used the babel plugin who @vjpr recommended and solve the problem. This is my .babelrc config if someone needed.

  "presets": ["next/babel"],
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    "babel-plugin-parameter-decorator"
  ]
}

image

Nope, it doesn't work 😞

PabloSzx avatar Aug 26 '20 18:08 PabloSzx

I was working on an example using type-graphql with next.js and I had an issue when I add the @Args(). I used the babel plugin who @vjpr recommended and solve the problem. This is my .babelrc config if someone needed.

  "presets": ["next/babel"],
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    "babel-plugin-parameter-decorator"
  ]
}

Did you try to do it? I make something simular and works 100% ok, but I have typeORM issues

I did exactly the same config, and testing it with a rather large real API and it didn't work 😢

PabloSzx avatar Sep 25 '20 01:09 PabloSzx

Getting the original error with this .babelrc in my Next.js app:

{
  "presets": ["next/babel"],
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    "babel-plugin-parameter-decorator"
  ]
}

Code:


import { Arg, Authorized, Query, Resolver } from "type-graphql";

import { UserService } from "../../services/user/user.service";

import { UserNotFoundError } from "./user.error";
import { User } from "./user.type";

@Resolver(User)
export class UserResolver {
  constructor(private userService: UserService) {}

  @Query(() => User)
  @Authorized()
  async recipe(@Arg("id") id: string) {
    const recipe = await this.userService.findById(id);
    if (recipe === undefined) {
      throw new UserNotFoundError(id);
    }
    return recipe;
  }
}

Error:

error - ./pages/api/lib/features/user/user.resolver.ts:14:15
Syntax error: Decorators cannot be used to decorate parameters

  12 |   @Query(() => User)
  13 |   @Authorized()
> 14 |   async recipe(@Arg("id") id: string) {
     |                ^
  15 |     const recipe = await this.userService.findById(id);
  16 |     if (recipe === undefined) {
  17 |       throw new UserNotFoundError(id);

aleccool213 avatar Dec 10 '20 14:12 aleccool213

Here is what my babel preset looks like:

NOTE: I had to patch parameter decorator to work with React@17.

module.exports = api => {
  return {

    ////////////////////////////////////////////////////////////////////////////

    presets: [
      require('@babel/preset-typescript'),
    ],

    ////////////////////////////////////////////////////////////////////////////

    plugins: [
      // Decorators must be before `class-properties`.
      [require('@babel/plugin-proposal-decorators'), {legacy: true}],

      ////////////////////

      // Patched to fix: https://github.com/WarnerHooh/babel-plugin-parameter-decorator/issues/25
      [require('@vjpr/babel-plugin-parameter-decorator')],

      ////////////////////

      // NOTE: Breaks automatic field getters with Sequelize if not in the correct spot.
      //   See: https://github.com/sequelize/sequelize/issues/11326
      //   See also: https://github.com/Polymer/lit-element/issues/234#issuecomment-687673767
      [require('@babel/plugin-proposal-class-properties'), {loose: true}],

      [require('babel-plugin-transform-typescript-metadata')],

   ]

}

vjpr avatar Dec 10 '20 14:12 vjpr

Thanks @vjpr, I finally got it to work this with .babelrc file in my Next.js app.

{
  "presets": ["next/babel"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "@vjpr/babel-plugin-parameter-decorator",
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    "babel-plugin-transform-typescript-metadata"
  ]
}

aleccool213 avatar Dec 10 '20 16:12 aleccool213

Hi everyone,

I have an issue with babel (I think). My @FieldResolvers don't seem to work after build. The function is not executed to resolve the field and graphql returns the following error: Error: Cannot return null for non-nullable field Article.tags..

In dev mode (ts-node --files ./src/index.ts), everything works well.

babel.config.json :

{
  "presets": [
    "@babel/preset-typescript",
    [
      "@babel/preset-env",
      {
        "targets": {
          "esmodules": true
        }
      }
    ]
  ],
  "plugins": [
    ["@babel/plugin-proposal-decorators", {"legacy":  true}],
    "babel-plugin-parameter-decorator",
    ["@babel/plugin-proposal-class-properties", {"loose":  true}],
    "babel-plugin-transform-typescript-metadata"
  ]
}

tsconfig.json :

{
  "compilerOptions": {
    "target": "es2018",
    "module": "CommonJS",
    "lib": ["es2018", "esnext.asynciterable"],
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true,
    "declaration": true,
    "emitDeclarationOnly": true,
    "isolatedModules": true
  }
}

PaulContremoulin avatar Dec 22 '20 05:12 PaulContremoulin

Just for anyone who is having trouble getting this working, Next.js uses Babel as a transpiler and I have a working example here: https://github.com/aleccool213/next-js-typeorm-typegraphql-example

aleccool213 avatar Dec 22 '20 15:12 aleccool213

Hi everyone,

I have an issue with babel (I think). My @FieldResolvers don't seem to work after build. The function is not executed to resolve the field and graphql returns the following error: Error: Cannot return null for non-nullable field Article.tags..

In dev mode (ts-node --files ./src/index.ts), everything works well.

@PaulContremoulin did you ever get this resolved? Running into the same issue with FieldResolver

jonjrodriguez avatar Mar 26 '21 18:03 jonjrodriguez

@jonjrodriguez @PaulContremoulin Hi, does anyone of you got it working? I have the same problem with @FieldResolvers() not being called, I used the configs that @aleccool213 provided, everything works as expected, except for that functionality.

Dont know if It can be this problem https://stackoverflow.com/questions/63892051/graphql-with-typescript-fieldresolver-not-working-in-compiled-to-js-type-grap

thanks ,regards

salascarlosni avatar Jun 23 '21 09:06 salascarlosni

@josesalasni , no I never got it working. I migrated to a different tool.

jonjrodriguez avatar Jun 23 '21 12:06 jonjrodriguez

I have this error or bug, i dont know image image but if i create the array manually, pass this image image why ?

edw19 avatar Jun 26 '21 17:06 edw19

@edw19 If you are using Babel to transpile ts with type-graphql to javascript, try to remove the Resolver( () => Company ) to Resolver(Company) , it Fixed some problems to me , or keep it only Resolver()

Does your service class return Promise<Company[]> as well?

Also I got it working the FieldResolvers at the end, If i remove the @Field() in my @objectType Class, The methods finally resolved to the @FieldResolver in my resolver class, with the config that Aleecool provided

salascarlosni avatar Jun 26 '21 19:06 salascarlosni

image I removed the types but I keep getting the error my configuration in babel is: { "presets": ["next / babel"], "plugins": [ "babel-plugin-transform-typescript-metadata", ["@ babel / plugin-proposal-decorators", {"legacy": true}], ["@ babel / plugin-proposal-class-properties", {"loose": true}], "babel-plugin-parameter-decorator" ] }

edw19 avatar Jun 26 '21 20:06 edw19

I solved it using typegoose https://typegoose.github.io/typegoose/

edw19 avatar Jun 30 '21 17:06 edw19

I have the same issue using the BaseResolver, all work fine but the resolvers that have inheritance dont show his args

TheElegantCoding avatar Oct 25 '21 21:10 TheElegantCoding

any update on this? I try babel but I think I set it up bad, if someone has an example of in express a server I really appreciate

TheElegantCoding avatar Oct 25 '21 21:10 TheElegantCoding

im facing the same problem. has anyone gotten this to work? attempting to use this in a lambda created with @aws-cdk/aws-lambda-nodejs'

ryanmargono avatar Feb 23 '23 16:02 ryanmargono