Can GraphQL query a third party API? - reactjs

I'm new to GraphQL and was curious if I could use it to query an external, third-part API for data. I have an express backend and a react frontend and I'm sending a GET request to a third party API for the price of precious metals.
The API responds with one big object that is filled with things I don't need but I still get via HTTP. For example, API is returning this:
{
"gold_bid_usd_toz": "1303.58",
"gold_ask_usd_toz": "1304.58",
"gold_change_dollar_usd_toz": "1.23",
"gold_change_percent_usd_toz": "0.09%",
"gold_high_usd_toz": "1306.51",
"gold_low_usd_toz": "1299.85",
"gold_londonfix_am": "1320.7",
"gold_londonfix_pm": "1319.92",
"silver_bid_usd_toz": "16.5",
"silver_ask_usd_toz": "16.6",
"silver_change_dollar_usd_toz": "-0.02",
"silver_change_percent_usd_toz": "-0.13%",
"silver_high_usd_toz": "16.6",
"silver_low_usd_toz": "16.46",
"silver_londonfix": "16.6",
...LOTS MORE...
}
If I'm only interested in two of the properties, can I do something like this:
query {
gold_bid_usd_toz
silver_bid_usd_toz
}
Just not sure if I have to control backend data in order to use GraphQL. Thanks.

You can return your request response directly from a resolver as it is.
Then in a frontend query matching this resolver, get only what you asked for.
Backend:
rootQuery {
resolverName: () => getThirdParty
}
Frontend:
query {
resolverName {
whatYouWant1
whatYouWant2
}
}
Both your query and resolver should match your graphql schema but not the third party response.

Related

Can you use aws-sdk/util-dynamodb unmarshall in Reactjs?

I have an API Gateway resource which calls a Dynamodb post request to query a table. I'm trying to call the API within my React app using Axios. The API is working, returning the data as expected (console log) but I'm getting errors if I try to use #aws-sdk/util-dynamodb (unmarshall) to convert the api data.items response into JSON and use within React.
./node_modules/#aws-sdk/util-dynamodb/dist-es/convertToNative.js 45:14 Module parse failed: Unexpected token (45:14)
Is there a way to use 'unmarshall' within React? Something like this:
useEffect(() => {
const getGoal = async () => {
try {
const response = await api.get(apiUrl)
setGoal(unmarshall(response.data.Items))
This works if I use a Lambda service, but I'm try to see if I can reduce my code.
While I'm not sure on the issue you are getting with unmarshall function, I would suggest using the DynamoDB Document Client which will return your data already unmarshalled.
The DynamoDB Document client simplifies working with items by abstracting the notion of attribute values. This abstraction annotates native JavaScript types supplied as input parameters, and converts annotated response data to native JavaScript types.

Apollo Client not querying custom scalar types

I've made a datasource API to fetch an external API and retrieve it in JSON format. Everything works perfectly, I can call the query in playground and get all the data.
But when I call that query from the react / apollo client side, the data from the query is always returning null. I'm guessing it has something to do with the scalar type.
Apollo Client Query
// Drops
export const GET_DROPS = gql`
query getDrops {
getDrops
}
`;
Drop Resolver (Server)
import GraphQLJSON from 'graphql-type-json';
export default {
JSON: GraphQLJSON,
Query: {
getDrops: async (_source, _args, { dataSources }) => {
const data = await dataSources.dropsAPI.fetchDrops();
return data.result.data;
}
}
};
Drop Schema
export default gql`
scalar JSON
extend type Query {
getDrops: JSON
}
`;
Apollo Client doesn't currently support custom scalar serialization on the client side at the moment. We do have an older feature requestt to add better support for them and are considering this for a future enhancement to our client library.
Feel free to follow this Github issue if you are interested in this capability, also adding a comment about your use case will help us better understand your needs as well. Thank you!

Error while using searchKitManager in React

I am trying to use the searchKitManager inside react-admin I provided the parameters etc according to the docs but when I run the code it throws errors. Here is how the code works
React Admin is running on http://localhost:3000
Golang backend is running on http://localhost:3006
ElasticSearch is running on http://localhost:9200
When data is inserted in mysql database using golang code it is also inserted in elasticsearch later on in one of my display component I call the above searchkitManager as follows
let apiUrl= 'http://localhost:9200/donate' // what link should I pass, url to elasticsearch or url to my backend
const searchkit = new SearchkitManager('/', {
searchUrlPath: `${apiUrl}/_search`,
});
This code will throw 404 Not Found or 400 Bad Request error but the API works in postman
if I change the above link to
let apiUrl= 'http://localhost:9200/donate' // what link should I pass, url to elasticsearch or url to my backend
const searchkit = new SearchkitManager('/', {
searchUrlPath: `${apiUrl}/_doc/`,
});
I am not getting anything at all sometimes it no error in console and sometimes 400 Bad Request or 405 Post Not Allowed
One last thing the link I am providing as for searchUrlPath should be like that or not? or should I pass the apiUrl in place of /? I tried that as well but just to make sure.
Any kind of help will be really appreciated.
Try doing this:
const elasticSearchUrl = 'http://localhost:9200/<your_index>';
const searchkit = new SearchkitManager(elasticSearchUrl );

Why is req.query always empty?

I'm trying to make a POST request to Express, but whenever I do, I can't access req.query. It's always empty.
The POST request works in Postman, but I can't get it to work in React.
I am wondering if whatever axios is sending over is not readable by the Express middleware. I'm new to Express, so I'm sure I'm missing something basic. Thanks for reading!
From my React file:
tryPost = () => {
axios.post('/login', {
firstName: 'Tom',
lastName: 'Rains'
});
}
From my Express file:
app.post('/login', (req, res) => {
console.log('test'); //prints test
console.log(req.query); //prints as {}
})
req.query refers to query string parameters, in your example you POST a JSON formatted body, no query string parameters are sent hence req.query is empty.
Depending on what way you intend to POST the data, if you want to pass it as query string data then you need to do:
axios.post('/login?firstName=Tom&lastName=Rains');
And then your code would work as is. However, If you want to POST the data as a body (like your example), then there is an additional change that needs applied in your express app i.e.
app.use(express.json())
This will ensure the JSON body gets parsed, then you can access the data via req.body from your route.
Note - Make sure this is configured before you setup your routes

Request to GraphQL with only Queries without Fragments

I want to request to GraphQL Server from Relay only Queries without Fragments.
For example with simple relay app at the link: https://facebook.github.io/relay/prototyping/playground.html#/, this always post to GraphQL server a query inculde Fragments like that:
query GreetingsQuery {
greetingsSchema {
...F0
}
}
fragment F0 on GreetingsQL {
hello
}
But I just want to post a single query without any fragment inside, something like that:
query UserQuery {
users() {
id
name
},
}
Any solutions for that?
You can inline the entire query in your Relay user queries. No need for fragments. Also make sure you don't have an empty parentheses if you don't have query params.

Resources