How to remove the `__typename` field from the graphql response which fails the mutations - node.js

I tried changing the addTypeName: false in the Apollo client in GraphQL
apollo.create({
link: httpLinkWithErrorHandling,
cache: new InMemoryCache({ addTypename: false }),
defaultOptions: {
watchQuery: {
fetchPolicy: 'network-only',
errorPolicy: 'all'
}
}
But it works and it throws the following messages in the console
fragmentMatcher.js:26 You're using fragments in your queries, but either don't have the addTypename:true option set in Apollo Client, or you are trying to write a fragment to the store without the __typename.Please turn on the addTypename option and include __typename when writing fragments so that Apollo Clientcan accurately match fragments.
,
Could not find __typename on Fragment PopulatedOutageType
and
fragmentMatcher.js:28 DEPRECATION WARNING: using fragments without __typename is unsupported behavior and will be removed in future versions of Apollo client. You should fix this and set addTypename to true now.
even if i change false to true new InMemoryCache({ addTypename: true }), the mutations start failing because of the unwanted typename in the mutation
is there any way to resolve this issue

Cleaning Unwanted Fields From GraphQL Responses
In the above thread, I have posted the answer for this problem please refer to it

Related

Ambiguos "Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type" error in nexus graphql

I'm getting the following error when using nexus to define a graphql schema with apollo-server.
Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type
The stacktrace doesn't give much information as to where the issue is occurring or to what the problem is. The project has 20+ models and dozens of resolvers so it's quite hard to debug.
Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type, check the docs for extending types
at extendError (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1744:2)
at SchemaBuilder.addType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:603:8)
at SchemaBuilder.missingType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1212:5)
at SchemaBuilder.getOrBuildType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1540:4)
at SchemaBuilder.getOutputType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1471:10)
at SchemaBuilder.buildOutputField (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1349:52)
at /Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1307:7
at Array.forEach (<anonymous>)
at SchemaBuilder.buildOutputFields (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1306:7)
at fields (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1009:33)
Any help appreciated.
I got the same error, but it was because I removed some exports. I'm not exactly sure what caused it, but I basically have a file that exports all of my graphql modules. E.g.
// graphql/modules/index.ts
export * from './file-a';
export * from './file-b';
When I removed the second export line, I started getting the error. I'm probably using some of the types defined in file-b somewhere else, and that's somehow causing the error. Anyway, adding the line back in fixed it (I had removed it by accident anyway).
UPDATE
I also go this by referencing some arg types that didn't exist (typo). For example:
args: {
where: arg({ type: 'ConversationsWhereInput' }),
orderBy: arg({ type: 'ConversationsOrderByInput', list: true }),
},
The s in Conversations shouldn't be there. It should be:
args: {
where: arg({ type: 'ConversationWhereInput' }),
orderBy: arg({ type: 'ConversationOrderByInput', list: true }),
},
It could have been much helpful if you could elaborate what did you do before this error happened.
I just came up with this error exactly as same as what you got and for me it was because I just accidentally changed the name for objectType of typeDef.
For instance, the name for the FollowUserResult was actually FollowResult and after I changed the name, the whole mutation resolvers related to this objectType became wrong.
export const FollowUserResult = objectType({
name: "FollowUserResult", // It was originally "FollowResult"
definition(t) {
t.nonNull.boolean("ok");
t.string("error");
},
});
You may check on this again. Once you got those correct, delete the schema.graphql file and generate the new schema.graphql file.
I got this error because I was using the incorrect Node version. My project didn't have a .nvrmc file (yet) so I was using Node 10 on a project that uses Node 14. So after switching to the correct Node version this error went away
I got this error when I incorrectly specified an unknown type in the type attribute of an extension to the Query type. More specifically:
export const CoursesQuery = extendType({
type: "Query",
definition(t) {
t.field("myQuery", {
type: InvalidType, // <--- Changing InvalidType to the correct type fixed the error
async resolve(_parent, _args, ctx) {
return ...
},
});
},
});
The error disappeared after I changed InvalidType to the correct type and restarted the server.

