MichalLytek / type-graphql

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

Integration with Nest #135

Open stevefan1999-personal opened 6 years ago

stevefan1999-personal commented 6 years ago

Owner note

Scroll to typegraphql-nestjs package info ⬇️

Original post

I was wondering if there could be more support for Nest.js, in particular, integration with an authorization endpoint is needed. Right now, I'm using this NPM package + TypeORM, following the sample, so far so good but unfortunately the source was nowhere to be found, and so I have to workaround my auth checker which required me to pass the database module into the context but it is very dangerous. So what about an official extension of TypeGraphQL to Nest.JS? This would make it easier to write universal services.

Salimlou commented 6 years ago

HI @stevefan1999 ,

I am the author of that package, and here is the source https://github.com/MagnusCloudCorp/nestjs-type-graphql,

But it's really really basic integration I made for a small project, just a matter to respect NestJs lifecycle.

You can easily put the same code inside your app, so you have full control.

If you have any question!

MichalLytek commented 6 years ago

The goal of TypeGraphQL integration with Nest is to create a replacement/substitute for the GraphQL (Apollo) module for Nest, so all the Nest features like pipes or guards would work. This requires a lot of changes in TypeGraphQL core so it will be done later 😞

kamilmysliwiec commented 6 years ago

Would love to see it! ❀️

Sacro commented 6 years ago

I have this working without needing anything fancy

import { Injectable, Logger } from '@nestjs/common';
import { GqlOptionsFactory, GqlModuleOptions } from '@nestjs/graphql';
import { buildSchema } from 'type-graphql';

@Injectable()
export class GraphqlConfigService implements GqlOptionsFactory {
  async createGqlOptions(): Promise<GqlModuleOptions> {
    const schema = await buildSchema({
      resolvers: [__dirname + '../**/*.resolver.ts'],
    });

    return {
      debug: true,
      playground: true,
      schema,
    };
  }
}

And then in the app.module...

  imports: [
    GraphQLModule.forRootAsync({
      useClass: GraphqlConfigService,
    }),
  ],
stevefan1999-personal commented 6 years ago

@Sacro Do you have injects available for TGQL resolvers in runtime?

Sacro commented 6 years ago

I'm not sure I follow.

My current repo is at https://gitlab.benwoodward.me.uk/pokedex/backend

stevefan1999-personal commented 6 years ago

@Sacro In this case, you aren't using NestJS injections at all in resolvers far as I see, you also used Active Record pattern so you evaded the need for a repository. Unfortunately, I was indeed using AR pattern (with @nestjs/typeorm package) and some other providers so Injectable is definitely needed.

But the problem is, NestJS doesn't have a global container, it is re-entrant-able, so instead, the container is attached by an instance context by design.

caseyduquettesc commented 5 years ago

@stevefan1999-personal Injecting repositories seems to work fine for me when I build off @Sacro's awesome integration work. Here is one of my resolvers that I moved from @nestjs/graphql to type-graphql along with the original statements.

item.resolvers.ts

// import { Resolver, Query } from '@nestjs/graphql';
import { Resolver, Query } from 'type-graphql';

import { Item } from './item.entity';
import { ItemService } from './item.service';

// @Resolver('Item')
@Resolver(_of => Item)
export class ItemsResolvers {
  constructor(private readonly itemsService: ItemService) {}

  // @Query()
  @Query(_returns => [Item])
  public async getItems(): Promise<Item[]> {
    return this.itemsService.findAll();
  }
}

item.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { Item } from './item.entity';

@Injectable()
export class ItemService {
  constructor(@InjectRepository(Item) private readonly itemRepository: Repository<Item>) {}

  public async findAll(): Promise<Item[]> {
    return this.itemRepository.find();
  }
}
kamilmysliwiec commented 5 years ago

I just realized that integration could be fairly easy. I'll provide a POC once I find some time :)

ghost commented 5 years ago

I just realized that integration could be fairly easy. I'll provide a POC once I find some time :)

Hello Kamil, do you have any news about this POC ? I'm trying to find the best integration method for type-graphql and Nest.js.

anodynos commented 5 years ago

Hey @kamilmysliwiec I found type-graphql this past weekend, which I spend looking at many possible graphql solutions (from prisma to postgraphile to type-graphql). My opinion, it rocks! Just like NestJS, you can build anything :-) I think it's the most mature and feature complete library out there, and it will be AWESOME if it works smoothly with Nest - we can't wait for nest/type-graphql ;-)

So, I've been trying a couple of days to make them work and eventually they did, but with quite a few hacks, for example:

The type-graphql @Resolver classes are injected their service props fine initially, but then type-graphql creates it's own instance of the resolver and it is using it. Of course, it misses to DI the new instance, so all injections are lost.

