MichalLytek / type-graphql

Create GraphQL schema and resolvers with TypeScript, using classes and decorators!
https://typegraphql.com
MIT License
8.05k stars 676 forks source link

JavaScript support #55

Open MichalLytek opened 6 years ago

MichalLytek commented 6 years ago

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 😉

capaj commented 6 years ago

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:

MichalLytek commented 6 years ago

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.

capaj commented 6 years ago

@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!

ematipico commented 5 years ago

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?

MichalLytek commented 5 years ago

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)
vjpr commented 5 years ago

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

tzarger commented 4 years ago

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

herreraemanuel commented 4 years ago

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"
  ]
}
PabloSzx commented 4 years ago

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 commented 4 years ago

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 😢

aleccool213 commented 3 years ago

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);
vjpr commented 3 years ago

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')],

   ]

}
aleccool213 commented 3 years ago

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"
  ]
}
PaulContremoulin commented 3 years ago

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
  }
}
aleccool213 commented 3 years ago

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

jonjrodriguez commented 3 years ago

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

SalasNi commented 3 years ago

@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

jonjrodriguez commented 3 years ago

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

edw19 commented 3 years ago

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

SalasNi commented 3 years ago

@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

edw19 commented 3 years ago

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 commented 3 years ago

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

TheElegantCoding commented 3 years ago

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

TheElegantCoding commented 3 years ago

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

ryanmargono commented 1 year ago

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'