GraphQLError: Syntax Error: Expected Name, found ":" - graphql

I am trying to Prisma along side with Apollo Server
and I keep getting this error
GraphQLError: Syntax Error: Expected Name, found ":"
this is the index.ts file
import { PrismaClient } from '#prisma/client';
import { ApolloServer } from 'apollo-server';
import { typeDefs } from './schema/schema';
import { Query } from './resolvers/Query';
import { Mutation } from './resolvers/Mutation';
const prisma = new PrismaClient();
const server = new ApolloServer({
typeDefs,
resolvers: {
Query,
Mutation,
},
context: {
prisma,
},
});
server.listen().then(({ url }: any) => {
console.log(`Server is running on ${url}`);
});
this is the schema.ts file
const { gql } = require('apollo-server');
export const typeDefs = gql`
type Query {
getProducts: [Product!]!
}
type Mutation {
addProduct(input: addProductInput): Boolean!
}
type Product {
name: String!
price: Float!
description: : String!
}
input addProductInput {
name: String!
price: Float!
description: : String!
}
`;
this is the Query.ts file in the resolvers folder
export const Query = {
getProducts: async (parent: any, args: any, { prisma }: any) => {
return await prisma.products.findMany();
},
};
this is the Query.ts file in the resolvers folder
export const Mutation = {
addProduct: async (parent: any, { input }: any, { prisma }: any) => {
const productData = {
name: input.name,
price: input.price,
description: input.description,
};
await prisma.products.create({
data: productData,
});
return true;
},
};
and lastly this is the Product model in schema.prisma file
model Product {
##map(name: "products")
id Int #id #default(autoincrement())
name String
price Float
description String
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
}
I have done some researches and all I got is that might be a missing bracket or a curly bracket, but I reviewed my code multiple times and did not find any mistakes.

In the schema definition, pay close attention to the Product type and addProductInput:
type Product {
name: String!
price: Float!
description: : String!
}
input addProductInput {
name: String!
price: Float!
description: : String!
}
`;
Are you sure the description fields should have two colons? I think they shouldn't have the middle one, and just be like description: String!

Related

How can I make GraphQL support int8 type in Supabase?

I'm creating a simple CRUD app to learn GraphQL and am using a Supabase postgres instance. All queries and mutations work fine except for one thing, I can't get the id field from my schemas because they are of type int8 on Supabase, and GraphQL only supports Int.
I'm getting this error when I try to get a row's id using the gql Int type in my type defs: GraphQLError: Int cannot represent non-integer value: 1
I know the solution involves creating a custom scalar type as in this example, but I'm not sure how to implement this type. Also, I cannot change this on Supabase's side, so I must find a way to handle this in gql. How can I handle this type in GraphQL?
TypeDefs:
export const typeDefs = `#graphql
type User {
id: Int!
name: String!
email: String!
age: Int!
verified: Boolean!
}
type Todo {
id: Int!
title: String!
description: String!
}
type Query {
# users queries
getAllUsers: [User]
getUser(email: String!): User
# todo queries
getAllTodos: [Todo]
getTodo(id: String!): Todo
}
type Mutation {
createUser(name: String!, email: String!, age: Int!): User
createTodo(title: String!, description: String!): Todo
}
`;
Resolvers:
import { GraphQLScalarType } from 'graphql';
import { prisma } from '../lib/db.js';
const BigInt = new GraphQLScalarType({
// how do I implement this type?
});
export const resolvers = {
BigInt,
Query: {
getAllUsers() {
return prisma.user.findMany();
},
getUser(parent, args) {
return prisma.user.findUnique({
where: {
email: args.email,
},
});
},
getAllTodos() {
return prisma.todo.findMany();
},
getTodo(parent, args) {
return prisma.todo.findUnique({
where: {
id: args.id,
},
});
},
},
// parent, arge are other arguments that get passes to resolvers automatically
Mutation: {
createUser(parent, args) {
return prisma.user.create({
data: args,
});
},
createTodo(parent, args) {
return prisma.todo.create({
data: args,
});
},
},
};
Solved this by using the graphql-type-ints package. You can just install it and then add the type you need to your schemas and resolvers. However, I don't quite understand why we need to do this. If someone could explain why Supabase uses int8 and that doesn't conform to graphql's Int I would appreciate it.

I have error on apollo server and grapghql

This is the error am getting
node_modules\apollo-server-core\dist\ApolloServer.js:358
throw Error('Apollo Server requires either an existing schema, modules or typeDefs');
Here is my code:
users.typeDefs.js
On top I have "import { gql } from "apollo-server";
export default gql `"
type User {
id: String!
firstName: String!
lastName: String
username: String!
email: String!
createdAt: String!
updatedAt: String!
}
type Mutation {
createAccount(
firstName: String!
lastName: String
username: String!
email: String!
password: String!
): User
}
type Query {
seeProfile(username:String): User
}
`;
Here is my users.mutations.js
On top I have:
import { PrismaClient } from "#prisma/client";
import client from "../client";"
Here is the main code:
export default {
Mutation: {
createAccount: async (
_, {
firstName,
lastName,
username,
email,
password
}
) => {
//check if username or email are already on DB.
const existingUser = await client.user.findFirst({
where: {
OR: [
{
username,
},
{
email,
}
],
},
});
console.log(existingUser);
// hash password
// save and return the user
},
} ,
};
The users.queries.js is export default,
Here is my schema.js and client.js
import { mergeTypeDefs, mergeResolvers, } from "#graphql-tools/merge";
import { loadFilesSync } from "#graphql-tools/load-files";
import { makeExecutableSchema } from "#graphql-tools/schema";
const loadedTypes = loadFilesSync(`${__dirname}/**/*.typeDefs.js`);
const loadedResolvers = loadFilesSync(`${__dirname}/**/*.{queries,mutations}.js`);
const typeDefs = mergeTypeDefs(loadedTypes);
const resolvers = mergeResolvers(loadedResolvers);
const schema = makeExecutableSchema({typeDefs, resolvers});
export default schema;
import { PrismaClient } from "#prisma/client";
const client = new PrismaClient ();
export default client;
Here is also my server.js
require ("dotenv").config();
import { ApolloServer, gql } from "apollo-server";
import {schema} from "./schema";
const server = new ApolloServer({
schema,
});
const PORT = process.env.PORT
server.listen(PORT).then(() => {
console.log(`🚀 Server ready at http://localhost:${PORT} ✅ `);
});

