Error when building typedefs TypeError: Cannot read property 'some' of undefined - graphql

I am getting the following error when building Typedefs in Apollo Server:
return typeDef.definitions.some(definition => definition.kind === language_1.Kind.DIRECTIVE_DEFINITION &&
^
TypeError: Cannot read property 'some' of undefined
I tried to follow some solutions from here https://github.com/apollographql/apollo-server/issues/2961 but still, I am getting the error.
This is how I am creating the schema:
fs.readdirSync(__dirname)
.filter(dir => { console.log('dir', dir); return dir.indexOf('.') < 0 })
.forEach((dir) => {
const tmp = require(path.join(__dirname, dir)).default;
resolvers = merge(resolvers, tmp.resolvers);
typeDefs.push(tmp.types);
});
const schema = new ApolloServer({
typeDefs,
resolvers,
playground: {
endpoint: '/graphql',
settings: {
'editor.theme': 'light'
}
}
});
type.js
const Book = gql`
type Book {
title: String!
author: String!
}
`;
export const types = () => [Book];
export const typeResolvers = {
};
mutation.js
const Mutation = gql`
extend type Mutation {
addBook(book: BookInput): Book
}
`;
export const mutationTypes = () => [Mutation];
export const mutationResolvers = {
Mutation: {
addBook: async (_, args, ctx) => {
return []
}
}
};
index.js
export default {
types: () => [types, queryTypes, inputTypes, mutationTypes],
resolvers: Object.assign(queryResolvers, mutationResolvers, typeResolvers),
};
Any suggestions? What could I be missing?

I just had the same issue for the past 2 hours. I realized the file were i was instantiating my apollo server was being executed before the typedefs was created.
Simple way to test for this is to make a console.log(types, queryTypes, inputTypes, mutationTypes) right before the execution of const schema = new ApolloServer({ ....
One of them is undefined. Thanks.

After spending some time making changes, I finally got a working solution.
I had to make sure that typeDefs was an array of GraphQL Documents and not a type of [Function: types]. To do that, I removed unnecessary function syntax.
For example:
I replaced this export const types = () => [Book]; with this export const types = Book;
I replaced this types: () => [types, queryTypes, inputTypes, mutationTypes] with types: [types, queryTypes, inputTypes, mutationTypes]
... and pretty much every where I had () =>
Finally, before instantiating ApolloServer, instead of pushing tmp.types to the array of types, I used concat to use all defined graphql types in the I had defined the current file 'plus' the graphql types imported in every directory
typeDefs = typeDefs.concat(tmp.types);

Related

graphql / Apollo test case fails Error: Expected one matching operation for criteria "Match DocumentNode", found none

I am trying to write a test for an angular service which I am using with graphql & Apollo.
I'm receiving these errors: Error: Expected one matching operation for criteria "Match DocumentNode", found none.
and
Error: Expected no open operations, found 1:
foo.spec.ts
import { TestBed } from '#angular/core/testing';
import {
....
const fragment: DocumentNode = gql`
fragment SummaryDetails on SummaryDetails {
foo
...
}
`;
const summaryQuery: DocumentNode = gql`
query Summary(
) {
Summary(
) {
...SummaryDetails
}
}
${fragment}
`;
const fundDataServiceParams: FundDataServiceParams = {
foo ...
};
const expectedRawSummaryDetails: any = {
Summary: [
{
foo ...
},
],
};
const expectedSummaryDetails: SummaryDetail[] = [
{
foo ...
},
];
describe('FundSummaryServiceRegisterMethod', () => {
let controller: ApolloTestingController;
let fundSummaryService: FundSummaryService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ApolloTestingModule, HttpClientTestingModule],
});
controller = TestBed.inject(ApolloTestingController);
foo = TestBed.inject(foo);
});
afterEach(() => {
controller.verify();
});
fit('should return foodetails', (done: DoneFn) => {
fundSummaryService
.register(fragment, fundDataServiceParams)
.subscribe((foo) => {
expect(foo).toEqual(foo);
done();
});
const op = controller.expectOne(fooQuery);
expect(op.operation.variables.foo).toEqual(foo.foo);
op.flushData(expectedfoo);
});
});
Note: I tried this old post's suggestion, didn't work.
The good news for you is that in the afterEach, controller.verify() is failing meaning there is a query in queue and not all of them have been dealt with. I am thinking that your summaryQuery is slightly off where it is not matching exactly the query where the afterEach is saying is still in queue and has not been flushed.
I think you can use a different definition of expectOne from the documentation to match the query in queue. I don't have much experience with Apollo or GraphQL but try something like this for the expectOne:
const op = controller.expectOne(operation => {
// can assert some stuff on the operation like the documentation shows
return true;
});
If the above works, it most likely means that summaryQuery does not match the query that ApolloTestingController sees.

