Need help to debug this updateLink resolver - graphql-js

I need to implement an updateLink to my graphQL server, but it keeps throwing 'id is not defined' error. The server doesn't have a database yet, only an array for practice purpose.
I have defined the schema for the mutation for update, also wrote the resolver, but it just didn't work.I have looked into the apollo document, it seems my resolver and schema are correct.
The following is the resolver
updateLink:(parent,args)=>{
const link = {
id:args.id,
description:args.description,
url:args.url,
}
links[Number(id)]=link
return link
}
},
The following the schema
type Query {
info: String!
feed: [Link!]!
link(id:ID!):Link
}
type Mutation {
post(url: String!, description: String!): Link!
updateLink(id:ID!,url:String!, description: String!): Link
delete(id:ID!):Link
}
type Link {
id: ID!
description: String!
url: String!
}
The expected outcome should be the update of the server of the link array, but I got the following error instead.
{
"data": {
"updateLink": null
},
"errors": [
{
"message": "id is not defined",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"updateLink"
]
}
]
}

You reference a variable called id here:
links[Number(id)]=link
but you have not defined a variable with that name as the error indicates. I would suggest adding a linter to your project to help you catch errors like that.

Related

GraphiQL Mutation: How can I ignore other objects in query variables

Currently having hard time setting up my end points clerk to hasura.
I am absolute new to this platform specially at GraphiQL and just following documentations and youtube video
What I am trying to do is import/insert specific data i neeed only from clerk. Here's the sample query variables:
{
"data": {
"birthday": "",
"created_at": 1654012591514,
"email_addresses": [
{
"email_address": "example#example.org",
"id": "idn_29w83yL7CwVlJXylYLxcslromF1",
"linked_to": [],
"object": "email_address",
"verification": {
"status": "verified",
"strategy": "ticket"
}
}
],
"external_accounts": [],
"external_id": "567772",
"first_name": "Example",
"gender": "",
"id": "user_29w83sxmDNGwOuEthce5gg56FcC",
"last_name": "Example",
"last_sign_in_at": 1654012591514,
"object": "user",
"password_enabled": true,
"phone_numbers": [],
"primary_email_address_id": "idn_29w83yL7CwVlJXylYLxcslromF1",
"primary_phone_number_id": null,
"primary_web3_wallet_id": null,
"private_metadata": {},
"profile_image_url": "https://www.gravatar.com/avatar?d=mp",
"public_metadata": {},
"two_factor_enabled": false,
"unsafe_metadata": {},
"updated_at": 1654012591835,
"username": null,
"web3_wallets": []
},
"object": "event",
"type": "user.created"
}
What I only need to this object is content inside of the "data" is: created_at, first_name, user_id, updated_at, profile_image_url
The GraphiQL Query I did is:
mutation CreateUser(
$created_at: String,
$first_name: String,
$user_id: String,
$updated_at: String,
$profile_image_url: String
)
{
insert_users_one(object:
{
created_at: $created_at,
first_name: $first_name,
user_id: $user_id,
updated_at: $updated_at,
profile_image_url: $profile_image_url,
}) {
created_at
first_name
user_id
updated_at
profile_image_url
}
}
Which throwing error of:
{
"errors": [
{
"extensions": {
"code": "validation-failed",
"path": "$"
},
"message": "unexpected variables in variableValues: object, type, data"
}
]
}
I tried using other method like this:
mutation CreateUser($data: users_insert_input!) {
insert_users_one(object: $data) {
created_at
first_name
user_id
updated_at
profile_image_url
}
}
But it is still having error because of object and type fields
{
"errors": [
{
"extensions": {
"code": "validation-failed",
"path": "$"
},
"message": "unexpected variables in variableValues: object, type"
}
]
}
Here's a sample of GraphQL type:
//is this how you break things down?
type Mutation {
data(
created_at: Int
first_name: String
id: String
updated_at: Int
profile_image_url: String
): Data
}
//this is what i will send in the database, things that I only need
type Verification {
status: String
strategy: String
}
type EmailAddresses {
email_address: String
id: String
object: String
verification: Verification
linked_to: [String]
}
type Data {
birthday: String
created_at: Int
external_id: String
first_name: String
gender: String
id: String
last_name: String
last_sign_in_at: Int
object: String
password_enabled: Boolean
primary_email_address_id: String
primary_phone_number_id: String
primary_web3_wallet_id: String
profile_image_url: String
two_factor_enabled: Boolean
updated_at: Int
username: String
web3_wallets: [String]
phone_numbers: [String]
external_accounts: [String]
email_addresses: [EmailAddresses]
}
type AutogeneratedMainType {
object: String
type: String
data: Data
}
I was expecting based on documents, It will ignore aren't included data.
Visit Github Discussions here
Context about the error
This is error you are receiving is based on this graphql spec - https://spec.graphql.org/June2018/#sec-Input-Objects . More over there is also a different spec for validation against variables here - https://spec.graphql.org/June2018/#sec-All-Variables-Used
TLDR; Using variable which isn’t defined in operation, will result into “unexpected variableValues” error. In your case apart from data , you have type and object as variables in your query variables object which is not defined in operation itself. Remember that query variables is an “object” expecting the variable key-values in it.
Workaround
Cleanest way to do this is to sanitize your object (which you will pass in query variables) by either creating a new object from it and passing data to it or either you remove the unnecessary fields from it which are not defined in operation. You could just delete the properties of that object. Consider yourObject containing data,type and object fields. Then you can do delete yourObject.type and delete yourObject.object. And then pass it.
This workaround is intended for client side code. But there's no exception for graphiQL explorer as that error would be thrown upon undefined variables in operation. If trying via graphiQL explorer, you would manually need to not pass those variables in query variables scope.
Conclusion
This behavior is in compliant with this graphql spec and not with Hasura directly, so we would suggest you to go through those graphql spec links and understand the aspect of it.