How to pass params to child property in GraphQL

i am pretty new to GraphQL, getting to become a huge fan :)
But, something is not clear to me. I am using Prisma with and GraphQL-Yoga with Prisma bindings.
I do not know how to pass params from my graphQL server to sub properties. Don't know if this is clear, but i will show it with code, thats hopefully easier :)
These are my types
type User {
id: ID! #unique
name: String!
posts: [Post!]!
}
type Post {
id: ID! #unique
title: String!
content: String!
published: Boolean! #default(value: "false")
author: User!
}
My schema.graphql
type Query {
hello: String
posts(searchString: String): [Post]
users(searchString: String, searchPostsTitle: String): [User]
me(id: ID): User
}
and my users resolver:
import { Context } from "../../utils";
export const user = {
hello: () => "world",
users: (parent, args, ctx: Context, info) => {
return ctx.db.query.users(
{
where: {
OR: [
{
name_contains: args.searchString
},
{
posts_some: { title_contains: args.searchPostsTitle }
}
]
}
},
info
);
},
me: (parent, args, ctx: Context, info) => {
console.log("parent", parent);
console.log("args", args);
console.log("info", info);
console.log("end_________________");
return ctx.db.query.user({ where: { id: args.id } }, info);
}
};
and my posts resolver
import { Context } from "../../utils";
export const post = {
posts: (parent, args, ctx: Context, info) => {
return ctx.db.query.posts(
{
where: {
OR: [
{
title_contains: args.searchString
},
{
content_contains: args.searchString
}
]
}
},
info
);
}
};
so, now :)
I am able to do the following when i am in the GraphQL playground on my prisma service:
{
user(where: {id: "cjhrx5kaplbu50b751a3at99d"}) {
id
name
posts(first: 1, after: "cjhweuosv5nsq0b75yc18wb2v") {
id
title
content
}
}
}
but i cant do it on the server, if i do something like that.. i am getting the error:
"error": "Response not successful: Received status code 400"
this is what i am trying:
{
me(id: "cjhrx5kaplbu50b751a3at99d") {
id
name
posts(first:1) {
id
title
content
}
}
}
does somebody know how i could do that?
since i have a custom type of user, posts does not have params like the generated one. Either i am using the the generated one, or modifying it to look like this:
type User {
id: ID!
name: String!
posts(where: PostWhereInput, orderBy: PostOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Post!]
}
EDIT 2018 June 4th
# import Post from './generated/prisma.graphql'
type Query {
hello: String
posts(searchString: String): [Post]
users(searchString: String, where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]
me(id: ID): User
}
type Mutation {
createUser(name: String!): User
createPost(
title: String!
content: String!
published: Boolean!
userId: ID!
): Post
}
I copied the params over from prisma.graphql manually.

