-
Notifications
You must be signed in to change notification settings - Fork 400
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add code-first support for grahql federation
Blocked until support for Directives lands in type-graphql[1] 1. MichalLytek/type-graphql#351
- Loading branch information
1 parent
bc4be48
commit ef2e409
Showing
13 changed files
with
314 additions
and
38 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,53 +1,100 @@ | ||
import { Injectable } from '@nestjs/common'; | ||
import { gql } from 'apollo-server-core'; | ||
import { loadPackage } from '@nestjs/common/utils/load-package.util'; | ||
|
||
import { extend } from './utils'; | ||
import { isEmpty, forEach } from 'lodash'; | ||
import { | ||
ScalarsExplorerService, | ||
DelegatesExplorerService, | ||
ResolversExplorerService, | ||
} from './services'; | ||
import { mergeSchemas } from 'graphql-tools'; | ||
import { GqlModuleOptions } from './interfaces'; | ||
import { GraphQLSchemaBuilder } from './graphql-schema-builder'; | ||
import { GraphQLFactory } from './graphql.factory'; | ||
import { GraphQLSchema, GraphQLSchemaConfig } from 'graphql'; | ||
import { GraphQLObjectType } from 'graphql'; | ||
|
||
@Injectable() | ||
export class GraphQLFederationFactory { | ||
constructor( | ||
private readonly resolversExplorerService: ResolversExplorerService, | ||
private readonly delegatesExplorerService: DelegatesExplorerService, | ||
private readonly scalarsExplorerService: ScalarsExplorerService, | ||
private readonly gqlSchemaBuilder: GraphQLSchemaBuilder, | ||
private readonly graphqlFactory: GraphQLFactory, | ||
) {} | ||
|
||
private extendResolvers(resolvers: any[]) { | ||
return resolvers.reduce((prev, curr) => extend(prev, curr), {}); | ||
async mergeOptions(options: GqlModuleOptions = {}): Promise<GqlModuleOptions> { | ||
const transformSchema = async s => (options.transformSchema ? options.transformSchema(s) : s); | ||
|
||
let schema: GraphQLSchema; | ||
if (options.autoSchemaFile) { | ||
// Enable support when Directive support in type-graphql goes stable | ||
throw new Error('Code-first not supported yet'); | ||
schema = await this.generateSchema(options); | ||
} else if (!isEmpty(options.typeDefs)) { | ||
schema = options.schema; | ||
} else { | ||
schema = this.buildSchemaFromTypeDefs(options); | ||
} | ||
|
||
return { | ||
...options, | ||
schema: await transformSchema(schema), | ||
typeDefs: undefined, | ||
}; | ||
} | ||
|
||
async mergeOptions(options: GqlModuleOptions = {}): Promise<GqlModuleOptions> { | ||
private buildSchemaFromTypeDefs(options: GqlModuleOptions) { | ||
const { buildFederatedSchema } = loadPackage('@apollo/federation', 'ApolloFederation'); | ||
|
||
const externalResolvers = Array.isArray(options.resolvers) | ||
? options.resolvers | ||
: [options.resolvers]; | ||
const resolvers = this.extendResolvers([ | ||
this.resolversExplorerService.explore(), | ||
this.delegatesExplorerService.explore(), | ||
...this.scalarsExplorerService.explore(), | ||
...externalResolvers, | ||
]); | ||
|
||
const schema = buildFederatedSchema([ | ||
return buildFederatedSchema([ | ||
{ | ||
typeDefs: gql` | ||
${options.typeDefs} | ||
`, | ||
resolvers, | ||
resolvers: this.getResolvers(options.resolvers), | ||
}, | ||
]); | ||
} | ||
|
||
private async generateSchema(options: GqlModuleOptions): Promise<GraphQLSchema> { | ||
const { buildFederatedSchema, printSchema } = loadPackage( | ||
'@apollo/federation', | ||
'ApolloFederation', | ||
); | ||
|
||
const autoGeneratedSchema: GraphQLSchema = await this.gqlSchemaBuilder.buildFederatedSchema( | ||
options.autoSchemaFile, | ||
options.buildSchemaOptions, | ||
this.resolversExplorerService.getAllCtors(), | ||
); | ||
const executableSchema = buildFederatedSchema({ | ||
typeDefs: gql(printSchema(autoGeneratedSchema)), | ||
resolvers: this.getResolvers(options.resolvers), | ||
}); | ||
|
||
const schema = options.schema | ||
? mergeSchemas({ | ||
schemas: [options.schema, executableSchema], | ||
}) | ||
: executableSchema; | ||
|
||
return schema; | ||
} | ||
|
||
private getResolvers(optionResolvers) { | ||
optionResolvers = Array.isArray(optionResolvers) ? optionResolvers : [optionResolvers]; | ||
return this.extendResolvers([ | ||
this.resolversExplorerService.explore(), | ||
this.delegatesExplorerService.explore(), | ||
...this.scalarsExplorerService.explore(), | ||
...optionResolvers, | ||
]); | ||
} | ||
|
||
return { | ||
...options, | ||
schema, | ||
typeDefs: undefined, | ||
}; | ||
private extendResolvers(resolvers: any[]) { | ||
return resolvers.reduce((prev, curr) => extend(prev, curr), {}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import { INestApplication } from '@nestjs/common'; | ||
import { Test } from '@nestjs/testing'; | ||
import * as request from 'supertest'; | ||
import { ApplicationModule } from '../type-graphql-federation/app.module'; | ||
|
||
describe.skip('TypeGraphQL - Federation', () => { | ||
let app: INestApplication; | ||
|
||
beforeEach(async () => { | ||
const module = await Test.createTestingModule({ | ||
imports: [ApplicationModule], | ||
}).compile(); | ||
|
||
app = module.createNestApplication(); | ||
await app.init(); | ||
}); | ||
|
||
it(`should return query result`, () => { | ||
return request(app.getHttpServer()) | ||
.post('/graphql') | ||
.send({ | ||
operationName: null, | ||
variables: {}, | ||
query: ` | ||
{ | ||
_service { sdl } | ||
}`, | ||
}) | ||
.expect(200, { | ||
data: { | ||
_service: { | ||
sdl: | ||
'type Post @key(fields: "id") {\n id: ID!\n title: String!\n authorId: Int!\n}\n\ntype Query {\n findPost(id: Float!): Post!\n getPosts: [Post!]!\n}\n\ntype User @extends @key(fields: "id") {\n id: ID! @external\n posts: [Post!]!\n}\n', | ||
}, | ||
}, | ||
}); | ||
}); | ||
|
||
afterEach(async () => { | ||
await app.close(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { Module } from '@nestjs/common'; | ||
import { GraphQLFederationModule } from '../../lib'; | ||
import { UserModule } from './user/user.module'; | ||
import { PostModule } from './post/post.module'; | ||
import { User } from './user/user.entity'; | ||
|
||
@Module({ | ||
imports: [ | ||
UserModule, | ||
PostModule, | ||
GraphQLFederationModule.forRoot({ | ||
debug: false, | ||
autoSchemaFile: true, | ||
buildSchemaOptions: { | ||
orphanedTypes: [User], | ||
}, | ||
}), | ||
], | ||
}) | ||
export class ApplicationModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import { ValidationPipe } from '@nestjs/common'; | ||
import { NestFactory } from '@nestjs/core'; | ||
import { ApplicationModule } from './app.module'; | ||
|
||
async function bootstrap() { | ||
const app = await NestFactory.create(ApplicationModule); | ||
app.useGlobalPipes(new ValidationPipe()); | ||
await app.listen(3000); | ||
} | ||
bootstrap(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { Field, ID, ObjectType, Directive, Int } from 'type-graphql'; | ||
|
||
@ObjectType() | ||
@Directive('@key(fields: "id")') | ||
export class Post { | ||
@Field(type => ID) | ||
public id: number; | ||
|
||
@Field() | ||
public title: string; | ||
|
||
@Field(type => Int) | ||
public authorId: number; | ||
|
||
constructor(post: Partial<Post>) { | ||
Object.assign(this, post); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { Module } from '@nestjs/common'; | ||
import { PostService } from './post.service'; | ||
import { PostResolver } from './post.resolver'; | ||
|
||
@Module({ | ||
providers: [PostService, PostResolver], | ||
exports: [PostService], | ||
}) | ||
export class PostModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { Query, Args, ResolveReference, Resolver } from '../../../lib'; | ||
import { PostService } from './post.service'; | ||
import { Post } from './post.entity'; | ||
|
||
@Resolver(of => Post) | ||
export class PostResolver { | ||
constructor(private readonly postService: PostService) {} | ||
|
||
@Query(returns => Post) | ||
public findPost(@Args('id') id: number) { | ||
return this.postService.findOne(id); | ||
} | ||
|
||
@Query(returns => [Post]) | ||
public getPosts() { | ||
return this.postService.all(); | ||
} | ||
|
||
@ResolveReference() | ||
public resolveRef(reference: any) { | ||
return this.postService.findOne(reference.id); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { Post } from './post.entity'; | ||
import { Injectable } from '@nestjs/common'; | ||
|
||
const data = [ | ||
{ | ||
id: 1, | ||
title: 'hello world', | ||
authorId: 2, | ||
}, | ||
{ | ||
id: 2, | ||
title: 'lorem ipsum', | ||
authorId: 1, | ||
}, | ||
]; | ||
|
||
@Injectable() | ||
export class PostService { | ||
public findOne(id: number) { | ||
const post = data.find(p => p.id === id); | ||
if (post) { | ||
return new Post(post); | ||
} | ||
return null; | ||
} | ||
|
||
public all() { | ||
return data.map(p => new Post(p)); | ||
} | ||
|
||
public forAuthor(authorId: number) { | ||
return data.filter(p => p.authorId === authorId).map(p => new Post(p)); | ||
} | ||
} |
Oops, something went wrong.