Missing field in Apollo GraphQL Query - javascript

I'm using react with Apollo and a F# backend.
When i make a query i get an error similar to this but i'm not sure why as it seems like stories is present in the response.
Missing field stories in "{\"stories\":[{\"name\":\"Story1\",\"__typename\":\"Story\"},{\"name\":\"Story2\",\"__typename\":\
My code for making the query is:
const client = new ApolloClient({
uri: '/graphql',
});
client
.query({
query: gql`
query testStoryQuery
{
stories
{
name
}
}
`
})
.then(result => console.log(result));
Finally the raw response returned by the server is:
{"data":"{\"stories\":[{\"name\":\"Story1\",\"__typename\":\"Story\"},{\"name\":\"Story2\",\"__typename\":\"Story\"},{\"name\":\"Story3\",\"__typename\":\"Story\"}]}"}
The only thing I've tried so far is jsonifying the response (i.e. the ") around fields, but it doesn't seem to find the field either way.
Update (extra info)
The full stack trace
Any help would be appreciated, i'll continue working on it in the meantime.
Thank you :)

Bad response format:
{"data":____"____{\"stories\":[{\"name\":\"Story1\",\"__typename\":\"Story\"},{\"name\":\"Story2\",\"__typename\":\"Story\"},{\"name\":\"Story3\",\"__typename\":\"Story\"}]}____"____}
This way data is a string, not object.
Also bad names \r\n\t\t\t\t__typename in a stack trace.
For more details run some working example (any apollo client project) and compare arguments passed to writeToStore.ts methods using browser debugger breakpoints.

Related

"redirect_uri_mismatch" when sending authentication code to GoogleAPI

I am having trouble with the authentication process for the GoogleAPI. In the end I want to be able to read the users steps using the GoogleFit API and then store that value in a database. Currently I'm using restdb.io and executing javascript in codehooks.
The documentation from Google that I am following can be found here, clicking on the HTTP/REST option in the code examples. At the moment I am at step 5: I have gotten the users authentication code and stored it in the database. Now I have to POST the code along with some other parameters and get the access and refresh tokens.
If the POST is successful (from what I understand) I should get back a 200-OK message that the request was valid. Google will then POST a JSON body with the access and refresh token to the redirect_uri that I have specified in my GoogleAPI credentials page and the initial request. At redirect_uri I have to handle the request and save the two values.
The problem is that I receive a redirect_uri_mismatch - Bad Request message from Google as a response when executing the request. I get it at the log.debug("ERROR HERE: " + [...]); in the code below:
async function mainFunction(){
const authCode = THIS_IS_MY_AUTHENTICATION_CODE;
try {
var answer = await postRequestToGoogle(authCode);
//do stuff with response from Google
} catch (error) {
//do stuff
}
}
async function postRequestToGoogle(authCode){
//body for the request
const params = "code=" + authCode + "&" +
"client_id=THIS_IS_MY_CLIENT_ID" + "&" +
"client_secret=THIS_IS_MY_CLIENT_SECRET" + "&" +
"redirect_uri=THIS_IS_MY_REDIRECT_URI" + "&" +
"grant_type=authorization_code";
try{
const result = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: params})
.then(res => {
log.debug("ERROR HERE: " + JSON.stringify(res.json()));
return res.json();
})
//return JSON back main function
return result;
}catch(error){
//do stuff
}
}
I looked up the error message and tried some things:
Copy and pasted multiple different Authorized redirect URI from the GoogleAPI credentials page into the code to make sure that there is no problem with
http/https
www/no www
trailing slashes
typos or capitalization
Waited for changes to be processed by Google (read that it can more than 30min)
Changed all the other parameters to see if the redirect_uri is actually the problem
If code is changed the message is invalid_grant - Bad Request
If client_id is changed the message is invalid_client - The OAuth client was not found
If client_secret is changed the message is invalid_client - Unauthorized
If the grant_type is changed the message is unsupported_grant_type - Invalid grant_type
That's why I think the issue is the redirect_uri, but it's unclear to me how since I copy&pasted it. Something that came to mind was that maybe the value of redirect_uri gets changed when it's read by Google? Or maybe when the request is being put together? Do some characters have to be replaced?
I tried to analyze the request with Wireshark but didn't think about the fact that it's HTTPS so I would have I would have to decrypt it.. Is that something I should look into?
Thank you for taking the time to read all of this! If you have any advice please let me know :)
Update 16.11.20:
I have created a new OAuth 2.0 Client ID and used the new id/secret in my request. The resulting message the same as before. I will wait and try again tomorrow to see if maybe Google needs some more time. Then I'll try to delete all current IDs and start with a fresh GoogleAPI project.
Update 19.11.20:
Creating a new OAuth 2.0 Client ID did not resolve my problem, neither did creating a whole new GoogleAPI project and adding those credentials into the request. I am in contact with the developers of restdb.io and have asked them to add the Google Auth Library: Node.js Client to the list of supported Node.js packages. Hopefully that will help, I will give it a try as soon as it can be used :)
Update 02.12.20:
No progress so far, but I'm optimistic that the developers will add the package soon. I will post a final update as soon as I am done with this project.

