"Variable '$data' expected value of type 'VoteCreateInput" - graphql

When I am trying to do the "vote" mutation, getting the below error. My other mutations are working fine.
When I am trying to do the "vote" mutation, getting the below error. My other mutations are working fine.
When I am trying to do the "vote" mutation, getting the below error. My other mutations are working fine.
"data": null,
"errors": [
{
"message": "Variable '$data' expected value of type 'VoteCreateInput!' but
got: {\"user\":{\"connect\":
{\"id\":\"ck1j3nzi68oef090830r8wd6b\"}},\"link\":{\"connect\":
{\"id\":\"ck1j58loj8x570908njwe4eu7\"}}}. Reason: 'User' Expected non-null
value, found null. (line 1, column 11):\nmutation ($data:
VoteCreateInput!) {\n ^",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"vote"
]
}
]
Mutation
async function vote(parent, args, context, info) {
// 1
const userId = getUserId(context)
// 2
const linkExists = await context.prisma.$exists.vote({
user: { id: userId },
link: { id: args.linkId },
})
if (linkExists) {
throw new Error(`Already voted for link: ${args.linkId}`)
}
// 3
return context.prisma.createVote({
user: { connect: { id: userId } },
link: { connect: { id: args.linkId } },
})
}
datamodel.schema
type Link {
id: ID! #id
createdAt: DateTime! #createdAt
description: String!
url: String!
postedBy: User
votes: [Vote!]!
}
type User {
id: ID! #id
name: String!
email: String #unique
password: String!
links: [Link!]!
votes: [Vote!]!
}
type Vote {
id: ID! #id
link: Link!
user: User!
}
schema.graphql
type Mutation {
vote(linkId: ID!): Vote!
}
type Link {
id: ID!
description: String!
url: String!
postedBy: User
votes: [Vote!]!
}

There was a glitch in prisma database which was not updating with the change in data model.
I have created a new instance of the db and now its working fine.

Related

Graphql React Dev Tools Missing field while writing result

I am running a graphql query to create a person object. The query works fine and the person is created. However I am receiving the following error in the console
react_devtools_backend.js:2842 Missing field 'create_person' while writing result {
"__typename": "PersonResponse",
"error": null,
"person": {
"__typename": "Person",
"hire_date": "2020-10-01",
"name": {
"__typename": "Name",
"first_name": "Joe",
"last_name": "Doe",
"middle_name": ""
},
"person_id": {
"__typename": "PersonId",
"id_": "44df8f7c-d019-410c-89b4-be602f631055"
},
"preferred_name": {
"__typename": "PreferredName",
"first_name": "J",
"last_name": "Dee",
"middle_name": null
}
},
"status": 201
}
This error seems to be saying that my query is missing a field create_person however create_person is not a field it is the name of the query. My first thought was that the message is due to the null fields (even though they are not required). I tried removing these fields from the schema and I still get the error. I am using React Dev Tools chrome extension but still not sure why I get this error.
As requested the gql schema:
const graphqlSchema = buildSchema(`
type Query {
people(person_id: String): [Person]!
emergency_contacts(
person_id: String!
emergency_contact_id: String
): [EmergencyContact]!
person_success: PersonResponse!
person_not_found: PersonResponse!
person_deleted: PersonResponse!
emergency_contact_success: EmergencyContactResponse!
}
scalar Datetime
type PersonId {
id_: String!
}
type Name {
first_name: String!
last_name: String!
middle_name: String
}
input NameInput {
first_name: String!
last_name: String!
middle_name: String
}
input UpdateNameInput {
first_name: String
last_name: String
middle_name: String
}
type ExemptStatus {
code: String!
description: String!
}
type PreferredName {
first_name: String
last_name: String
middle_name: String
}
input PreferredNameInput {
first_name: String
last_name: String
middle_name: String
}
type Relationship {
code: String!
display: String!
description: String!
}
type Address {
line_1: String!
line_2: String!
city: String!
state: String!
zip_code: String!
}
type Person {
person_id: PersonId!
name: Name!
hire_date: Datetime!
preferred_name: PreferredName
contact_info: ContactInfo
exempt_status: ExemptStatus
hired_hours_per_week: Float
hired_hours_per_two_weeks: Float
emergency_contacts: [EmergencyContact]
}
type PersonResponse {
status: Int
error: String
person: Person
}
input PersonInput {
name: NameInput!
hire_date: Datetime!
preferred_name: PreferredNameInput
contact_info: ContactInfoInput
exempt_status_code: String
hired_hours_per_week: Float
hired_hours_per_two_weeks: Float
}
input AddressInput {
line_1: String!
line_2: String!
city: String!
state: String!
zip_code: String!
}
type ContactInfo {
primary_phone: String!
alternate_phone: String
email: String
address: Address
}
input ContactInfoInput {
primary_phone: String!
alternate_phone: String
email: String
address: AddressInput
}
type EmergencyContactId {
id_: String!
}
type EmergencyContact {
emergency_contact_id: EmergencyContactId!
name: Name!
relationship: Relationship!
contact_info: ContactInfo!
}
input EmergencyContactInput {
name: NameInput!
relationship_code: String!
contact_info: ContactInfoInput!
}
input UpdateEmergencyContactInput {
name: NameInput
relationship_code: String
contact_info: ContactInfoInput
}
type EmergencyContactResponse {
status: Int
error: String
person_id: PersonId
emergency_contact: EmergencyContact
}
type Mutation {
create_person(person_input: PersonInput): PersonResponse
update_name(person_id: String!, name_input: UpdateNameInput!): PersonResponse
update_hire_date(person_id: String!, hire_date: Datetime!): PersonResponse
update_preferred_name(
person_id: String!
preferred_name_input: UpdateNameInput!
): PersonResponse
delete_person(person_id: String!): PersonResponse
}
`);

How to add item into an list field?

I want to add members to chatRoom member list by passing memberId to graphql mutation function. But it pop up some errors. I have attached most code that relevant to this question as below. Please help me to figure it out. I guess create: {connect } might be the cause of this issue.
//Here is Mutation function
async function addMemberToChatRoom(parent, args, context, info) {
const member = await context.prisma.users({
where: {
id: args.memberId
}
});
const chatRoom = await context.prisma.updateChatRoom({
where: {
id: args.roomId
},
data: {
users: {
create: {
{ connect: { id: args.memberId } }
}
}
}
})
return chatRoom
}
//Here is prisma datamodel
type User {
id: ID! #id
name: String!
email: String! #unique
password: String!
}
type ChatRoom {
id: ID! #id
name: String!
users: [User]!
}
type Message {
id: ID! #id
content: String!
createdAt: DateTime! #createdAt
updatedAt: DateTime! #updatedAt
}
//Here is Schema.graphql
type Query {
info: String!
users: [User!]!
}
type Mutation {
signup(email: String!, password: String!, name: String!): AuthPayload
login(email: String!, password: String!): AuthPayload
createChatRoom(name: String!): ChatRoom
addMemberToChatRoom(roomId: String!, memberId: String!): ChatRoom
}
type AuthPayload {
token: String!
user: User!
}
type User {
id: ID!
name: String!
email: String!
}
type ChatRoom {
id: ID!
name: String!
users: [User!]
}
//Here is index.js
const { GraphQLServer } = require('graphql-yoga')
const { prisma } = require('./generated/prisma-client')
const Query = require('./resolvers/Query')
const Mutation = require('./resolvers/Mutation')
// const User = require('./resolvers/User')
const resolvers = {
Query,
Mutation
}
const server = new GraphQLServer({
typeDefs: './src/schema.graphql',
resolvers,
context: request => {
return {
...request,
prisma,
}
},
tracing: true,
})
server.start(() => console.log(`Server is running on http://localhost:4000`))
//Here is error
{
"data": {
"addMemberToChatRoom": null
},
"errors": [
{
"message": "Variable '$data' expected value of type 'ChatRoomUpdateInput!' but got: {\"users\":{\"create\":{\"id\":\"cjuzcf7lx75g60b953w50uwdc\"}}}. Reason: 'users.create[0].name' Expected non-null value, found null. (line 1, column 46):\nmutation ($where: ChatRoomWhereUniqueInput!, $data: ChatRoomUpdateInput!) {\n ^",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"addMemberToChatRoom"
]
}
]
}
I remove create and change it to
users:
{
connect: { id: args.memberId }
}
then it works.
async function addMemberToChatRoom(parent, args, context, info) {
const member = await context.prisma.users({
where: {
id: args.memberId
}
});
const chatRoom = await context.prisma.updateChatRoom({
where: {
id: args.roomId
},
data: {
users: {
connect: { id: args.memberId }
}
}
})
const returnedChatRoom = await context.prisma.chatRooms({
where: {
id: args.roomId
}
});
return returnedChatRoom
}

Prisma graphql computed fields on relations

I have the following datamodel:
type Tvshow {
id: ID! #unique
title: String!
pricing: [Pricing]
startDate: DateTime!
endDate: DateTime!
subscribers: [Tvshowsubscription!]
.....
}
type FavoriteTvshow {
id: ID! #unique
tvshow: Tvshow!
user: User!
}
type User {
id: ID! #unique
name: String
email: String! #unique
password: String
googleID: String #unique
resetToken: String
resetTokenExpiry: String
permissions: [Permission]
address: Address
phone: String
favorites: [FavoriteTvshow!]
tvshowSubscriptions: [Tvshowsubscription!]
}
I have my custom Tvshow resolver using addFragmentToInfo:
resolver-queries.js
const Query = {
...
favoriteTvshows: forwardTo('db'),
tvshow: (parent, args, ctx, info) => {
const fragment = `fragment EnsureComputedFields on Tvshow { pricing { minQuantity maxQuantity unitPrice} subscribers { id }}`
return ctx.db.query.tvshow({}, addFragmentToInfo(info, fragment))
},
....
};
tvshow-resolver.js
const Tvshow = {
countSubscribers: (parent) => {
return parent.subscribers.length;
},
}
This is an example, I have more computed fields for Tvshow
I can query Tvshows with countSubscribers, It works fine doing something like this:
query SINGLE_TVSHOW_QUERY($id: ID!) {
tvshow(where: { id: $id }) {
id
title
pricing {
minQuantity
maxQuantity
unitPrice
}
startDate
endDate
countSubscribers
}
}
But what I want to do is to get all the favorite Tvshows from an user returning the countSubscribers, a query for that could be something like this:
query FAVORITES_FROM_USER($userId: ID!) {
favoriteTvshows(where: { user: {id: $userId} }) {
tvshow {
id
title
startDate
endDate
countSubscribers
}
}
}
The problem is that when I query this, in the tvshow-resolver.js I mentioned before, the parent doesn’t have any subscribers object
The error was very silly but I will post it anyway. I needed subscribers in the query
query FAVORITES_FROM_USER($userId: ID!) {
favoriteTvshows(where: { user: {id: $userId} }) {
tvshow {
id
title
startDate
endDate
subscribers { <---
id
quantity
}
countSubscribers
}
}
}
That way the parent in tvshow-resolver.js will have subscribers object

Querying NOT NULL GraphQL with Prisma

Schema:
type TrackUser {
id: ID! #unique
createdAt: DateTime!
user: User #note there is no `!`
}
type User {
id: ID! #unique
name: String! #unique
}
I want to get Alls TrackUser where User is not null. What would be the query?
This would be a possible query:
query c {
trackUsers(where: { NOT: [{ user: null }] }) {
name
}
}
Here you can see how it looks in the Playground. I added a name to Trackuser in the datamodel in order to be able to create it from that side without a user.
this works, but I guess it is just a hack..
query TrackUsersQuery($orderBy: TrackUserOrderByInput!, $where: TrackUserWhereInput, $first: Int, $skip: Int) {
trackUsers(where: $where, orderBy: $orderBy, first: $first, skip: $skip) {
id
createdAt
user {
id
name
}
}
}
variables = {
where: {
user: {
name_contains: ''
}
}
}
UPDATE:
For Prisma2, here you have the possibilities:
For products that have no invoice, you can use the following:
const data = await prisma.product.findMany({
where: {
invoices: {
none: {
id: undefined,
},
},
},
})
And for Invoices that do not have a product associated:
const data = await prisma.invoice.findMany({
where: {
productId: null,
},
})
more details here: https://github.com/prisma/prisma/discussions/3461

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

Resources