So I had to hack it like:

let service: TheService;
@Resolver()
export class TheResolver {  
  constructor(private _service: TheService) {
    if (_service) service = _service; // workaround for DI 
  }
  @Query(ret => Them)
  getEm() { return service.getEm(); }
}

but its not nice or scalable etc.

So if we can make this integration happen, it will be really awesome!!!

ghost commented 5 years ago

Hey @anodynos, you can look at this working solution :

src/app/app.module.ts

import * as path from 'path';

import { APP_INTERCEPTOR } from '@nestjs/core';
import { Module, CacheModule, CacheInterceptor } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { GraphQLModule } from '@nestjs/graphql';
import { ConfigModule } from 'nestjs-config';

import { TypeOrmConfigService } from './typeorm.config.service';
import { GraphqlConfigService } from './graphql.config.service';

import { PaysModule } from 'pays/pays.module';

@Module({
  imports: [
    ConfigModule.load(path.resolve(__dirname, 'config/**/*.{ts,js}')),
    CacheModule.register(),
    TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService }),
    GraphQLModule.forRootAsync({ useClass: GraphqlConfigService }),
    PaysModule,
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: CacheInterceptor,
    },
  ],
})
export class AppModule {
}

src/app/graphql.config.service.ts

import { Injectable } from '@nestjs/common';
import { GqlOptionsFactory, GqlModuleOptions } from '@nestjs/graphql';
import { ConfigService } from 'nestjs-config';
import { useContainer, buildSchema } from 'type-graphql';

@Injectable()
export class GraphqlConfigService implements GqlOptionsFactory {
  constructor(private readonly config: ConfigService) { }

  setContainer(container: any) {
    useContainer(container);
  }

  async createGqlOptions(): Promise<GqlModuleOptions> {
    const schema = await buildSchema({
      resolvers: [ __dirname + '../**/*.resolver.ts' ],
    });

    return {
      debug: this.config._isDev(),
      playground: this.config._isDev(),
      schema,
    };
  }
}

src/pays/pays.service.ts

import { Injectable } from '@nestjs/common';

import { Pays } from './pays.entity';

@Injectable()
export class PaysService {
 async findAll(): Promise<Pays[]> {
    return Pays.find();
  }
}

src/pays/pays.resolver.ts

import { Injectable } from '@nestjs/common';
import { Resolver, Query, Arg, Int } from 'type-graphql';

import {Β Pays } from './pays.entity';
import { PaysService } from './pays.service';

@Resolver(of => Pays)
export class PaysResolver {
  constructor(private readonly paysService: PaysService) { }

  @Query(returns => [Pays])
  async pays(): Promise<Pays[]> {
    return this.paysService.findAll();
  }
}

src/main.ts

// Nest App
const app = await NestFactory.create(AppModule, server);
const graphQlConfigService = app.get(GraphqlConfigService);
graphQlConfigService.setContainer(app);
caseyduquettesc commented 5 years ago

That method still won't use any guards or interceptors that you have setup in NestJS. The only way I've gotten requests to go through those is by using Nest's @Resolver decorator, which can't be used on the same class as type-graphql's @Resolver decorator.

anodynos commented 5 years ago

Thank you Christopher @christopherdupont - I had a similar setup at some point, didn't work :-( Does yours work without the problem/workaround I described above?

Basicaly I took code / ideas from @Sacro https://gitlab.benwoodward.me.uk/pokedex/backend I think my when I tried to @InjectRepository on my service and the service into the Resolver, I started having the problem I said:

@Resolver(of => Pays)                                                            
export class PaysResolver {
  constructor(private readonly paysService: PaysService) { }   // <---- THIS IS CALLED TWICE - 1st time with `paysService` instance (instantiated by NestJS) and second time by type-graphql, with `null`.

If your's doesn't have this problem, I 'd like to examine your setup - can you please put a min working example on a repo?

@caseyduquettesc Sure, there are a lot of integration points (and pains!!!) still... We're can't wait for @nest/type-graphql@~1.0 :-)

anodynos commented 5 years ago

Thank you @christopherdupont - I had a look and I think it works because you're using

@Entity({ name: 't_pays' })
@ObjectType()
export class Pays extends BaseEntity

I think if you start using Repository based entities or start using more DI, you'll start facing problems.

mohaalak commented 5 years ago

I created a module for NestJs, combining the typegraphql and nestjs decorators, the type graphql will generate the schema from typescript and NestJS will provide the resolvers, so guards, pipes, interceptors, injection is on NestJS but schema generating is by type graphql.

https://github.com/mohaalak/nestjs_typegraphql

kamilmysliwiec commented 5 years ago