TypeGraphQl: Usage with Netlify Functions/AWS Lambda

I was finally able to get TypeQL working with Netlify Functions / AWS Lambda after a day of work, going over the docs and examples, and in the end desperate brute force.
I'm sharing my working code here for others (or for future reference of my own :P ) as it contains some counterintuitive keyword usage.
Normal Approach
The error I kept getting when using the simple example was:
Your function response must have a numerical statusCode. You gave: $ undefined
I searched of course in the issues, but none of the suggested solutions worked for me.
Working Code
import 'reflect-metadata'
import { buildSchema } from 'type-graphql'
import { ApolloServer } from 'apollo-server-lambda'
import { RecipeResolver } from 'recipe-resolver'
async function lambdaFunction() {
const schema = await buildSchema({
resolvers: [RecipeResolver],
})
const server = new ApolloServer({
schema,
playground: true,
})
// !!! NOTE: return (await ) server.createHandler() won't work !
exports.handler = server.createHandler()
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!! NOTE: weird but only way to make it work with
// AWS lambda and netlify functions (netlify dev)
// also needs a reload of the page (first load of playground won't work)
lambdaFunction()
// exports.handler = lambdaFunction wont work
// export { lambdaFunction as handler } wont work
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Also I got some reflection errors from the simple example
Unable to infer GraphQL type from TypeScript reflection system. You need to provide explicit type for argument named 'title' of 'recipe' of 'RecipeResolver
So I had to figure out how to add explicit type to #Arg:
// previous:
// recipe(#Arg('title') title: string)
// fixed:
recipe( #Arg('title', (type) => String) title: string
I share the code that works for me
// File: graphql.ts
import 'reflect-metadata'
import { buildSchema } from 'type-graphql'
import { ApolloServer } from 'apollo-server-lambda'
import { ApolloServerPluginLandingPageGraphQLPlayground } from 'apollo-server-core'
import { RecipeResolver } from './recipe-resolver'
export const createHandler = async function(){
const schema = await buildSchema({
resolvers: [RecipeResolver],
})
const server = new ApolloServer({
schema,
introspection: true,
plugins: [ApolloServerPluginLandingPageGraphQLPlayground()],
})
return server.createHandler()
}
export const handler = async function(event, context, callback) {
const graphqlHandler = await createHandler()
return await graphqlHandler(event, context, callback)
}
// Lambda: graphql.handler
node16.x
type-graphql ^1.1.1
graphql ^15.3.0
apollo-server-lambda: ^3.10.2

Apollo on local client doesn't trigger the local resolvers

Apollo doesn't trigger the resolvers in the case of Local state Client (frontent local state). Apollo 2.7
Does anyone have any idea why it happens?
Here is the setup:
Apollo client
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import fetch from 'isomorphic-unfetch'
import { resolvers, typeDefs } from './resolvers';
import { initCache } from './init-cache';
export default function createApolloClient(initialState, ctx) {
// The `ctx` (NextPageContext) will only be present on the server.
// use it to extract auth headers (ctx.req) or similar.
return new ApolloClient({
ssrMode: Boolean(ctx),
link: new HttpLink({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
credentials: 'include', // Additional fetch() options like `credentials` or `headers`
fetch,
}),
typeDefs,
resolvers,
connectToDevTools: true,
cache: initCache({
robot: {
__typename: 'Robot',
name: 'Robbie',
status: 'live',
},
member: {
__typename: 'Member',
name: 'RFesagfd',
}
}),
})
}
Types & resolvers (resolvers.js)
import gql from 'graphql-tag';
export const typeDefs = gql`
type Robot {
name: String!
status: String!
}
type Member {
name: String!
isLogged: Boolean!
}
`;
export const resolvers = {
Member: {
isLogged: (...args) => {
console.log('args', args); // THIS NEVER TRIGGERS SOMEHOW
return true;
}
}
};
Query
const GET_IS_MEMBER_LOGGED = gql`
query isMemberLogged {
member #client {
name
isLogged
}
}
`;
Thanks for any help!
You need to define result type of local queries:
const typeDefs = gql`
extend type Query {
robot: Robot
member: Member
}
... and resolver for your query - not type (as you decorated entire query as local)... but you have to return typed data:
export const resolvers = {
Query: {
member: (...args) => {
console.log('args', args);
return {
__typename: 'Member',
name: 'some name', // read from cache
isLogged: true // function result
};
}
}
};
You should also use __typename for cache writes.
update
assuming you have a Memeber in cache ... you can:
// read (initialized with permanent) data:
const memberData = cache.readQuery(....
// f.e. it should have `__typename` and 'name`
// ... and 'decorate' it with derived properites
memberData.age = currentYear - memberData.birthYear;
memberData.isLogged = someFuncReturningBool();
return memberData; // Member type shaped object
It's about shape/data organization - typed (return type shaped object with defined properties) or simple (return all properties separately) or mixed, f.e. (some global app state)
const GET_IS_MEMBER_LOGGED = gql`
query profileViewData {
member #client {
name
isLogged
}
isProfilePanelOpen #client
termsAccepted #client
}
`;
I found a possible solution. Maybe this info will be useful for someone.
If we want to omit the Query Resolver + Field resolvers and we want to have the only Field resolver we need to use #client(always: true).
The in deep explanation
In general, there is a problem with how the Apollo client works with Cache.
By default, it caches the response, and next time it'll fetch the cached result from the cache (eg. optimistic UI). This behavior is the same even in the case of the Client.
It means when we have the initial model in cache Apollo will fetch in from the cache and ignores the resolvers, even if we pass the #client directive.
To solve this problem and let Apollo know that we need to use Local resolvers EVEN if we have a cached object, we need to use #client(always: true) for the preferred field or the whole object. I made an example below.
P.S. Unfortunately I didn't find how to force Apollo to work with non-existing field so if we want to have some resolver for a specific field, we still need to define the initial field value it the initial Cached Model to let the Apollo know about this field. After that, Apollo will use resolver for it to generate some high-calculated output for this particular field, thanks to #client(always: true).
In general, it's ok, because we should know what kind of dynamic field we'll have in our model.
Apollo client
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import fetch from 'isomorphic-unfetch'
import { resolvers, typeDefs } from './resolvers';
import { initCache } from './init-cache';
export default function createApolloClient(initialState, ctx) {
// The `ctx` (NextPageContext) will only be present on the server.
// use it to extract auth headers (ctx.req) or similar.
return new ApolloClient({
ssrMode: Boolean(ctx),
link: new HttpLink({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
credentials: 'include', // Additional fetch() options like `credentials` or `headers`
fetch,
}),
typeDefs,
resolvers,
connectToDevTools: true,
cache: initCache({
author: {
__typename: 'Author',
posts: 0,
name: '' // NEED TO SET AN INITIAL VALUE
}
})
}
Types & resolvers (resolvers.js)
import gql from 'graphql-tag';
import { print } from 'graphql';
export const typeDefs = gql`
type Author {
posts: Int!
name: String
}
`;
export const resolvers = {
Author: {
name(author) {
console.log('Author name resolver', author). // WORKS
return 'NAME';
},
},
};
Query
const GET_AUTHOR = gql`
query getAuthor {
author {
posts
name #client(always: true)
}
}
`;

Not able to understand what this error means

enter image description hereI am trying to create graphql schema directive and trying to add it in makeExecutableSchema and the following error is occurring. Is there anyone who can help me understand this error or solve it.
const templateDirective = require('../index');
// Define your schema and resolvers if needed
const typeDefs = `
type Query {
me(): Me #templateDirective
}
`;
const resolvers = {
Query: {
me: () => false,
},
};
module.exports = makeExecutableSchema({
typeDefs,
resolvers,
schemaDirectives: {
templateDirective,
},
});
You have a syntax error in your document. If a field takes no arguments, you have to omit the parentheses, you cannot just have an empty set of parentheses after the field name. The corrected document:
type Query {
me: Me #templateDirective
}

Using graphql-tools to mock a GraphQL server seems broken

I've followed the documentation about using graphql-tools to mock a GraphQL server, however this throws an error for custom types, such as:
Expected a value of type "JSON" but received: [object Object]
The graphql-tools documentation about mocking explicitly states that they support custom types, and even provide an example of using the GraphQLJSON custom type from the graphql-type-json project.
I've provided a demo of a solution on github which uses graphql-tools to successfully mock a GraphQL server, but this relies on monkey-patching the built schema:
// Here we Monkey-patch the schema, as otherwise it will fall back
// to the default serialize which simply returns null.
schema._typeMap.JSON._scalarConfig.serialize = () => {
return { result: 'mocking JSON monkey-patched' }
}
schema._typeMap.MyCustomScalar._scalarConfig.serialize = () => {
return mocks.MyCustomScalar()
}
Possibly I'm doing something wrong in my demo, but without the monkey-patched code above I get the error regarding custom types mentioned above.
Does anyone have a better solution than my demo, or any clues as to what I might be doing wrong, and how I can change the code so that the demo works without monkey-patching the schema?
The relevant code in the demo index.js is as follows:
/*
** As per:
** http://dev.apollodata.com/tools/graphql-tools/mocking.html
** Note that there are references on the web to graphql-tools.mockServer,
** but these seem to be out of date.
*/
const { graphql, GraphQLScalarType } = require('graphql');
const { makeExecutableSchema, addMockFunctionsToSchema } = require('graphql-tools');
const GraphQLJSON = require('graphql-type-json');
const myCustomScalarType = new GraphQLScalarType({
name: 'MyCustomScalar',
description: 'Description of my custom scalar type',
serialize(value) {
let result;
// Implement your own behavior here by setting the 'result' variable
result = value || "I am the results of myCustomScalarType.serialize";
return result;
},
parseValue(value) {
let result;
// Implement your own behavior here by setting the 'result' variable
result = value || "I am the results of myCustomScalarType.parseValue";
return result;
},
parseLiteral(ast) {
switch (ast.kind) {
// Implement your own behavior here by returning what suits your needs
// depending on ast.kind
}
}
});
const schemaString = `
scalar MyCustomScalar
scalar JSON
type Foo {
aField: MyCustomScalar
bField: JSON
cField: String
}
type Query {
foo: Foo
}
`;
const resolverFunctions = {
Query: {
foo: {
aField: () => {
return 'I am the result of resolverFunctions.Query.foo.aField'
},
bField: () => ({ result: 'of resolverFunctions.Query.foo.bField' }),
cField: () => {
return 'I am the result of resolverFunctions.Query.foo.cField'
}
},
},
};
const mocks = {
Foo: () => ({
// aField: () => mocks.MyCustomScalar(),
// bField: () => ({ result: 'of mocks.foo.bField' }),
cField: () => {
return 'I am the result of mocks.foo.cField'
}
}),
cField: () => {
return 'mocking cField'
},
MyCustomScalar: () => {
return 'mocking MyCustomScalar'
},
JSON: () => {
return { result: 'mocking JSON'}
}
}
const query = `
{
foo {
aField
bField
cField
}
}
`;
const schema = makeExecutableSchema({
typeDefs: schemaString,
resolvers: resolverFunctions
})
addMockFunctionsToSchema({
schema,
mocks
});
// Here we Monkey-patch the schema, as otherwise it will fall back
// to the default serialize which simply returns null.
schema._typeMap.JSON._scalarConfig.serialize = () => {
return { result: 'mocking JSON monkey-patched' }
}
schema._typeMap.MyCustomScalar._scalarConfig.serialize = () => {
return mocks.MyCustomScalar()
}
graphql(schema, query).then((result) => console.log('Got result', JSON.stringify(result, null, 4)));
I and a few others are seeing a similar issue with live data sources (in my case MongoDB/Mongoose). I suspect it is something internal to the graphql-tools makeExecutableSchema and the way it ingests text-based schemas with custom types.
Here's another post on the issue: How to use graphql-type-json package with GraphQl
I haven't tried the suggestion to build the schema in code, so can't confirm whether it works or not.
My current workaround is to stringify the JSON fields (in the connector) when serving them to the client (and parsing on the client side) and vice-versa. A little clunky but I'm not really using GraphQL to query and/or selectively extract the properties within the JSON object. This wouldn't be optimal for large JSON objects I suspect.
If anyone else comes here from Google results, the solution for me was to add the JSON resolver as parameter to the makeExecutableSchema call. It's described here:
https://github.com/apollographql/apollo-test-utils/issues/28#issuecomment-377794825
That made the mocking work for me.

Resources