AWS AppSync: Add multiple query string items in request mapping template not work

I have a request mapping template as follow: This is mapped to a GraphQL query called getPost
{
"version": "2018-05-29",
"method": "GET",
## E.G. if full path is https://api.xxxxxxxxx.com/posts then resourcePath would be /posts **
"resourcePath": "/event1/wp-json/wp/v2/posts",
"params":{
## "query":$util.toJson($ctx.args),
"query":{
"slug": "$ctx.args.slug",
"lang": "$ctx.args.lang"
},
"headers": {
"Authorization": "$ctx.request.headers.Authorization"
}
}
}
A valid JSON response URL is this:
http://my_domain/wp-json/wp/v2/posts?slug=new-post-en&lang=zh-hant
But when I tested in "Queries" using this:
query MyQuery {
getPost(slug: "new-post-en", lang: "zh-hant") {
id
}
}
No result return, but it should have at least one record returned.
Can you please tell me what's wrong with my request?
Thank you.
UPDATED Add Schema:
type Post {
id: ID!
date: String!
slug: String!
type: String!
link: AWSURL
title: AWSJSON!
content: AWSJSON!
excerpt: AWSJSON!
}
type Query {
getPost(slug: String!, lang: String): Post
getPosts: [Post]
}
schema {
query: Query
}
I found the solution:
When we make a request to http://my_domain/wp-json/wp/v2/posts?slug=new-post-en&lang=zh-hant, it will return an array in terms of JSON
However, in the schema, the query is: getPost(slug: String!, lang: String): Post
Notice the return type Post, it is not an array
So to get a valid return, we change it from
getPost(slug: String!, lang: String): Post to
getPost(slug: String!, lang: String): [Post]
And hola~ It works!

Why I'm I getting an error saving date using graphql > hasura > postgres

I'm using react, apollo, graphql, hasura, postgres as my stack to interact with the database. I think my issue is something small, so I'll just focus on the part that's not working rather than posting the whole code.
Thanks.
Error: GraphQL error: unexpected variables in variableValues: birthday
at new ApolloError (bundle.esm.js:63)
at Object.next (bundle.esm.js:1004)
at notifySubscription (Observable.js:135)
at onNotify (Observable.js:179)
at SubscriptionObserver.next (Observable.js:235)
at bundle.esm.js:866
at Set.forEach (<anonymous>)
at Object.next (bundle.esm.js:866)
at notifySubscription (Observable.js:135)
at onNotify (Observable.js:179)
at SubscriptionObserver.next (Observable.js:235)
at bundle.esm.js:76
variables{ id: 2324324, name: "Fred", birthday: "1991-01-11" }
If i remove birthday the query works.
Here is the function
const onUpdateUser = (options) => {
updateUser({
variables: Object.assign({ id: userId }, options),
optimisticResponse: {
__typename: "mutation_root",
update_users: {
__typename: "users_mutation_response",
affected_rows: 1,
returning: [
{
__typename: "users",
id: userId,
...options,
},
],
},
},
});
};
input {birthday: '1991-01-11'}
So without looking at your graphql query, I think you may be thinking of it a little bit off.
You can't dynamically add non-existent variables to a graphql query. The error is telling you that you are trying to add a variable that doesn't exist in your query
i.e. this with NOT work because you haven't defined birthday.
mutation updateUser(
$userId: Int!
$birthday (UNDEFINED)
) {
rest of query...
}
If you need to add a dynamic amount of variables, you could do something like this.
React Code
const onUpdateUser = (options) => {
updateUser({
variables: {
userId,
userVariables: options
},
optimisticResponse: {
__typename: "mutation_root",
update_users: {
__typename: "users_mutation_response",
affected_rows: 1,
returning: [
{
__typename: "users",
id: userId,
...options,
},
],
},
},
});
};
GraphQL mutation
mutation updateUser(
$userId: Int!
$userVariables: user_set_input!
) {
update_user(
where: { id: { _eq: $userId} }
_set: $userVariables
) {
affected_rows
}
}
https://hasura.io/docs/1.0/graphql/manual/mutations/update.html

