Uncaught (in promise) Invariant Violation: Schema type definitions not allowed in queries. Found: "InputObjectTypeDefinition" - graphql

I'm not able to insert values ​​of an object in Mutation, I've tried everything, with input, with type, looking at the documentation, but nothing works..
MY CODE
const ADD_CARD = gql`
input ComissionPrice {
value: Float!
percent: Float!
}
mutation Create(
$assetName: String!
$structureName: String!
$highlightThesisText: String
$maturityAt: String!
$commissionPrice: ComissionPrice!
$objective: String!
$maxProfit: Float!
$maxLoss: Float!
$rebate: Float
) {
createSuggestedOperation(
command: {
assetName: $assetName
structureName: $structureName
highlightThesisText: $highlightThesisText
maturityAt: $maturityAt
commissionPrice: $commissionPrice
objective: $objective
maxProfit: $maxProfit
maxLoss: $maxLoss
rebate: $rebate
}
) {
errorMessages
}
}
`;
const onSubmit = useCallback((formData: any) => {
console.log(formData);
const VARIABLES_PARAMETERS_OBJECT = {
variables: {
assetName: formData.asset.value.name,
structureName: formData.structure.value.name,
maturityAt: formData.maturityAt.value,
comissionPrice: {
percent: parseFloat(formData.commissionToDividePercentage.value),
value: parseFloat(formData.commissionToDivideMonetary.value),
},
objective: formData.objective.value,
maxProfit: parseFloat(formData.maxProfit.value),
maxLoss: parseFloat(formData.maxLoss.value),
strike: 1,
barrier: 2,
},
};
const VARIABLES_PARAMETERS = Object.assign(VARIABLES_PARAMETERS_OBJECT);
if (formData.highlightThesisText?.value) VARIABLES_PARAMETERS.variables.highlightThesisText = formData.highlightThesisText.value;
if (formData.rebate?.value) VARIABLES_PARAMETERS.variables.rebate = formData.rebate.value;
addCard(VARIABLES_PARAMETERS);
}, []);

Related

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

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!

Cast to ObjectId failed for value \"{ proposser: '618e49a68e18cd48286de4b5' }\" (type Object) at path \"_id\" for model \"Proposal\"

I am getting this error in graphql playground (image below ) .
I have checked for the validity of objectId in the resolver as well.
// model
const ProposalSchema = new Schema({
cover
Letter: {
type: String,
},
budget: {
type: String,
},
proposals: {
type: mongoose.Schema.Types.ObjectId,
},
_id: {
type: mongoose.Schema.Types.ObjectId,
},
});
//resolver
also checked If the argument is valid using mongoose.isValidObjectId(proposser) it returns true
Query: {
proposals(_, args) {
const { proposser } = args;
return Proposal.findById({
proposser,
});
},
},
// schema
const typeDefs = gql`
type Proposal {
_id: ID!
coverLetter: String
budget: String
proposser: ID!
}
`;
const Proposal = mongoose.model("Proposal", ProposalSchema);
I was using wrong method in resolvers .
findById was being used for field non Id field.
async proposals(_, args) {
const { proposser } = args;
const userProposals = await Proposal.find({
proposser,
});
try {
const result = userProposals;
return result ? result : [];
} catch (err) {
console.log(err);
}
},

Relationships with AwsCdk, DynamoDB and AppSync - Typescript and lambda functions

we are currently studying the stack: cdk, appsync and amplify to migrate our applications.
In our initial tests, we were able to upload a graphql api with only appsync wit relationships and it was very smooth, nice and fast.
When testing to build with cdk, we are having difficulties to create the relationships.
Here my code:
Schema
type Person {
id: ID!
name: String!
}
input PersonInput {
id: ID!
name: String!
}
input UpdatePersonInput {
id: ID!
name: String
}
type Client {
id: ID!
type: String!
personId: String
# Person: PersonConnection
Person: Person #connection(fields: ["personId"])
}
input ClientInput {
id: ID!
type: String!
personId: String!
}
input UpdateClientInput {
id: ID!
type: String
personId: String
}
My function
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
async function list() {
const params = {
TableName: process.env.CLIENT_TABLE,
}
try {
const data = await docClient.scan(params).promise()
return data.Items
} catch (err) {
console.log('DynamoDB error: ', err)
return null
}
}
export default list;
My table
const clientTable = new dynamodb.Table(scope, 'ClientTable', {
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
partitionKey: {
name: 'id',
type: dynamodb.AttributeType.STRING,
},
});
clientTable.addGlobalSecondaryIndex({
indexName: 'client-by-person-id',
partitionKey: {
name: 'personId',
type: dynamodb.AttributeType.STRING
},
sortKey: {
name: 'createdAt',
type: dynamodb.AttributeType.STRING
}
})
My query
query MyQuery {
listClients {
id
personId
type
Person {
name
}
}
}
However, my return to Person connection is null
"listClients": [
{
"id": "1",
"personId": "1",
"type": "PJ",
"Person": null
}
]
I would appreciate it if could point out our mistake
Solution of the problem based on the response of the Thorsten.
First, add resolver to the Person field in Client
export const clientResolvers = [{ typeName: "Client", fieldName: "Person" },...]
clientResolvers.map(((resolver: clientTypeResolver) => dataSource2.createResolver(resolver)))
Map function to the Person field in its lambda function
type AppSyncEvent = {
...
source: {personId: string,}
...
}
exports.handler = async (event:AppSyncEvent) => {
switch (event.info.fieldName) {
...
case "Person":
return await getPerson(event.source.personId);
}
}```
Function to solve the person field
async function getPerson(personId: string) {
console.log("CONTEXT\n" + JSON.stringify(personId, null, 2))
// console.log(context.source)
const params = {
TableName: process.env.PERSON_TABLE,
Key: { id: personId }
}
try {
const { Item } = await docClient.get(params).promise()
console.log("DATA\n" + JSON.stringify(Item, null, 2))
return Item
} catch (err) {
console.log('DynamoDB error: ', err)
}

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;
});
}
......
}
};

graphql mutation gives syntax error: Expected Name

I am trying to implement mutations with a variable. But I get the following error:
"Syntax Error GraphQL request (3:22) Expected Name, found $
2: mutation {
3: createProperty($property) {
^
4: id
"
My schema definitely doesn't say anything about a name, that's why I think this error is so strange.. I also don't think the documentations about graphql / apollo are very good.
Calling the mutation from client:
const property = {
title: 'First house',
cost: 849,
bedrooms: 3,
bathrooms: 2,
car_spaces: 1,
house_size: 60,
};
const createPropertyQuery =
graphql(gql`
mutation {
createProperty($property) {
id
}
}
`, {
options: {
variables: {
property,
},
},
});
const { data } = await apolloClient.query({
query: createPropertyQuery,
});
Schema:
type Property {
title: String!
cost: Float
user: User
bedrooms: Int!
bathrooms: Int!
car_spaces: Int!
house_size: Int!
}
input propertyInput {
title: String!
cost: Float
bedrooms: Int!
bathrooms: Int!
car_spaces: Int!
house_size: Int!
}
type RootMutation {
createProperty (
property: propertyInput
): Property
}
You should mention name of the parameter at first!
mutation CreatePropertyMutatuin($property: propertyInput){
createProperty(property: $property) {
id
}
}

Resources