Query.products is defined in resolvers but not in schema

Hi I defined rootQuery in Customer schema and then in Product schema I extended query. I wrote resolvers for product schema but then I got following error: Error: Query.products defined in resolvers, but not in schema.
When I move product queries to customer query definition it works.
I dont understand why I'm getting this error. Do I need implement some rootQuery and insert it into typeDefs array and then extend queries in Customer and Product ?
Customer schema
import CustomerPhoto from "./customerPhoto";
const Customer = `
type Customer {
customerID: ID!
firstname: String
lastname: String
phone: String
email: String
CustomerPhoto: CustomerPhoto
}
input CustomerInput {
firstname: String!
lastname: String!
phone: String!
email: String!
}
type Query {
customers(cursor: Int!):[Customer]
customer(id: Int!): Customer
}
type Mutation {
createCustomer(photo: String!, input: CustomerInput): Customer
updateCustomer(customerID: ID!, photo: String, input: CustomerInput): Customer
deleteCustomer(customerID: ID!): Customer
}
`;
export default [Customer, CustomerPhoto];
Product Schema
import ProductPhoto from "./productPhoto";
const Product = `
type Product {
productID: ID!
name: String!
description: String!
pricewithoutdph: Float!
pricewithdph: Float!
barcode: Int!
ProductPhoto: ProductPhoto
}
extend type Query {
products: [Product]
product(productID: ID!): Product
}
`;
export default [Product, ProductPhoto]
Here Im importing both schemas. Is there something missing ?
const schema = makeExecutableSchema({
typeDefs: [...Customer,...Product],
resolvers: merge(CustomerResolvers, ProductResolvers),
logger: {
log: e => {
console.log("schemaError", e);
}
},
resolverValidationOptions: {
requireResolversForNonScalar: true
}
});
Product Resolvers
const ProductResolvers = {
Query: {
products: (_, { cursor }) => {
return models.Product.findAndCountAll({
include: {
model: models.ProductPhoto,
attributes: ["productPhotoID", "photo"],
required: true
},
offset: cursor,
limit: 10,
attributes: ["productID", "name", "description", "pricewithoutdph", "pricewithdph", "barcode"]
}).then(response => {
return response.rows;
});
}
};
export default ProductResolvers;
Customer Resolvers
const CustomerResolvers = {
Query: {
customers: (_, {cursor}) => {
return models.Customer.findAndCountAll({
include: {
model: models.CustomerPhoto,
attributes: ["customerPhotoID", "photo"],
required: true
},
offset: cursor,
limit: 10,
attributes: ["customerID", "firstname", "lastname", "phone", "email"]
}).then(response => {
return response.rows;
});
}
......
}
};

ApolloClient: Refactor updateQueries to work with this.props.client.mutate

Note: As the process for handling mutation/query/cache updates is now addressed by update, I am no longer using uodateQueries, making this question no longer relevant.
So, I have a one to many relationship from Posts to Comments:
type Comments {
createdAt: DateTime!
id: ID!
posts: Posts #relation(name: "PostsOnComments")
text: String!
updatedAt: DateTime!
user: String!
}
type Posts {
caption: String!
comments: [Comments!]! #relation(name: "PostsOnComments")
createdAt: DateTime!
displaysrc: String!
id: ID!
likes: Int
updatedAt: DateTime!
}
and a Root_Query, as depicted in Apollo devTools (See attached image), of:
query allPostsCommentsQuery {
allPostses {
id
displaysrc
caption
likes
comments {
id
posts {
id
}
text
user
}
}
}
Running Add_Comment_Mutation or Remove_Comment_MutationNew:
export const Add_Comment_Mutation = gql`
mutation createComment ($id: ID, $textVal: String!, $userVal: String!) {
createComments (postsId: $id, text: $textVal, user: $userVal){
id
text
user
}
}
`;
export const Remove_Comment_MutationNew = gql`
mutation removeComment ($cid: ID!) {
deleteComments(id: $cid) {
id
}
}
`;
does not correctly update reactive cache, and thus my UI does not correctly reflect any additions/deletions of comments, which are triggered by onClick events.
How do I get updateQueries to correctly work with this.props.client.mutate, as current attempt generates "Error: update(): expected target of $unshift to be an array; got undefined." errors (See below):
import { graphql, gql, withApollo } from 'react-apollo';
import ApolloClient from 'apollo-client';
import update from 'immutability-helper';
import { Add_Comment_Mutation, Remove_Comment_MutationNew } from '../graphql/mutations';
const Comments = React.createClass({
removeCommentMutation(commentID) {
console.log ("Remove_Comment_MutationNew is called for id=" + commentID);
const { client } = this.props;
return this.props.client.mutate({
mutation: Remove_Comment_MutationNew,
variables: {
"cid": commentID,
},
updateQueries: {
allPostsCommentsQuery: (previous, { mutationResult }) => {
console.log("Previous = " + previous);
const newComment = mutationResult.data.removeComment;
return update(previous, {
allPostses: {
comments: {
$set: [newComment],
},
},
});
}
}
})
.then(({ data }) => {
console.log('got data', data.deleteComments.id);
})
.catch(this.handleSubmitError);
},
Generated error:
Note - The issue appears to be with
const newComment = mutationResult.data.removeComment;
which is being returned as 'undefined', instead of as an object.
Error: update(): expected target of $unshift to be an array; got undefined.
at invariant (http://localhost:7770/static/bundle.js:23315:16)
at invariantPushAndUnshift (http://localhost:7770/static/bundle.js:71469:4)
at Object.$unshift (http://localhost:7770/static/bundle.js:71430:6)
at update (http://localhost:7770/static/bundle.js:71408:36)
at update (http://localhost:7770/static/bundle.js:71410:32)
at update (http://localhost:7770/static/bundle.js:71410:32)
at allPostsCommentsQuery (http://localhost:7770/static/bundle.js:54181:52)
at http://localhost:7770/static/bundle.js:39552:87
at tryFunctionOrLogError (http://localhost:7770/static/bundle.js:39457:17)
at http://localhost:7770/static/bundle.js:39552:44
at Array.forEach (native)
at data (http://localhost:7770/static/bundle.js:39536:47)
at apolloReducer (http://localhost:7770/static/bundle.js:39789:24)
at combination (http://localhost:7770/static/bundle.js:23011:30)
at computeNextEntry (<anonymous>:2:27051)
at recomputeStates (<anonymous>:2:27351)
at <anonymous>:2:30904
at Object.dispatch (http://localhost:7770/static/bundle.js:22434:23)
at dispatch (<anonymous>:2:31397)
at http://localhost:7770/static/bundle.js:41210:40
at http://localhost:7770/static/bundle.js:73223:17
at Object.dispatch (http://localhost:7770/static/bundle.js:23158:19)
at http://localhost:7770/static/bundle.js:40597:30
tryFunctionOrLogError # apollo.umd.js:1410
(anonymous) # apollo.umd.js:1501
data # apollo.umd.js:1485
apolloReducer # apollo.umd.js:1738
combination # combineReducers.js:132
computeNextEntry # VM77918:2
recomputeStates # VM77918:2
(anonymous) # VM77918:2
dispatch # createStore.js:179
dispatch # VM77918:2
(anonymous) # apollo.umd.js:3159
(anonymous) # index.js:14
dispatch # applyMiddleware.js:45
(anonymous) # apollo.umd.js:2546
I don't think you can concatenate mutations. At least the error message tells so. It should be something like:
...
removeCommentMutation(commentID) {
const { client } = this.props;
client.mutate({
mutatation: Remove_Comment_Mutation,
variables: {
"cid": commentID
},
updateQueries: {
removeComment: (previous, { mutationResult }) => {
const newComment = mutationResult.data.submitComment;
return update(prev, {
allPostses: {
comments: {
$unshift: [newComment],
},
},
});
}
}
});
}
...

Resources