Graphql returing null - javascript

GraphQL returing hello type as NULL but everything is correct. What could me the possible reasons for this as everything is correct ?
const { ApolloServer, gql } = require("apollo-server")
const typeDefs = gql`
type Query {
hello: String
}
`
const Resolvers = {
Query: {
hello: () => {
return "World!"
},
}
}
const server = new ApolloServer({
typeDefs,
Resolvers
});
server.listen().then(({ url }) => {
console.log('Server is ready' + url);
})

Related

Insert data from javascript file into mongodb using graphql

I am new to using Graphql and MongoDB. I am trying to insert data from an existing javascript file where the data has been defined. I was trying to use a mutation in order to achieve this but I have no clue what I'm really doing. Any help would be nice.
const dotenv = require('dotenv');
dotenv.config();
const { ApolloServer, gql } = require('apollo-server');
const { MongoClient } = require('mongodb');
const items = require('./itemsListData');
const typeDefs = gql`
type Query {
items:[Item!]!
}
type Item{
id:ID!,
name:String!,
aisle:String!,
bay:String!,
price:Float!,
xVal:Int!,
yVal:Int!
}
type Mutation {
createItem(name: String!, aisle: String!): Item!
}
`;
console.log(items)
const resolvers = {
Query: {
items:() => items,
},
Item:{
id: ( { _id, id }) => _id || id,
},
Mutation: {
createItem: async(_, { name }, { db }) => {
// name:String!, bays:[Bay!]!, xStartVal:Int!, xEndVal:Int!, yStartVal:Int!, yEndVal:Int!
const newItem = {
items
}
// insert Item object into database
const result = await db.collection('Items').insert(newItem);
console.log("This is the result " + result);
return result.ops[0]; // first item in array is the item we just added
}
}
};
const start = async () => {
const client = new MongoClient("mongodb+srv://admin:admin#quickkartcluster.o0bsfej.mongodb.net/test", { useNewUrlParser: true, useUnifiedTopology: true });
await client.connect();
const db = client.db("QuickKart");
const context = {
db,
}
const server = new ApolloServer({
typeDefs,
resolvers,
context,
introspection: true
});
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
}
start();
here is my javascript data file
https://pastebin.com/wvGANBgR

Apollo GraphQL - TypeError: Cannot read property 'findOrCreateUser' of undefined