How to build a Graqhql mutation with existing variables

This might seem like an odd question, or something really straightforward, but honestly I am struggling to figure out how to do this. I am working in Node.js and I want to set data I have saved on a node object into my GraphQL mutation.
I'm working with a vendor's GraqhQL API, so this isn't something I have created myself, nor do I have a schema file for it. I'm building a mutation that will insert a record into their application, and I can write out everything manually and use a tool like Postman to manually create a new record...the structure of the mutation is not my problem.
What I'm struggling to figure out is how to build the mutation with variables from my node object without just catting a bunch of strings together.
For example, this is what I'm trying to avoid:
class MyClass {
constructor() {
this.username = "my_username"
this.title = "Some Title"
}
}
const obj = new MyClass()
let query = "mutation {
createEntry( input: {
author: { username: \"" + obj.username + "\" }
title: \"" + obj.title + "\"
})
}"
I've noticed that there are a number of different node packages out there for working with Graphql, but none of their documentation that I've seen really addresses the above situation. I've been completely unsuccessful in my Googling attempts, can someone please point me in the right direction? Is there a package out there that's useful for just building queries without requiring a schema or trying to send them at the same time?
GraphQL services typically implement this spec when using HTTP as a transport. That means you can construct a POST request with four parameters:
query - A Document containing GraphQL Operations and Fragments to execute.
operationName - (Optional): The name of the Operation in the Document to execute.
variables - (Optional): Values for any Variables defined by the Operation.
extensions - (Optional): This entry is reserved for implementors to extend the protocol however they see fit.
You can use a Node-friendly version of fetch like cross-fetch, axios, request or any other library of your choice to make the actual HTTP request.
If you have dynamic values you want to substitute inside the query, you should utilize variables to do so. Variables are defined as part of your operation definition at the top of the document:
const query = `
mutation ($input: SomeInputObjectType!) {
createEntry(input: $input) {
# whatever other fields assuming the createEntry
# returns an object and not a scalar
}
}
`
Note that the type you use will depend on the type specified by the input argument -- replace SomeInputObjectType with the appropriate type name. If the vendor did not provide adequate documentation for their service, you should at least have access to a GraphiQL or GraphQL Playground instance where you can look up the argument's type. Otherwise, you can use any generic GraphQL client like Altair and view the schema that way.
Once you've constructed your query, make the request like this:
const variables = {
input: {
title: obj.title,
...
}
}
const response = await fetch(YOUR_GRAPHQL_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
})
const { data, errors } = await response.json()

Watson Conversation API says: 'Patterns are defined but type is not specified.'

I am trying to call the updateValue method of the Watson Conversation API using the Watson SDK for Node.js. The request updates the patterns of the patterns-type entity value.
My request fails with a 400 Bad Request and the message:
[ { message: 'Patterns are defined but type is not specified.',
path: '.patterns' } ],
Here is the code I'm using to call the API - pretty standard.:
let params = {
workspace_id: '<redacted>',
entity: 'myEntityType',
type: 'patterns', // tried with and without this line
value: 'myCanonicalValue',
new_patterns: ['test'],
};
watsonApi.updateValue(params, (error, response) => {
if (error) {
console.log('Error returned by Watson when updating an entity value.');
reject(error);
} else {
resolve(response);
}
});
Actually, what the request is doing is trying to delete a pattern from the pattern list. Since there is no endpoint for deleting patterns, I fetch the list of patterns, delete the one I need to delete from the pattern list, and send the now-reduced patterns list via the updateValue method. In the above example, imagine the pattern list was ['test', 'test2']. By calling updateValue with ['test'] only, we are deleting the test2 pattern.
I am using a previous API version but I've also tested it in the Assistant API Explorer and the version 2018-07-10 results in the same problem when sending a raw request body formed as follows:
{
"patterns": ["test"]
}
Am I doing something wrong or did I forget a parameter?
It's not a bug, but it is a non-intuitive parameter name. The service accepts a type parameter and the Node SDK has a wrapper parameter called new_type. If you are using this to update patterns and not synonyms (the default), then you need to specify new_type as "patterns" even though the parameter is listed as optional.
This appears to be a bug in Watson Conversation Node.js SDK.
To avoid this, always add new_type: 'patterns' to the params:
let params = {
workspace_id: '<redacted>',
entity: 'myEntityType',
new_type: 'patterns',
value: 'myCanonicalValue',
new_patterns: ['test'],
};
I read the Watson Assistant API for updateValue the following way:
The new_type parameter is not required, valid values are synonyms or patterns. However, if you don't provide that parameter, the default kicks in. According to the documentation the default is synonyms. This would explain the error when you pass in patterns.

