GraphQL mutation in KeystoneJS: "Cannot use 'in' operator to search for 'id' in undefined" - graphql

In a KeystoneJS GraphQL project I'm trying to create a new data object (an "Article") in the 'resolveInput' hook of another, existing, data object (a "Proposal" -- when a Proposal is approved, I create an Article based on that Proposals'data).
This worked fine using the Mongoose adapter, but I've tried to do it using the built in GraphQL API, using keystone.executeQuery and I get the following error:
My Article list has a relationship with one Proposal (I'm leaving out the other fields)
fields: {
proposal: {
isUnique: false,
type: fields_1.Relationship,
ref: 'Proposal',
access: {
create: true,
read: true,
update: false
}
}
}
and I create the new Article thus (I'm omitting some code)
hooks: {
resolvedInput: async params => {
const articleCreateInput = {
title: cleanTitle,
text: cleanText,
visible: HIDDEN,
proposal: {
connect: {
id: proposalId
}
}
};
const articleCreationResult = await keystone.executeQuery(createArticle, { variables: articleCreateInput });
}
}
As far as I can see this is the correct way to do it, using connect, connecting an existing item to one you are creating.
My query is
const createArticle = `mutation createArticle($data:ArticleCreateInput) {
createArticle(data:$data) {
id
title
visible
publishDate
}
} `;
and as far as I can see I'm following the schema correctly
I'm sure I'm making an obvious mistake but at the moment I don't see it -- and I'm not sure whether that mistake is a GraphQL mistake or a KeystoneJS mistake (or both).

Related

Getting an error when having heuristic fragment matching with Apollo & Nuxt.js

I am trying to connect the below graphql query with nuxtjs.
query getContent($slug: String!) {
contents (filters: { slug: { eq: $slug } }) {
data {
id
attributes {
title
content {
__typename
... on ComponentContentParagraph {
content
}
}
}
}
}
}
I am getting the following error and not getting the result from the query.
You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types. Apollo Client will not be able to accurately map fragments. To make this error go away, use the `IntrospectionFragmentMatcher` as described in the docs: https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher
I have checked the questions and answers available here.
Apollo+GraphQL - Heuristic Fragment Manual Matching
I have followed the docs from apollo as well.
https://www.apollographql.com/docs/react/data/fragments/#fragment-matcher
I managed to generate possibleTypes as mentioned in the docs.
Here is my next config.
apollo: {
includeNodeModules: true,
clientConfigs: {
default: "~/graphql/default.js",
},
},
This is the default.js
import { InMemoryCache } from "apollo-cache-inmemory";
import possibleTypes from "./possibleTypes.json";
export default () => {
return {
httpEndpoint: process.env.BACKEND_URL || "http://localhost:1337/graphql",
cache: new InMemoryCache({ possibleTypes }),
};
};
I am using strapi for the backend and this query works fine when running from graphql interface.

Prisma Not Returning Created Related Records

i want to create a new graphql api and i have an issue that i am struggling to fix.
the code is open source and can be found at: https://github.com/glitr-io/glitr-api
i want to create a mutation to create a record with relations... it seems the record is created correctly with all the expected relations, (when checking directly into the database), but the value returned by the create<YourTableName> method, is missing all the relations.
... so so i get an error on the api because "Cannot return null for non-nullable field Meme.author.". i am unable to figure out what could be wrong in my code.
the resolver looks like the following:
...
const newMeme = await ctx.prisma.createMeme({
author: {
connect: { id: userId },
},
memeItems: {
create: memeItems.map(({
type,
meta,
value,
style,
tags = []
}) => ({
type,
meta,
value,
style,
tags: {
create: tags.map(({ name = '' }) => (
{
name
}
))
}
}))
},
tags: {
create: tags.map(({ name = '' }) => (
{
name
}
))
}
});
console.log('newMeme', newMeme);
...
that value of newMeme in the console.log here (which what is returned in this resolver) is:
newMeme {
id: 'ck351j0f9pqa90919f52fx67w',
createdAt: '2019-11-18T23:08:46.437Z',
updatedAt: '2019-11-18T23:08:46.437Z',
}
where those fields returned are the auto-generated fields. so i get an error for a following mutation because i tried to get the author:
mutation{
meme(
memeItems: [{
type: TEXT
meta: "test1-meta"
value: "test1-value"
style: "test1-style"
}, {
type: TEXT
meta: "test2-meta"
value: "test2-value"
style: "test2-style"
}]
) {
id,
author {
displayName
}
}
}
can anyone see what issue could be causing this?
(as previously mentioned... the record is created successfully with all relationships as expected when checking directly into the database).
As described in the prisma docs the promise of the Prisma client functions to write data, e.g for the createMeme function, only returns the scalar fields of the object:
When creating new records in the database, the create-method takes one input object which wraps all the scalar fields of the record to be
created. It also provides a way to create relational data for the
model, this can be supplied using nested object writes.
Each method call returns a Promise for an object that contains all the
scalar fields of the model that was just created.
See: https://www.prisma.io/docs/prisma-client/basic-data-access/writing-data-JAVASCRIPT-rsc6/#creating-records
To also return the relations of the object you need to read the object again using an info fragment or the fluent api, see: https://www.prisma.io/docs/prisma-client/basic-data-access/reading-data-JAVASCRIPT-rsc2/#relations

How get rid of redundant wrapper object of a mutation result?

When I'm making a request to my backend through a mutation like that:
mutation{
resetPasswordByToken(token:"my-token"){
id
}
}
I'm getting a response in such format:
{
"data": {
"resetPasswordByToken": {
"id": 3
}
}
}
And that wrapper object named the same as the mutation seems somewhat awkward (and at least redundant) to me. Is there a way to get rid of that wrapper to make the returning result a bit cleaner?
This is how I define the mutation now:
export const ResetPasswordByTokenMutation = {
type: UserType,
description: 'Sets a new password and sends an informing email with the password generated',
args: {
token: { type: new GraphQLNonNull(GraphQLString) },
captcha: { type: GraphQLString },
},
resolve: async (root, args, request) => {
const ip = getRequestIp(request);
const user = await Auth.resetPasswordByToken(ip, args);
return user.toJSON();
}
};
In a word: No.
resetPasswordByToken is not a "wrapper object", but simply a field you've defined in your schema that resolves to an object (in this case, a UserType). While it's common to request just one field on your mutation type at a time, it's possible to request any number of fields:
mutation {
resetPasswordByToken(token:"my-token"){
id
}
someOtherMutation {
# some fields here
}
andYetAnotherMutation {
# some other fields here
}
}
If we were to flatten the structure of the response like you suggest, we would not be able to distinguish between the data returned by one mutation from another. We likewise need to nest all of this inside data to keep our actual data separate from any returned errors (which appear in a separate errors entry).

Can't find cache key in Cache redirect

When I start my react-native app I wan't to query "everything" for an offline experience.
So I
query all {
groups {
...GroupF
}
persons {
...PersonF
}
}${PERSON_ITEM}${GROUP_ITEM}
PersonF and GroupF are fragments.
The first view has a list of groups, each person can belong to a group. When the user clicks on an group the query looks like:
persons($group: ID) {
persons(group: $group) {
...PersonsF
}
}${PERSON_ITEM}
But my cacheRedirects just does not reflect the same data as is returned.
I know this because i console.log out the response in my component wrapper (it looks excellent here)
but in my
const cache = new InMemoryCache({
cacheRedirects: {
Query: {
persons: (_, args, {getCacheKeys}) => {
// I have tried everything here but nothing maps correctly
// I have tried getCacheKey({__typename: 'Person', id: args.group})
// I have tried following the apollo documentation
// No luck, it just can't find the group
// Using the chrome dev tools I don't see persons having groups
const a = getCacheKey({__typename: 'Person', id: args.group});
// Console.log(a) is:
// {generated: false, id: "Person:9", type: "id", typename "Person"}
}
}
}
});
Do you have any suggestions on how I can write a proper cache redirects persons query?
Help really really really appreciated
|1| https://www.apollographql.com/docs/react/advanced/caching.html#cacheRedirect
This was caused by the fact we used the id field in the Person, since we stoped using the field it works perfectly.

Relay how to write outputFields, getFatQuery, getConfigs for create new Item

How to write outputFields, getFatQuery, getConfigs for create new item and update items list
Please take a look gist or live
Questions are
getFatQuery() {
return Relay.QL`
???
`;
}
getConfigs() {
return [???];
}
outputFields: {
???
},
The outputFields in your schema make up the GraphQL type CreateActivityPayload that will be generated from your schema.js file. A mutation is like a regular query, but with side effects. In outputFields you get to decide what's queryable. Since your store is the only thing in your app that can change as a result of this mutation, we can start with that.
outputFields: {
store: {
type: storeType,
resolve: () => store,
},
}
The fat query operates on these output fields. Here you tell Relay what could possibly change as a result of this mutation. Adding an activity could change the following fields:
getFatQuery() {
return Relay.QL`
fragment on CreateActivityPayload #relay(pattern: true) {
store {
activities
}
}
`;
}
Finally, the config tells Relay what to do with the query when it gets it, or even if it needs to be made at all. Here, you're looking to update a field after creating a new activity. Use the FIELDS_CHANGE config to tell Relay to update your store.
getConfigs() {
return [{
type: 'FIELDS_CHANGE',
fieldsIDs: {
store: this.props.storeId,
},
}];
}
See more: https://facebook.github.io/relay/docs/guides-mutations.html

Resources