I'm following this tutorial https://www.apollographql.com/docs/tutorial/mutation-resolvers/#book-trips
and have ended up getting this error:
"TypeError: Cannot read property 'findOrCreateUser' of undefined",
" at login
Below is the function I use to call login:
mutation LoginUser {
login(email: "daisy#apollographql.com") {
token
}
}
The file below is where findOrCreateUser is called:
src/resolvers.js
module.exports = {
Mutation: {
login: async (_, {email}, {dataSources}) => {
const user = await dataSources.userAPI.findOrCreateUser({ email });
if (user) {
user.token = Buffer.from(email).toString('base64');
return user;
}
},
},
This is where dataSources is defined:
src/index.js
require('dotenv').config();
const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const { createStore } = require('./utils');
const resolvers = require('./resolvers');
const isEmail = require('isemail');
const LaunchAPI = require('./datasources/launch');
const UserAPI = require('./datasources/user');
const store = createStore();
const server = new ApolloServer({
context: async ({req}) => {
const auth = req.headers && req.headers.authorization || '';
const email = Buffer.from(auth, 'base64').toString('ascii');
if (!isEmail.validate(email)) return {user: null};
// find a user by their email
const users = await store.user.findOrCreate({ where: { email } });
const user = users && users[0] || null;
return { user: {...user.dataValues } };
},
dataSources: () => ({
launchAPI: new LaunchAPI(),
UserAPI: new UserAPI({store})
}),
typeDefs,
resolvers,
});
server.listen().then(() => {
console.log(`
Server is running!
Listening on port 4000
Explore at https://studio.apollographql.com/dev
`)
});
As xadm mentioned in the comment the issues is your usage of userAPI vs UserAPI. the datasource object is created in index.js in the following block
dataSources: () => ({
launchAPI: new LaunchAPI(),
UserAPI: new UserAPI({store})
}),
here you defined datasources.UserAPI however in resolvers.js you refer to it as datasources.userAPI (note the difference in capitalization of userAPI). Your problem can be resolved by changing the above code block to
dataSources: () => ({
launchAPI: new LaunchAPI(),
userAPI: new UserAPI({store})
}),

Can't get Graphql-tools to read my schema.graphql file

I am using Apollo-server-express and Graphql-tools. I have been all over the Graphql-tools documentation and I can't get this to work. I'm trying to get my schema.graphql file to import as my typeDefs. It seems like Graphql-tools should be making this easy, but something isn't falling into place.
index.js
const { ApolloServer } = require("apollo-server-express");
const { makeExecutableSchema } = require('#graphql-tools/schema');
const express = require("express");
const { join } = require("path");
const { loadSchema } = require("#graphql-tools/load");
const { GraphQLFileLoader } = require("#graphql-tools/graphql-file-loader");
const { addResolversToSchema } = require("#graphql-tools/schema");
const app = express();
const resolvers = {
Query: {
items: (parent, args, ctx, info) => {
return ctx.prisma.item.findMany();
},
},
Mutation: {
makeItem: (parent, args, context, info) => {
const newItem = context.prisma.item.create({
data: {
...args,
price: parseInt(Math.ceil(args.price * 100)),
},
});
return newItem;
},
deleteItem: (parent, args, context, info) => {
return context.prisma.item.delete({
where: {
id: args.id,
},
});
},
},
};
const schemaSource = loadSchemaSync(join(__dirname, "schema.graphql"), {
loaders: [new GraphQLFileLoader()],
});
const schema = makeExecutableSchema({
typeDefs: schemaSource,
resolvers,
});
const server = new ApolloServer({
schema,
resolvers,
});
server.applyMiddleware({ app });
app.listen(
{ port: 4000 },
() =>
console.log(
`🌎 => Backend server is now running on port http://localhost:4000`
)
);
schema.graphql
type Query {
items: [Item!]!
}
type Mutation {
makeItem(
piece: String!
image: String!
identifier: String!
price: Float!
itemNumber: Int!
): Item!
deleteItem(id: ID!): Item!
}
type Item {
id: ID!
piece: String!
image: String!
identifier: String!
price: Int!
itemNumber: Int!
}
In its current state I am getting an error that says: "Error: typeDefs must be a string, array or schema AST, got object"
As I understand it makeExecutableSchema should be doing all the necessary steps, like changing the schema into a string. I can't seem to figure out what is going on here and any help would be greatly appreciated.
loadSchemaSync will load a GraphQLSchema object using the provided pointer. You should use loadTypedefsSync instead.
const sources = loadTypedefsSync(join(__dirname, "schema.graphql"), {
loaders: [new GraphQLFileLoader()],
});
const typeDefs = sources.map(source => source.document)
const server = new ApolloServer({ typeDefs, resolvers })
If you want to use loadSchema, you don't need to use makeExecutableSchema because your schema has already been created. So you would do this instead as shown in the docs:
const schema = loadSchemaSync(join(__dirname, "schema.graphql"), {
loaders: [new GraphQLFileLoader()],
});
const resolvers = {...};
const schemaWithResolvers = addResolversToSchema({
schema,
resolvers,
});
const server = new ApolloServer({ schema: schemaWithResolvers })

GraphQL server with Deno

It works just once for the below code
import {
graphql,
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
buildSchema,
} from "https://cdn.pika.dev/graphql/^15.0.0";
import { serve } from "https://deno.land/std#0.50.0/http/server.ts";
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "RootQueryType",
fields: {
hello: {
type: GraphQLString,
resolve() {
return "world";
},
},
},
}),
});
var query = "{ hello }";
graphql(schema, query).then((result) => {
console.log(result);
});
How to keep it listening, just like express
Something like this
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello world!';
},
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
import {
graphql,
buildSchema,
} from "https://cdn.pika.dev/graphql/^15.0.0";
import {Application, Router} from "https://deno.land/x/oak/mod.ts";
var schema = buildSchema(`
type Query {
hello: String
}
`);
var resolver = {hello: () => 'Hello world!'}
const executeSchema = async (query:any) => {
const result = await graphql(schema, query, resolver);
return result;
}
var router = new Router();
router.post("/graph", async ({request, response}) => {
if(request.hasBody) {
const body = await request.body();
const result = await executeSchema(body.value);
response.body = result;
} else {
response.body = "Query Unknown";
}
})
let app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
console.log("Server running");
app.listen({port: 5000})
You can now use https://deno.land/x/deno_graphql to achieve this goal.
It provides everything needed out-of-the-box and works with multiple Deno frameworks (oak, abc, attain, etc).
This is how you code looks like (with oak for example):
import { Application, Context, Router } from "https://deno.land/x/oak/mod.ts";
import {
gql,
graphqlHttp,
makeExecutableSchema,
} from "https://deno.land/x/deno_graphql/oak.ts";
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => "Hello world!",
},
};
const context = (context: Context) => ({
request: context.request,
});
const schema = makeExecutableSchema({ typeDefs, resolvers });
const app = new Application();
const router = new Router();
router.post("/graphql", graphqlHttp({ schema, context }));
app.use(router.routes());
await app.listen({ port: 4000 });
PS : i'm the author of the package, so you can ask me anything.
Hope this helps!
Here is an example using oak working with your GraphQL code.
First let's say you have a repository graphRepository.ts with your graph schema:
import {
graphql,
GraphQLSchema,
GraphQLObjectType,
GraphQLString
} from "https://cdn.pika.dev/graphql/^15.0.0";
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "RootQueryType",
fields: {
hello: {
type: GraphQLString,
resolve() {
return "world";
},
},
},
}),
});
export async function querySchema(query: any) {
return await graphql(schema, query)
.then(async (result) => {
return result;
});
}
Now start your app.ts listener with the routes, and use the following URL to call the endpoint:
http://localhost:8000/graph/query/hello
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { querySchema } from "./graphRepository.ts";
const router = new Router();
router
.get("/graph/query/:value", async (context) => {
const queryValue: any = context.params.value;
const query = `{ ${queryValue}}`
const result = await querySchema(query);
console.log(result)
context.response.body = result;
})
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 });
here is a code example using oak and middleware.
You also can enjoy the playground GUI like an apollo one.
import { Application } from "https://deno.land/x/oak/mod.ts";
import { applyGraphQL, gql } from "https://deno.land/x/oak_graphql/mod.ts";
const app = new Application();
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.headers.get("X-Response-Time");
console.log(`${ctx.request.method} ${ctx.request.url} - ${rt}`);
});
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.response.headers.set("X-Response-Time", `${ms}ms`);
});
const types = gql`
type User {
firstName: String
lastName: String
}
input UserInput {
firstName: String
lastName: String
}
type ResolveType {
done: Boolean
}
type Query {
getUser(id: String): User
}
type Mutation {
setUser(input: UserInput!): ResolveType!
}
`;
const resolvers = {
Query: {
getUser: (parent: any, {id}: any, context: any, info: any) => {
console.log("id", id, context);
return {
firstName: "wooseok",
lastName: "lee",
};
},
},
Mutation: {
setUser: (parent: any, {firstName, lastName}: any, context: any, info: any) => {
console.log("input:", firstName, lastName);
return {
done: true,
};
},
},
};
const GraphQLService = applyGraphQL({
typeDefs: types,
resolvers: resolvers
})
app.use(GraphQLService.routes(), GraphQLService.allowedMethods());
console.log("Server start at http://localhost:8080");
await app.listen({ port: 8080 });
I have created gql for making GraphQL servers that aren't tied to a web framework. All of the responses above show Oak integration but you don't really have to use it to have a GraphQL server. You can go with std/http instead:
import { serve } from 'https://deno.land/std#0.90.0/http/server.ts'
import { GraphQLHTTP } from 'https://deno.land/x/gql/mod.ts'
import { makeExecutableSchema } from 'https://deno.land/x/graphql_tools/mod.ts'
import { gql } from 'https://deno.land/x/graphql_tag/mod.ts'
const typeDefs = gql`
type Query {
hello: String
}
`
const resolvers = {
Query: {
hello: () => `Hello World!`
}
}
const schema = makeExecutableSchema({ resolvers, typeDefs })
const s = serve({ port: 3000 })
for await (const req of s) {
req.url.startsWith('/graphql')
? await GraphQLHTTP({
schema,
graphiql: true
})(req)
: req.respond({
status: 404
})
}