Zapier custom response object

Working on creating a custom zapier integration using zapier CLI. My API endpoint is not technically a create, but it uses the POST method so I made it under the create definition in zapier. I set my output fields to empty, but it breaks on my empty response object.
outputFields: []
The error message:
We had trouble sending your test through.
Unexpected end of JSON input
Hide details
Troubleshooting Errors | Contact Support
What happened (You are seeing this because you are an admin):
Starting POST request to https://api.fake.com/v2/demo-finance/live/csh-search
Received 202 code from https://api.fake.com/v2/demo-finance/live/csh-search after 596ms
Received content ""
Unexpected end of JSON input
Everything is working as expected the request went through it is just not happy with the empty string response not being valid JSON. Is there some way to tell zapier this is an acceptable response object?
David here, from the Zapier Platform team.
It's fine if your API works that way, but you still need to return something json serializable from your function. Try something like this:
const performCreate = async (z, bundle) => {
const response = await z.request('https://api.fake.com/v2/demo-finance/live/csh-search')
if (response.statusCode === 202) {
return {}
}
// handle errors, other cases, whatever
// just make sure to return an object
}
As a side note, just because the request uses a POST request doesn't mean it needs to be a Create; it should be whatever type makes the most sense for the operation. If it's a search (like the fake url suggests) a search is probably the way to go.

Network error: Unexpected token < in JSON at position 0 at new ApolloError

const httpLink = createHttpLink({
uri: 'http://localhost:3090/'
})
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
})
client.query({
query: gql`
query users {
email
}
`,
})
.then(data => console.log(data))
.catch(error => console.error(error));
This query gives an error when fetching from client-side code but when i execute this query in browser on http://localhost:3090/graphql it fetches data correctly
The graphql endpoint you are posting your queries to is missing the /graphql. So your server probably returns an html document containing the 404 error message that starts with < from <html.... Apollo tries to parse that as the query result and fails to do so.
Check that httpLink is actually localhost:3090/graphql.
Also the syntax of a query is either:
{
users {
email
}
}
or if you want to name the query:
query Users {
users {
email
}
}
For posterity in case someone finds this in the future, another reason you might get this error is if your API is returning something other than JSON.
https://medium.com/programmers-developers/one-simple-apollo-client-debugging-tip-youll-like-7877a97b9c16
I ran into this issue because the content type that was being returned from my API was text/plain rather than application/json. Apollo lets you specify a different body serializer in this case.
https://www.apollographql.com/docs/link/links/rest/
This happens when you do not define the path correctly in the queries files. This is a typechecking error when passing arguments
In my case this error was being thrown due to a trailing slash I had after the API URL. A possible fix would be checking your API URL properly and ensuring it is referencing the correct URL.
In my case, I only had to take out the trailing slash / after the URL.
As #Trixn posted: "So your server probably returns an html document containing the 404 error message that starts with < from <html.... Apollo tries to parse that as the query result and fails to do so."
In my case, I did not put "http://" in the beginning of my URL, and this returned a HTML web page with an error message.
Also check that usually, you should use "https://"
Make sure that you have configured the uri for httpLink and wsLink same.
I have seen this error when I had different uris as below.
httpLink had uri : "http://localhost:4000"
wsLink had uri: "ws://localhost:4000/graphql"
setting httpLink's uri to http://localhost:4000/graphql helped resolving the issue.
In my case, I recieved the same error, when I switched from a create-react-app to a next JS app pointing to port 3000.The react app had some values saved to local storage (tokens). In my case all I had to do, was to clear the local storage for localhost:3000, and I got rid of the error.
In my case, there was a typo in my graphql endpoint url. I had added a few characters to the end by accident. I think it would be good practice to add a catch rule for this situation so it does not break the site, just does not show the content and posts error to console log.

