I'm submitting a...Bug report
[ ] Regression
[*] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Current behavior
Hello,
I'm using the graphql example( in the example directory of nest) with the Cat CRUD and i try to use a union type and interface but i didn't find a way to do it.
When i try to request my data with a fragment, i have the following error :
"Abstract type MutationResult must resolve to an Object type at runtime for field Mutation.createCat with value "[object Object]", received "undefined". Either the MutationResult type should provide a "resolveType" function or each possible types should provide an "isTypeOf" function."
There is nothing in the doc explaining how to use union / interface, and there is nothing in the graphql example.
In the apollo documentation, the type resolver ( here "Cat" Resolver") should implement a __resolveType function. I tried to set this function in the @resolver('Cat') class CatsResolvers
but it's not working.
I tried to add it on the cat resolvers class
Expected behavior
The request should return either a Cat item or GraphQLErrorItem from my schema definition.
Minimal reproduction of the problem with instructions
export interface GraphQLError {
readonly message: string;
readonly errorCode: number;
readonly type: string;
}
type GraphQLError {
message: String
errorCode: Int
type: String
}
union MutationResult = Cat | GraphQLError
- change the createCat Mutation in the schema
- createCat(name: String, age: Int): MutationResult
- add the function in cats.resolvers.ts in the CatsResolvers class
__resolveType(obj, context, info): string{
return obj.errorCode ? 'GraphQLError' : 'Cat';
}
What is the motivation / use case for changing the behavior?
Environment
Nest version: 4.5.10 (core)
For Tooling issues:
- Node version: 9.4
- Platform: Mac
Others:
Hi,
I have an issue, when merge types and create schema, on terminal console show errors like this:
node:8726) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): TypeError: buildASTSchema.getDescription is not a function
(node:8726) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled willterminate the Node.js process with a non-zero exit code.
this is my code
const typeDefs = this.graphQLFactory.mergeTypesByPaths('./**/*.graphql');
const schema = this.graphQLFactory.createSchema({ typeDefs });
consumer
.apply(graphqlExpress(req => ({ schema: {}, rootValue: req })))
.forRoutes({ path: '/graphql', method: RequestMethod.ALL });
Trying to configure GraphQL subscriptions using existing express server.
But seems that there is some kind of conflict.
Error thrown in graphiql
console:
WebSocket connection to 'ws://localhost:3000/subscriptions' failed: Connection closed before receiving a handshake response