How to fix constructor error in GraphQL Mutation with Mongoose Schema [duplicate]

This question already has answers here:
Mongoose TypeError: User is not a constructor
(1 answer)
TypeError: User is not a constructor
(6 answers)
Closed 3 years ago.
Having a lot of trouble with a GraphQL mutation Mongoose error for validating if a user is new or existing in MongoDB. Per the code below the error message is "message": "User is not a constructor".
A similar issue is here, and I redefined the variable below given each method in the solution to that linked issue with similar errors - only change in error was due to lacking constructor such as when I used other methods like append the error is "User is undefined".
CodeSandbox with all the code: https://codesandbox.io/s/apollo-server-sh19t?fontsize=14
The code in question is:
var userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
trim: true
},
password: {
type: String,
required: true,
trim: true
},
avatar: {
type: String
},
joinDate: {
type: Date,
default: Date.now
},
favorites: {
type: [mongoose.Schema.Types.ObjectId],
required: true,
ref: "Post"
}
});
// compile model
var User = mongoose.model("User", userSchema);
var getUserModel = function() {
return mongoose.model("User", userSchema);
};
Mutation: {
signupUser: async (_, { username, email, password }, { User }) => {
let user = await getUserModel().findOne({ username });
if (user) {
throw new Error("Please choose another username");
}
const newUser = await new User({
username,
email,
password
}).save();
return newUser;
}
}
};
The full error is:
{
"errors": [
{
"message": "User is not a constructor",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"signupUser"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"TypeError: User is not a constructor",
" at signupUser (/xxx/xxx/xxx/servers.js:175:29)",
" at process._tickCallback (internal/process/next_tick.js:68:7)"
]
}
}
}
],
"data": null
}
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"signupUser"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"TypeError: Cannot read property 'create' of undefined",
" at signupUser (/xxxx/xxxx/xxx/servers.js:175:38)"
Any assistance to this issue would be greatly appreciated.
That TypeError is thrown any time you try to use the new keyword with something that's not a constructing, including an undefined value. Even if you define a User variable outside of the constructor, you're still shadowing that variable because you're destructuring the context parameter and declaring a User variable that way. If you're not passing the User model to your context correctly, attempting to get the value from the context will result in the value being undefined. Either fix the context or don't unnecessarily destructure it.

Ember.js - Error while loading route: TypeError: Cannot set property 'store' of undefined

I'm getting the following error in my Ember.js app.
Error while processing route: books Cannot set property 'store' of undefined TypeError: Cannot set property 'store' of undefined
at DS.Store.Ember.Object.extend.modelFor (http://localhost:8080/js/libs/ember-data.js:2986:19)
at DS.Store.Ember.Object.extend.recordForId (http://localhost:8080/js/libs/ember-data.js:2437:17)
at deserializeRecordId (http://localhost:8080/js/libs/ember-data.js:3355:23)
at deserializeRecordIds (http://localhost:8080/js/libs/ember-data.js:3369:5)
at http://localhost:8080/js/libs/ember-data.js:3335:7
at http://localhost:8080/js/libs/ember-data.js:7117:16
at http://localhost:8080/js/libs/ember.js:14899:20
at Object.OrderedSet.forEach (http://localhost:8080/js/libs/ember.js:14741:14)
at Object.Map.forEach (http://localhost:8080/js/libs/ember.js:14897:14)
at Function.DS.Model.reopenClass.eachRelationship (http://localhost:8080/js/libs/ember-data.js:7116:38)
I'm using
ember.js version 1.7.1 and
ember-data.js version 1.0.0-beta.5.
I have the following project:
window.App = Ember.Application.create();
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:8080'
});
App.Router.map(function() {
this.resource('books', { path: '/' });
});
App.BooksRoute = Ember.Route.extend({
model: function() {
return this.store.find('book');
}
});
App.Author = DS.Model.extend({
firstname: DS.attr('string'),
lastname: DS.attr('string')
});
App.Book = DS.Model.extend({
title: DS.attr('string'),
authors: DS.hasMany('author')
});
and the following is my JSON response to http://localhost:8080/books.
{
"books":
[
{
"id": 0,
"authors":
[
{
"id": 0,
"firstname": "Andrzej",
"lastname": "Sapkowski"
}
],
"title": "Zaklínač I: Poslední přání"
},
...
]
}
When I remove the Author model and the authors relationship declaration, the application works fine.
The error message I'm getting doesn't reveal the cause and according to what I've found on the Internet, my code seems to be ok.
What's the problem?
Wow, I can't believe I didn't notice this, but your data isn't formatted properly. It should look something like this:
{
"books": [{}, {}, {}],
"authors": [{}, {}, {}]
}
This is explained in the REST adapter guide.