How to pass javascript variable to graphql query? - javascript

I have a super simple GraphQl query, but im having trouble to make the query dynamic based on input. Lets say you will get a string in javascript that you want to pass along to the query, how is it done? Take example below, how would i replace the hardcoded string of "3111" on the Sku field in the product but instead inserting the value from the variable myString? I am just getting errors when i try to pass it along.
let myString = "3111"
`query getProductBySku {
site {
product(sku: "3111") {
id
entityId
name
sku
}
}
}`

Have a look here: https://graphql.org/graphql-js/passing-arguments/
In your case scenario:
var query = `query getProductBySku($sku: String) {
site {
product(sku: $sku) {
id
entityId
name
sku
}
}
}
`;
fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
variables: { "3111" }, // this refers to SKU
})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));
Basically other than creating a query that allows argument to pass, you need a POST request with the body setup to accomodate the inputs which are expected to be fulfilled

Related

How do I get the return statement from JavaScript's Fetch?

Now I'm using Fetch to fetch some data from an API in SpringBoot.
const onSubmit = (data) => {
fetch("http://localhost:8080/addMedicine", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
};
Here is the Java code.
#PostMapping("/addMedicine")
public String addMedicine (#RequestBody Medicine medicine){
return medicineService.addMedicine(medicine);
}
public String addMedicine(Medicine medicine) {
medicineRepository.save(medicine);
System.out.println("Added medicine "+ medicine.getMedicineName());
return "Added medicine "+ medicine.getMedicineName() ;
}
The above methods are from different classes I just put them here to simplify my question.
Now when I use Postman I get the statement like
"Added medicine X"
Now when I post the data from my Frontend app which is in React. I want to get that statement so that I can use it to display something on the page as a confirmation.
How am I going to do it or for more info how does even Postman do it because it looks so easy from them? Please help.
this should work :
const onSubmit = (data) => {
fetch("http://localhost:8080/addMedicine", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}).then(data=>{
// Do something ....
})
};

Fetch(): Request body malformed

I want to make a fetch request to an API that accepts different types of body requests: twitter handle, facebook link, phone number, etc. The structure of the body is:
body: {
"typeOfHandle": "input"
}
Since there are different types of handles, I test the input type and assign it to the body accordingly, as seen below:
// handle is the input
let atSign = /^[#]/,
handleIsTwitter = atSign.test(handle.value),
handleType;
handleIsTwitter ? handleType = `"` + "twitter" + `"` : console.log("not twitter");
let abc = `"` + handle.value + `"`;
let bodyOfFetch = `{${handleType}: ${abc}}`;
console.log("body: " + bodyOfFetch);
fetch("xxx", {
method: "POST",
headers: {
Authorization: "xxx"
},
body: JSON.stringify(bodyOfFetch)
})
.then(function(res) {
return res.json();
})
.then(function(json) {
console.log(json);
});
However, this method returns a body malformed error. When I do the request statically (i.e. replace the variables with static text, e.g. "twitter": "#alex") it works. I double-triple-quadruple checked the syntax, I don't think that is the problem. Can it be an issue on the API's side?
In your example bodyOfFetch is a string ({"twitter": "#alex"}). Either you can send it directly, this is:
fetch("xxx", {
method: "POST",
headers: {
Authorization: "xxx"
},
body: bodyOfFetch
})
Or you can send a stringify object:
fetch("xxx", {
method: "POST",
headers: {
Authorization: "xxx"
},
body: JSON.stringify({[handleType]: abc})
})
But sending JSON.stringify(bodyOfFetch) will stringify a json string, this will add surrounding " and escape existing quotation marks: "{\\"twitter\\": \\"#alex\\"}"
Hope this helps.

How can I post a json object and a file to asp.net server with fetch

I'm a bit stuck here, I'm trying to post a json object from my indexedDb simultaneously with a IFormFile object to the server. The method that accepts it looks like this:
[HttpPost]
public async Task<IActionResult> Create(BatchModel model, IFormFile vinFile)
{
//logic goes here
}
This method worked earlier, before I had to store my batchModels as Json objects, and were just posted straight from the form with a POST. A lot has changed since then, and now the client will upload it as soon as he gets online again from an offline state, with the following (simplified) method:
if (infoChanged === true) {
fetchPromises.push(
fetch('/Batch/Create/', {
headers: new Headers({
'Content-Type': 'application/javascript' //Tried this with multi-part/form
}),
credentials: 'same-origin',
method: 'POST',
body: batch //, vinFile
})
);
}
return Promise.all(fetchPromises);
For testing I tried to use the method with only the model filled, and the only thing I had to change was that I had to change in the C# code was adding a [FromBody] tag, but now I need the vinFile filled as well.
I tried it already with a FormData object, appending the batch and the vinFile with the same name as in the Create function. But that would result in both variables as null.
The key feature you need to look at is your header. You can change your response to JSON if you do header: { Content-Type: "application/json" }
You want something like this: You need to configure the type yourself.
fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
if(contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then(function(json) { /* process your JSON further */ })
.catch(function(error) { console.log(error); });
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Graphql query with $http.post does not work

The request for the code below goes all ok but I don't get any data back (Just says "Error Not Found" in the "preview" tab of the request in chrome). I try the same query in GraphiQL and it gives back relevant data. I am not sure what I am missing here. Please advise, kind of stuck with this.
PlayService.prototype.getPlays = function(playID) {
//The query.
const playsQuery = `query ($playid: String) {
plays(id: $playid) {
id
items {
nodes {
id
name
}
}
}
}`;
// variables to pass.
const variables = {
playid: playID
};
//The request.
const result = $http.post(
/graphql,
{
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ playsQuery, variables })
}
);
return result && result.data;
};
You appear to be sending the data body as:
{
playsQuery: "<query string>",
variables: {}
}
The GraphQL spec specifies that you must follow this format for GraphQL queries over REST:
http://graphql.org/learn/serving-over-http/
{
"query": "...",
"operationName": "...",
"variables": { "myVariable": "someValue", ... }
}

JSON-Server doesn't update my .json file after fetching some new data

Currently I'm working on little app that's using JSON server but I have a little problem. Objects I'm working with consist of id, name, and complete fields like this {"id": ,"name": ,"complete": }. Fetching data from the server works fine but putting some new data inside it doesn't work. My code looks like this:
export const addNewItem = (newItem) =>{
return fetch(myUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type':'application-json'
},
body: JSON.stringify(newItem)
}).then(res => res.json())
}
After adding new item to my server there only id in it ({"id": some new id}. The name and complete fields are gone. Where am I making mistake?

Categories

Resources