I have just finished POC integration locally. The biggest issue that I'm encountering frequently so far is an inconsistency between graphql libraries. Hence, I'm quite often seeing this error: https://19majkel94.github.io/type-graphql/docs/faq.html#i-got-error-like-cannot-use-graphqlschema-object-object-from-another-module-or-realm-how-to-fix-that

which makes it almost impossible to provide a good developer experience for the end-user (calling npm dedupe is always required). This issue has been discussed here already: https://github.com/19majkel94/type-graphql/issues/192 and I see that it's not going to be fixed. However, I would love to keep type-graphql as a peer dependency (and graphql is nest peer dep as well), therefore, these libraries would be able to share the same graphql package by default. So the question goes here (cc @19majkel94): since the graphql package has to stay as a normal dependency of the type-graphql, could you expose another function which works same as buildSchema but instead of returning a schema, it would additionally call printSchema(schema) (from internal graphql-tools) and return us a string? :) For now (as a workaround), I have to emit schema to the file and afterward, read file content to get the stringified schema (what heavily affects library performance).

MichalLytek commented 5 years ago

@kamilmysliwiec

However, I would love to keep type-graphql as a peer dependency (and graphql is nest peer dep as well), therefore, these libraries would be able to share the same graphql package by default.

The problem is that TypeGraphQL heavily depends on graphql-js (and @types/graphql) and it's hard to control the version using peer dependencies mechanism. I can bump major version (with 0.x.y it's not a problem) when bumping peer deps minor version of graphql-js but this might fail in runtime (cannot read property 'directives' of undefined) as many people ignore npm peer deps warnings in console on install.

could you expose another function which works same as buildSchema but instead of returning a schema, it would additionally call printSchema(schema) (from internal graphql-tools) and return us a string? :)

emitSchemaFile options (as well as emitSchemaDefinitionFile helper function) are only a 3-lines wrapper around printSchema and writeFile. It doesn't change the schema building pipeline, it only acts as a helper for better DX because many people think that buildSchema return a special object, not a standard graphql-js schema.

So all you need to do is:

const schema = await buildSchema(options);
const schemaString = printSchema(schema);

I also have a PoC of building apollo-like resolversMap on a branch, this might help you with the integration: https://github.com/19majkel94/type-graphql/tree/resolvers-map

kamilmysliwiec commented 5 years ago

Actually, I took a look into the source code of these functions already. The problem is that when I have tried to do the exact same thing as you proposed above^

const schema = await buildSchema(options);
const schemaString = printSchema(schema);

I was also getting the graphql inconsistency error, because in this case, buildSchema uses nested graphql dependency of type-graphql (and schema is built using this internal version) while my imported printSchema would come from another graphql package.

MichalLytek commented 5 years ago

@kamilmysliwiec You're right, I will try to finish the work on generating typedefs-resolvers instead of the executable schema as soon as possible.

I will also try to find a way to detect the version of graphql in node_modules to throw error when peer dependency version isn't correct. I see that the whole ecosystem is switching to having graphql as a peer dependency, so this will solve a lot of compatibility problems.

And sorry for the late response 😞

apiel commented 5 years ago

@kamilmysliwiec is there any chance that you share your code to see how you attempted to integrate Type-graphql to Nest?

I am really looking forward to be able to use Type-graphql with Nest.

MichalLytek commented 5 years ago

@kamilmysliwiec Thanks to #233 and #239, you now should be able to finish your integration PoC πŸŽ‰

You can install the new 0.17.0 beta version - npm i type-graphql@next πŸš€ Stable release coming soon πŸ‘€

kamilmysliwiec commented 5 years ago

Awesome, I'll give it a shot asap πŸ’₯

natqe commented 5 years ago

@kamilmysliwiec I can't wait to use Type-graphql with Nest.

michelcve commented 5 years ago

@kamilmysliwiec Just curious, how are things progressing with your PoC?

kamilmysliwiec commented 5 years ago

I'm actually ready to publish it (waiting for the stable release of type-graphql)

michelcve commented 5 years ago

@kamilmysliwiec That's great news! Is there a preview that works with type-graphql@next? I'm not sure how long the wait for the stable release of type-graphql is gonne be, but I fear it's still some time until 1.0.0 is ready?

kamilmysliwiec commented 5 years ago

@michelcve I'm saying about the 0.17.0 :)

michelcve commented 5 years ago

Phew ;-) (though I have no idea when that version is due ;-))

MichalLytek commented 5 years ago

I'm actually ready to publish it

I'm glad the changes proved to be enough to make the integration possible.

I'm finishing #180 and after that will release 0.17 stable πŸš€ Then large refactoring #183 is coming πŸ› 