When using new server. There is no error.
Here the graphQL configuration I've used:
this.setSameServer()
- uses nest http server instance.
this.setDifferentServer()
- uses new http instance.
import {
MiddlewareConsumer,
Module,
HttpServer,
Inject,
NestModule,
OnModuleDestroy,
} from '@nestjs/common';
import { AppController } from 'app.controller';
import { AppService } from 'app.service';
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import { GraphQLModule, GraphQLFactory } from '@nestjs/graphql';
import { AuthorResolver } from 'author.resolver';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { HTTP_SERVER_REF } from '@nestjs/core';
@Module({
imports: [GraphQLModule, AuthorResolver],
controllers: [AppController],
providers: [
{
provide: 'SUBSCRIPTION_SERVER',
useFactory: () => {
const server = createServer();
return new Promise(resolve => server.listen(88, () => resolve(server)));
},
},
AppService,
],
})
export class AppModule implements NestModule, OnModuleDestroy {
private subscriptionServer: SubscriptionServer;
private subscriptionPort: number;
private wsServer: HttpServer;
constructor(
private readonly graphQLFactory: GraphQLFactory,
@Inject(HTTP_SERVER_REF) private readonly httpServerRef: HttpServer,
@Inject('SUBSCRIPTION_SERVER') private readonly ws: HttpServer,
) {
this.setSameServer();
//this.setDifferentServer();
}
private setSameServer() {
this.wsServer = this.httpServerRef.getHttpServer();
this.subscriptionPort = 3000;
}
private setDifferentServer() {
this.wsServer = this.ws;
this.subscriptionPort = 88;
}
public configure(consumer: MiddlewareConsumer) {
const typeDefs = this.graphQLFactory.mergeTypesByPaths('./**/*.graphql');
const schema = this.graphQLFactory.createSchema({ typeDefs });
const route = '/graphql';
const routeIDE = '/graphiql';
const routeSubs = '/subscriptions';
const middlewareIDE = graphiqlExpress({
endpointURL: route,
subscriptionsEndpoint:
'ws://localhost:' + this.subscriptionPort + routeSubs,
});
const middleware = graphqlExpress(req => ({
schema,
rootValue: req,
debug: false,
}));
consumer.apply(middleware).forRoutes(route);
consumer.apply(middlewareIDE).forRoutes(routeIDE);
this.subscriptionServer = new SubscriptionServer(
{
execute,
subscribe,
schema,
},
{
server: this.wsServer,
path: routeSubs,
},
);
}
public onModuleDestroy() {
this.subscriptionServer.close();
}
}
Used these issues for help:
nestjs/nest#500
#6
And full repo if you want to reproduce:
https://github.com/ph55/nest-graphql-subscriptions
I'm submitting a...
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Current behavior
typePaths
is mandatory and dominant, without it on graphql.mergeTypes it will throw an error.
Expected behavior
I should be able to use a pre-cooked schema out of the box.
Minimal reproduction of the problem with instructions
GraphQLModule.forRootAsync({
imports: [
TypeGQLModule.forSchema({
resolvers: [
DefaultResolver,
...ModuleLocator.flattenModuleField('resolvers')
],
pubSub,
authChecker
})
],
async useFactory(graphQL: GraphQlBridge): Promise<GqlModuleOptions> {
const schema: GraphQLSchema = graphQL.buildSchema()
const playground: any = {
settings: {
'editor.cursorShape': 'line'
}
}
return {
schema,
introspection: true,
tracing: true,
context: ({ req, res }) => ({
req,
res
}),
playground
}
},
inject: [GraphQlBridge]
})
],
It failed with:
Error: Specified query type "Query" not found in document.
at E:\typescript-starter\node_modules\graphql\utilities\buildASTSchema.js:184:15
at Array.forEach (<anonymous>)
at getOperationTypes (E:\typescript-starter\node_modules\graphql\utilities\buildASTSchema.js:177:27)
at Object.buildASTSchema (E:\typescript-starter\node_modules\graphql\utilities\buildASTSchema.js:127:36)
at Object.buildSchemaFromTypeDefinitions (E:\typescript-starter\node_modules\graphql-tools\dist\generate\buildSchemaFromTypeDefinitions.js:24:28)
at Object.makeExecutableSchema (E:\typescript-starter\node_modules\graphql-tools\dist\makeExecutableSchema.js:27:29)
at GraphQLFactory.mergeOptions (E:\typescript-starter\node_modules\@nestjs\graphql\dist\graphql.factory.js:30:98)
at Function.<anonymous> (E:\typescript-starter\node_modules\@nestjs\graphql\dist\graphql.module.js:73:55)
at Generator.next (<anonymous>)
at E:\typescript-starter\node_modules\@nestjs\graphql\dist\graphql.module.js:19:71
at new Promise (<anonymous>)
at __awaiter (E:\typescript-starter\node_modules\@nestjs\graphql\dist\graphql.module.js:15:12)
at Object.useFactory [as metatype] (E:\typescript-starter\node_modules\@nestjs\graphql\dist\graphql.module.js:71:68)
at resolveConstructorParams (E:\typescript-starter\node_modules\@nestjs\core\injector\injector.js:68:55)
at Injector.resolveConstructorParams (E:\typescript-starter\node_modules\@nestjs\core\injector\injector.js:99:30)
at process._tickCallback (internal/process/next_tick.js:68:7)
What is the motivation / use case for changing the behavior?
I used MagnusCloudCorp/nestjs-type-graphql instead of the helpers from @nestjs/graphql
provided out of the box and TypeGraphQL provided a compiled schema instead of SDL.
Environment
Extra info
This is the reason it failed:
|
mergeOptions(options: GqlModuleOptions = { typeDefs: [] }): GqlModuleOptions { |
|
const resolvers = extend( |
|
this.scalarsExplorerService.explore(), |
|
this.resolversExplorerService.explore(), |
|
); |
|
return { |
|
...options, |
|
typeDefs: undefined, |
|
schema: makeExecutableSchema({ |
|
resolvers: extend(resolvers, options.resolvers), |
|
typeDefs: gql` |
|
${options.typeDefs} |
|
`, |
|
}), |
|
}; |
|
} |
My schema option, no matter what are always gonna be
Object.assign
'd
I'm submitting a...
[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Current behavior
I want to implement two endpoints. For this goal I have two modules: AdminModule and SiteModule. In each module I imported GraphQLModule:
GraphQLModule.forRootAsync({
useFactory: async () => {
return {
typePaths: ['./src/admin/**/*.graphql'],
path: '/admin',
}
},
})
and
GraphQLModule.forRootAsync({
useFactory: async () => {
return {
typePaths: ['./src/site/**/*.graphql'],
path: '/site',
}
},
})
In this case only /admin
is available. When I request /site
it returns 404. From another side I can use forRoot
instead of forFootAsync
. In this case both endpoints work as expected. But I have to use forRootAsync
for have possibility to define allowResolversNotInSchema: true
by the issue described in #19. Without It I get error: Error: "Mutation" defined in resolvers, but not in schema
when in shared module I add some resolver which defined only in one of two schemes.
Expected behavior
Possibility for implement multiple endpoints
Minimal reproduction of the problem with instructions
- Use with example https://github.com/nestjs/nest/tree/master/sample/12-graphql-apollo/src
- Add two modules with configs as described above.
What is the motivation / use case for changing the behavior?
It is very convenient for have possibility for split public and protected API.
Environment
Nest version: 5.3.0
For Tooling issues:
- Node version: 10.1.0
- Platform: Windows
Does this package support Apollo Server 2.0 or the older version? I installed their release candidate for express (ap[email protected]). graphqlExpress is no longer available. import { graphqlExpress } from 'apollo-server-express';
How would I go about using nestjs/graphql with Apollo Server 2.0?
thank you
Hello,
Is there any good way to validate data in mutations like string length etc?
typescript mutation { createSth(name:"something", website:"http://test.com/") { id name website } }
How can i validate name or website data?
PS: Kamil, great job with nestjs!
Regards
Ho can the query method be passed to the right Query type parent?
Or how can the resolver class be annotated correctly in order to resolve?
.graphql
type CustomQuery{
foo: String
}
type Query {
mw: CustomQuery
}
CustomResolver
import { Query, Resolver } from '@nestjs/graphql';
@Resolver()
export class CustomResolver {
constructor() {}
@Query()
foo(): string {
return 'bar';
}
}
create schema
const typeDefs = this.graphQLFactory.mergeTypesByPaths( './**/*.graphql');
const schema = this.graphQLFactory.createSchema({ typeDefs });
result
{
"data": {
"mw": {
"foo": null
}
},
"extensions": {
"tracing": {
"version": 1,
"startTime": "2018-02-20T17:01:09.202Z",
"endTime": "2018-02-20T17:01:09.202Z",
"duration": 242964,
"execution": {
"resolvers": [
{
"path": [
"mw"
],
"parentType": "Query",
"fieldName": "mw",
"returnType": "CustomQuery",
"startOffset": 77828,
"duration": 96395
},
{
"path": [
"mw",
"foo"
],
"parentType": "CustomQuery",
"fieldName": "foo",
"returnType": "String",
"startOffset": 214124,
"duration": 8691
}
]
}
}
}
}
maybe relevant dependencies
{
"dependencies": {
"@nestjs/common": "4.6.4",
"@nestjs/core": "4.6.4",
"@nestjs/graphql": "2.0.0",
"@types/graphql": "0.12.4",
"graphql": "0.13.1",
"graphql-tools": "2.21.0"
}
}
A) What am I doing wrong?
B) Can anyone confirm that custom query types are not supported at the moment?
C) Would a PR supporting this via annotation be welcomed?
I have following code:
import {
Module,
MiddlewaresConsumer,
NestModule,
RequestMethod,
} from '@nestjs/common';
import { graphqlExpress } from 'apollo-server-express';
import { GraphQLModule, GraphQLFactory } from '@nestjs/graphql';
import {UsersModule} from './Users/users.module';
@Module({
imports: [GraphQLModule],
modules: [UsersModule],
export class ApplicationModule {
constructor(private readonly graphQLFactory: GraphQLFactory) {}
}
And application exits with following error:
[Nest] 24011 - 2018-2-13 13:06:05 [NestFactory] Starting Nest application...
[Nest] 24011 - 2018-2-13 13:06:05 [ExceptionHandler] Nest can't resolve dependencies of the ApplicationModule (?). Please verify whether [0] argument is available in the current context.
Error: Nest can't resolve dependencies of the ApplicationModule (?). Please verify whether [0] argument is available in the current context.
at Injector.<anonymous> (/home/tymur/Learning/nest/project/node_modules/@nestjs/core/injector/injector.js:160:23)
at Generator.next (<anonymous>)
at fulfilled (/home/tymur/Learning/nest/project/node_modules/@nestjs/core/injector/injector.js:4:58)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
at Function.Module.runMain (module.js:703:11)
at startup (bootstrap_node.js:190:16)
at bootstrap_node.js:662:3
1: node::Abort() [node]
2: 0x8c8099 [node]
3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [node]
4: 0xaddc5c [node]
5: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [node]
6: 0x3ab9ebd042fd
Aborted (core dumped)
UsersModule is dummy module:
import {Module} from '@nestjs/common';
import {UsersService} from './users.service';
import UsersController from './users.controller';
import {usersProviders} from './users.providers';
import {DatabaseModule} from '../common/database/database.module';
import {LibrariesModule} from '../Libraries/libraries.module';
import {UserResolver} from './user.resolver';
@Module({
// modules: [DatabaseModule, LibrariesModule],
// controllers: [UsersController],
// components: [
// UsersService,
// ...usersProviders,
// UsersResolver,
// ],
// exports: [
// UsersService,
// ],
})
export class UsersModule {}
but if i comment out modules: [UsersModule],
in ApplicationModule, everithing works fine. Same as commenting out constructor in application module. What im doing wrong?
Following code
const typeDefs = this.graphQLFactory.mergeTypesByPaths(
`src/@core/**/*.graphqls`,
`src/${process.env.APP_NAME}/**/*.graphqls`
);
will only generate type definitions for first pattern: src/@core/**/*.graphqls
, all next patterns not merged.
Manual merging fixes this issue:
import { fileLoader, mergeTypes } from 'merge-graphql-schemas';
const coreTypes = fileLoader(`src/@core/**/*.graphqls`);
const appTypes = fileLoader(`src/${process.env.APP_NAME}/**/*.graphqls`);
const types = coreTypes.concat(appTypes);
const typeDefs = mergeTypes(types);
Recommend Projects
-
-
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
An Open Source Machine Learning Framework for Everyone
-
The Web framework for perfectionists with deadlines.
-
A PHP framework for web artisans
-
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
Some thing interesting about web. New door for the world.
-
A server is a program made to process requests and deliver data to clients.
-
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Some thing interesting about visualization, use data art
-
Some thing interesting about game, make everyone happy.
-
Recommend Org
-
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Open source projects and samples from Microsoft.
-
Google ❤️ Open Source for everyone.
-
Alibaba Open Source for everyone
-
Data-Driven Documents codes.
-
China tencent open source team.
-