How to return the http status code using "graphql-request"?

I've been playing around with "graphql-request" and I like it because of it's simplicity. Is there any way of returning the http status code from my request also? Currently the following doesn't work (response.status):
const {request} = require('graphql-request');
const query = `{
Post(id: 1) {
id
title
views
User {
name
}
Comments {
date
body
}
}
}`;
request('http://localhost:3000', query)
.then(response => console.log(response.status))
.catch(err => { throw new Error(err); });
The Documentation doesn't cover returning status codes. Hopefully it's possible. Thanks.
You can't, the way it's written now.
Status codes are only returned in the event of a network error. If you look at the source code for this package, you can see that a status code is not returned on Fetch#ok:
request: https://github.com/graphcool/graphql-request/blob/master/src/index.ts#L66
rawRequest: https://github.com/graphcool/graphql-request/blob/master/src/index.ts#L34
However, there's nothing stopping you from forking the project and adding the status code to the data object. You could even make a PR back to the project. Maybe they'll merge it :)

Firebase FCM error: 'InvalidRegistration'

I am currently trying to send a PushNotification to a Device Group using FCM with the help of Firebase Cloud Functions but once the notification is sent, it returns with code 200 but with failure :
SUCCESS response= {
multicast_id: 8834986220110966000,
success: 0,
failure: 1,
canonical_ids: 0,
results: [ { error: 'InvalidRegistration' } ]
}
Here is the code I am using to send this notification... what am I missing?
const options = {
method: 'POST',
uri: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Authorization': 'key=' + serverKey,
},
body: {
to: groupId,
data: {
subject: message
},
notification: {
title: title,
body: body,
badge: 1,
},
content_available: true
},
json: true
};
return rqstProm(options)
.then((parsedBody) => {
console.log('SUCCESS response=', parsedBody);
})
.catch((err) => {
console.log('FAILED err=', err);
});
Where JSON values title, body, subject, message are String
In my case, I was sending notifications to topic ("topics/my-topic"). I was missing prepending / in the starting of topic so I was getting the same issue. SO topic should be /topics/my-topic.
May be this helps!!
There is an easier way to send a message to a device group from a Cloud Function. Use admin.messaging().sendToDeviceGroup(). Sample code and instructions are in this guide.
I think your current method is failing because there is something wrong with the group notification key provided in groupId. It should be the string key value that was returned when you created the device group. The error codes are listed in this table. For 200/InvalidRegistration it says:
Check the format of the registration token you pass to the server.
Make sure it matches the registration token the client app receives
from registering with Firebase Notifications. Do not truncate or add
additional characters.
I was losing my mind with this InvalidRegistration error.
Eventually the problem was that I was subscribing my device to "example" but sending the notification json to: "example".
But we actually need to send to "/topics/example"
2 hours of my life wasted..
A registration token is tied to a certain group of senders. When a client app registers for FCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app.
Al you need to do is add a http header 'project_id' with your sender id.
I was getting InvalidRegistration:
Basic meaning: you are using the wrong token. Why? This may happen when you a new registrationToken is given to you in onNewToken (docs), but for some reason you are using the old token. That could happen when:
You're using a different push notification library which remembers token (stores it somewhere locally) and you didn't update that library with the new token.
Your application (or other library dependencies) implements another FirebaseMessagingService, and they conflict. Only one service can accept (react to) to the action sent by the FirebaseMessaging Android library's when a new token is given to it. You can double check this by opening the AndroidManifest.xml in Android Studio and selecting the Merged Manifest tab at the bottom of the tab. You can also place debuggers in each Service from each library you use. You'll see that only one service's onNewToken gets called.
When they conflict, one doesn't get the correct token, and the FCM registration token that gets registered would be wrong. Sending a message to a wrong registration, gets you InvalidRegistration.
for me, it was a mistake that I was passing an Id from my models instead of the tokens of the users
InvalidRegistration simply means that the token is either invalid or expired. You can uninstall the app and then reinstall and get a new token and then try with that token. This will definitely solve your problem.
You can read more here.

Categories

Resources