How to make 'testPattern' mandatory while updating snapshots in Jest?

Snapshot testing comes handy for testing UI components. If your UI component changes, you are expected to update the snapshot as well to reflect the same. We can specify 'testNamePattern' to update snapshots for a specific test.
jest --updateSnapshot --testNamePattern abc.test.js
Is it possible to mandate 'testNamePattern' while updating snapshots? This will help avoid updating other failing snapshots by mistake. I understand that it is expected to be caught in code review phase. However, I want to ensure that snapshots are always updated for a specific pattern.
As of now, there isn't any CLI option for doing this per doc. I have added a small snippet to my testFrameworkScriptFile to ensure that testNamePattern is passed while updating snapshots.
import yargs from 'yargs';
const mandateTestNamePattern = () => {
const args = yargs.option('testNamePattern', {
type: 'string'
}).option('t', {
type: 'string'
}).argv;
if (args.updateSnapshot || args.u) {
if (args.testNamePattern || args.t) {
// valid case
} else {
throw new Error('TestNamePattern is mandatory while updating snapshots');
}
}
};
mandateTestNamePattern();

rally-node Add new item to collection

Using the rally-node toolkit, I'm getting an error message returned when attempting to add new Changeset, with new Changes inline, to an existing Userstory. When I have the new Changes commented out there's the Changeset is added as expected. It seems to be something specifically with the Change data that I can't figure out.
Add call:
rallyApi.add({
"ref":"https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement/91834286580",
"collection":"Changesets",
"data":[
{
"Author":{
"_ref":"https://rally1.rallydev.com/slm/webservice/v2.0/user/53634054872"
},
"CommitTimestamp":"2017-03-17T09:52:07-04:00",
"Message":"Feature/tags (#11)",
"Revision":"b8460460254cb79d3e72c98172c164f5c4d3493a",
"Uri":"https://ghe/org/repo/commit/b8460460254cb79d3e72c98172c164f5c4d3493a",
"Changes":[
{
"Action":"M",
"PathAndFilename":"file1.json",
"Uri":"https://ghe/org/repo/commit/b8460460254cb79d3e72c98172c164f5c4d3493a/file1.json"
},
{
"Action":"M",
"PathAndFilename":"file2.json",
"Uri":"https://ghe/org/repo/commit/b8460460254cb79d3e72c98172c164f5c4d3493a/file2.json"
}
],
"SCMRepository":{
"_ref":"https://rally1.rallydev.com/slm/webservice/v2.0/scmrepository/101417587520"
}
}
]
})
Returned error:
{ [Error: Could not create artifact to collection]
errors:
[ 'Could not create artifact to collection',
'Cannot parse object reference from "{null: {"Action": "M", "PathAndFilename": "file1.json", "Uri": "https://ghe/org/repo/commit/b8460460254cb79d3e72c98172c164f5c4d3493a/file1.json"}}"' ] }
It seems to be telling me it tried to find an existing change with that data, but I want to add a new change as specified in the docs and a recent question:
https://github.com/RallyTools/rally-node/wiki/User-Guide#add-to-a-collection
Rally API Add Tags to existing userstory NodeJS
I don't think you can do all of these things at the same time (although that would be pretty cool).
I'd first use the add method to add the changeset like you have specified, but without any changes. And then use the add method again to create the changes on that changeset. Does that work?

Resources