Security News
tea.xyz Spam Plagues npm and RubyGems Package Registries
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
typegraphql-nestjs
Advanced tools
Readme
Basic integration of TypeGraphQL in NestJS.
Allows to use TypeGraphQL features while integrating with NestJS modules system and dependency injector.
First, you need to instal the typegraphql-nestjs
module along with @nestjs/graphql
:
npm i typegraphql-nestjs @nestjs/graphql
If you haven't installed it yet, it's time to add type-graphql
into the project:
npm i type-graphql
The typegraphql-nestjs
package exports TypeGraphQLModule
dynamic module, which is based on the official NestJS GraphQLModule
. It exposes three static methods:
.forRoot()
The first one is TypeGraphQLModule.forRoot()
which you should call on your root module, just like with the official GraphQLModule
.
The only difference is that as its argument you can provide typical TypeGraphQL buildSchema
options like emitSchemaFile
or authChecker
apart from the standard GqlModuleOptions
from @nestjs/graphql
like installSubscriptionHandlers
or context
:
import { Module } from "@nestjs/common";
import { TypeGraphQLModule } from "typegraphql-nestjs";
import RecipeModule from "./recipe/module";
import { authChecker } from "./auth";
@Module({
imports: [
TypeGraphQLModule.forRoot({
driver: ApolloDriver,
emitSchemaFile: true,
authChecker,
scalarsMap: [{ type: Date, scalar: GraphQLTimestamp }],
context: ({ req }) => ({ currentUser: req.user }),
}),
RecipeModule,
],
})
export default class AppModule {}
Then, inside the imported modules (like RecipeModule
) you just need to register the resolvers classes in the module providers
array:
import { Module } from "@nestjs/common";
import RecipeResolver from "./resolver";
import RecipeService from "./service";
@Module({
providers: [RecipeResolver, RecipeService],
})
export default class RecipeModule {}
And that's it! 😁
Notice that the resolvers classes are automatically inferred from your submodules providers
array, so you don't need to specify resolvers
property from TypeGraphQL buildSchema
options inside TypeGraphQLModule.forRoot()
.
.forFeature()
In case of need to provide orphanedTypes
setting, you should use TypeGraphQLModule.forFeature()
. The recommended place for that is in the module where the orphaned type (like SuperRecipe
) belongs:
import { Module } from "@nestjs/common";
import { TypeGraphQLModule } from "typegraphql-nestjs";
import RecipeResolver from "./resolver";
import RecipeService from "./service";
import { SuperRecipe } from "./types";
@Module({
imports: [
TypeGraphQLModule.forFeature({
orphanedTypes: [SuperRecipe],
}),
],
providers: [RecipeResolver, RecipeService],
})
export default class RecipeModule {}
Using .forFeature()
ensures proper schemas isolation and automatically supply orphanedTypes
option for underlying buildSchema
from TypeGraphQL - again, there's no need to provide it manually in .forRoot()
options.
.forRootAsync()
If you need to access some services to construct the TypeGraphQLModule
options, you might be interested in the TypeGraphQLModule.forRootAsync()
method. It allows you to define your own useFactory
implementation where you have injected services from imports
option.
Example of using the config service to generate TypeGraphQLModule
options:
@Module({
imports: [
ConfigModule,
RecipeModule,
TypeGraphQLModule.forRootAsync({
driver: ApolloDriver,
inject: [ConfigService],
useFactory: async (config: ConfigService) => ({
cors: true,
debug: config.isDevelopmentMode,
playground: !config.isDevelopmentMode,
scalarsMap: [{ type: Date, scalar: GraphQLTimestamp }],
emitSchemaFile:
config.isDevelopmentMode && path.resolve(__dirname, "schema.graphql"),
}),
}),
],
})
export default class AppModule {}
typegraphql-nestjs
has also support for Apollo Federation.
However, Apollo Federation requires building a federated GraphQL schema, hence you need to adjust your code a bit.
The usage is really similar to the basic case - the only difference is that in TypeGraphQLModule.forFeature()
method you can provide a referenceResolvers
option object, which is needed in some cases of Apollo Federation:
function resolveUserReference(
reference: Pick<User, "id">,
): Promise<User | undefined> {
return db.users.find({ id: reference.id });
}
@Module({
imports: [
TypeGraphQLModule.forFeature({
orphanedTypes: [User],
referenceResolvers: {
User: {
__resolveReference: resolveUserReference,
},
},
}),
],
providers: [AccountsResolver],
})
export default class AccountModule {}
For the .forRoot()
method there's no differences - just need to provide driver: ApolloFederationDriver
option in order to build a subgraph schema, same as with GraphQLModule
from @nestjs/graphql
described in the NestJS docs. However, you also need to explicitly setup federation version, by using federationVersion
option:
@Module({
imports: [
TypeGraphQLModule.forRoot({
driver: ApolloFederationDriver,
federationVersion: 2,
}),
AccountModule,
],
})
export default class AppModule {}
Then, for exposing the federated schema using Apollo Gateway, you should use the standard NestJS ApolloGatewayDriver
solution.
While this integration provides a way to use TypeGraphQL with NestJS modules and dependency injector, for now it doesn't support other NestJS features like guards, interceptors, filters and pipes.
To achieve the same goals, you can use standard TypeGraphQL equivalents - middlewares, custom decorators, built-in authorization and validation.
Moreover, with typegraphql-nestjs
you can also take advantage of additional features (comparing to @nestjs/graphql
) like inline field resolvers, Prisma 2 integration or up-to-date capabilities like deprecating input fields and args (thanks to always synced with latests graphql-js
).
You can see some examples of the integration in this repo:
Basics of the integration, like TypeGraphQLModule.forRoot
usage
Advanced usage of multiple schemas inside single NestJS app - demonstration of schema isolation in modules and TypeGraphQLModule.forFeature
usage
Usage of request scoped dependencies - retrieving fresh instances of resolver and service classes on every request (query/mutation)
Usage of class-based middlewares - modules, providers and schema options
Showcase of the legacy Apollo Federation approach
Showcase of the new Apollo Federation V2 approach
Most of them you can run by using ts-node
, like npx ts-node ./examples/1-basics/index.ts
.
All examples folders contain a query.graphql
file with some examples operations you can perform on the GraphQL servers.
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
FAQs
Basic integration of TypeGraphQL in NestJS. Allows to use TypeGraphQL features while integrating with NestJS modules system and dependency injector.
The npm package typegraphql-nestjs receives a total of 3,003 weekly downloads. As such, typegraphql-nestjs popularity was classified as popular.
We found that typegraphql-nestjs demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.
Security News
UnitedHealth Group disclosed that the ransomware attack on Change Healthcare compromised protected health information for millions in the U.S., with estimated costs to the company expected to reach $1 billion.