kamilmysliwiec commented 5 years ago

Excellent! I have just finished the docs part. #180 feature sounds awesome btw

kamilmysliwiec commented 5 years ago

Btw @19majkel94, so far I have to use such a workaround:

await buildSchema({
  ...options,
  emitSchemaFile,
  scalarsMap,
  resolvers: ['---.js'], // NOTE: Added to omit options validation
});

Is there a way to disable resolvers validation (additional flag?)? I don't have to instantiate any resolver during the schema creation process.

MichalLytek commented 5 years ago

@kamilmysliwiec Right now resolvers are only used for triggering module evaluation (registering metadata from decorators) by require-ing files from glob paths. The schema is generated based on all registered types in global metadata storage.

In the future (#183), to allow for multiple schemas in single process with no leaks, it will strictly traverse only the modules in provided glob paths (or provided classes) to emit only the desired types, not all from the storage. So this workaround will fail and result in empty schema.

kamilmysliwiec commented 5 years ago

@19majkel94 Could you allow to pass an array of classes as well (instead of string glob path)? In this case, I would just traverse modules graph, extract resolvers, and pass them in the resolvers array.

MichalLytek commented 5 years ago

@kamilmysliwiec Available from the beginning for over the year πŸ˜„ https://github.com/19majkel94/type-graphql/blob/fa3f69842b2ab1f5d23ab5a75edc12e814150984/src/utils/buildSchema.ts

image

kamilmysliwiec commented 5 years ago

awesome ❀️

hexonaut commented 5 years ago

@kamilmysliwiec Any chance you can put up the WIP code? I'd like to start integrating this into my own project.

apiel commented 5 years ago

https://github.com/nestjs/nest/tree/6.0.0-next

https://github.com/nestjs/nest/tree/6.0.0-next/sample/23-type-graphql

@kamilmysliwiec do you have any plan for the release of nextjs 6? Maybe for Js-kongress :D ?

kamilmysliwiec commented 5 years ago

hey @19majkel94, Since #180 has been fixed 4 days ago, do you have any rough estimation when 0.17.0 will be published? πŸš€

MichalLytek commented 5 years ago

@kamilmysliwiec I am grouping breaking changes, as some of them are coming unexpectedly, like #258.

Will try to ensure that none pending issues left and release 0.17 this week πŸ˜‰

MichalLytek commented 5 years ago

v0.17 is out! πŸš€

Spread the words, guys! πŸ“£ https://twitter.com/typegraphql/status/1102652523326902273

kamilmysliwiec commented 5 years ago

Congrats @19majkel94! 🎸πŸ’₯

michelcve commented 5 years ago

@19majkel94 Great work!

MichalLytek commented 5 years ago

Hey @kamilmysliwiec,

Do you have any rough estimation when Nest v6 will be published? We're all waiting for Nest & TypeGraphQL integration πŸš€

kamilmysliwiec commented 5 years ago

Hey @19majkel94, Nest v6 will be published this month, ETA is next week :)

MichalLytek commented 5 years ago

In case someone didn't notice, Nest v6 has been released! πŸŽ‰ https://medium.com/@kammysliwiec/announcing-nestjs-6-whats-new-38959d94221f

So now TypeGraphQL is officially supported in Nest as the code first approach ❀️ https://docs.nestjs.com/graphql/quick-start#code-first

However, as discussed earlier, I will leave this issue open because I would like to provide an alternative implementation where you can use all the TypeGraphQL features, like middlewares, query complexity or other integrations (TypeORM, dataloader) that requires full control of executing resolvers methods. Maybe during the development I will introduce other concepts like custom param decorators (#45) that will allow to wrap all the Nest goodness like guards, interceptors, filters or pipes 🍾

KristenLeach commented 5 years ago

I'm loving the new type-graphql integration with Nest! I'm curious though, will this work with mongoose? I'm having trouble extending from Document within the new code-first syntax. I tried to extend from the class, @ObjectType() export class User extends Document{, but the service is still throwing this error: "Type 'User' does not satisfy the constraint 'Document'." I could be attempting this in the wrong place. If I write a separate User interface and extend there it works, but that defeats the purpose of reducing redundancy.

MichalLytek commented 5 years ago

@KristenLeach I think that's better to use Typegoose to define Mongoose models using TypeScript classes πŸ˜‰

santutu commented 5 years ago

Amazing intergration...

Veetaha commented 5 years ago

I wish we could use 'type-graphql' decorators for resolvers in NestJS. Mixing decorators from '@nestjs/graphql' with ones from this package seems odd and conter-intuitive. This also prevents users from using new functionality for resolvers from this package. Any intentions for full integration with Nest, @19majkel94, @kamilmysliwiec?