GraphQL: field.resolve() result is undefined inside directive

I've been following all the results I found on Google on how to make an AuthDirective but I can't make it work.
I'll leave all the files to see if I'm making an error on the implementation but I guess not because I tested even without having any conditions inside the field.resolve.
One particular thing I found is that field.resolve, comes with 4 args, the first of them is always undefined, not sure if that could be it but just as an additional tip.
So here's the code:
This is a part of my typedefs
directive #isAuthenticated on FIELD_DEFINITION
scalar Date
type User {
id: ID,
name: String
email: String
password: String
createdAt: Date
}
type Token {
token: String
}
# IF I REMOVE #isAuthenticated this works!
type Query {
user(name: String): User! #isAuthenticated
users: [User!]! #isAuthenticated
}
type Mutation {
createUser(name: String, email: String, password: String): Boolean!
login(email: String!, password: String!): Token!
}
Here is my schema:
import path from 'path';
import { makeExecutableSchema } from 'graphql-tools';
import { fileLoader, mergeResolvers, mergeTypes } from 'merge-graphql-schemas';
import schemaDirectives from './Directives';
const typedefsArray = fileLoader(path.join(__dirname, './**/*.graphql'));
const resolversArray = fileLoader(path.join(__dirname, './**/*.resolvers.ts'));
const typeDefs = mergeTypes(typedefsArray);
const resolvers = mergeResolvers(resolversArray);
const schema = makeExecutableSchema({ typeDefs, resolvers, schemaDirectives });
export default schema;
Here is my AuthDirective
import { defaultFieldResolver } from 'graphql';
import { AuthenticationError, SchemaDirectiveVisitor } from 'apollo-server-express';
class AuthDirective extends SchemaDirectiveVisitor {
visitFieldDefinition(field: any) {
const { resolver = defaultFieldResolver } = field;
field.resolve = async function (...args: any) {
const [_, __, context] = args;
const { req } = context;
const accessToken = req.headers.authorization
? req.headers.authorization.replace('Bearer ', '')
: null;
if (accessToken) {
// here I was doing jwt.verify(accessToken) but I removed it for now to simplify
const result = await resolver.apply(this, args);
return result; // <--- THIS IS ALWAYS UNDEFINED
} else {
throw new AuthenticationError('Unauthorized field');
}
};
}
}
export default AuthDirective;
which lives under ./Directives and is being exported from an index as:
import AuthDirective from './auth';
export default {
isAuthenticated: AuthDirective
}
Finally my user resolver. Like I said before, if I remove the directive from the user graphql query its working as it should:
import jwt from 'jsonwebtoken';
import { AuthenticationError, UserInputError } from 'apollo-server-express';
import { IUser } from './IUser';
import UserModel from './user.schema';
import { Config } from '../../config';
const { APP_SECRET } = Config;
const createToken = async (user: IUser, secret: string, expiresIn: string) => {
const { id, email, name } = user;
return jwt.sign({ id, email, name }, secret, { expiresIn });
};
const userResolvers = {
Query: {
user: (_: any, { name }: { name: string }) => UserModel.findOne({ name }).exec(),
users: () => UserModel.find({}).exec()
},
Mutation: {
createUser: async (_: any, args: IUser) => {
await new UserModel(args).save();
return true;
},
login: async (_: any, { email, password }: IUser) => {
const user = await UserModel.findOne({ email }).exec();
if (!user) {
throw new UserInputError('No user found with this login credentials.');
}
const isValid = await user.validatePassword(password);
if (!isValid) {
throw new AuthenticationError('Invalid password.');
}
return { token: createToken(user, APP_SECRET, '30m') };
}
}
};
export default userResolvers;
and my server:
import morgan from 'morgan';
import express from 'express';
import bodyParser from 'body-parser';
import compression from 'compression';
import depthLimit from 'graphql-depth-limit';
import { ApolloServer } from 'apollo-server-express';
import { Config, DBConfig } from './config';
import schema from './domain';
const { PORT } = Config;
const app = express();
const apolloServer = new ApolloServer({
schema,
validationRules: [depthLimit(7)],
context: ({ req, res }: any) => ({ req, res })
});
app.use(express.json());
app.use(compression());
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({ extended: true }));
apolloServer.applyMiddleware({ app });
DBConfig.init();
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
There is no resolver property on field, so this
const { resolver = defaultFieldResolver } = field;
will always result in resolver having the value of defaultFieldResolver. If you're using the directive on some field that had a custom resolver, that custom resolver is never being called -- only the default behavior is used, which could indeed return undefined.
You need to make sure you're using the correct property:
const { resolve = defaultFieldResolver } = field;
or you can rename the resulting variable when you destructure field:
const { resolve: resolver = defaultFieldResolver } = field;

Categories

Resources