How to pass the Query Data in Body for making REST API call in graphql - graphql

I am doing a post operation where i am getting some response.
My URl looks Like:
http://domainname/api/v1:id
As a part of body i want to pass the below data:
{ elemetnt { id, name } }
Can anybody suggest me how i can achieve this.
i am trying with the below code but i am getting 404:
let queryParam = `{ elemetnt { id, name } }`;
this.http.post(`http://domainname/api/v1:1`, {
query: queryParam,
}, {
headers: new Headers({
'Content-Type': 'application/graphql',
}),
})
.catch((error: Response | any) => {
console.log(error);
return Observable.of(error);
})
.subscribe((res) => {
console.log(JSON.stringify(res));
});
I know i am doing something wrong. But, if somebody can help me on this then it would be great help.

It depends on method which receiving this data, but this is correct format for you as given in question
queryParam= { element : { id: "0000" , name: "name" };
you may need to stringy your solution

Canyou please try with
'Content-Type': 'application/json'
and pass json body like
{"query":"{ elemetnt { id, name } }" }
I think this may help you

Related

Strapi update username from custom controller

I am trying to create a custom controller to update the user profile.
I created the routing file and the corresponding controller.
Routing file: server/src/api/profile/routes/profile.js
module.exports = {
routes: [
{
method: 'GET',
path: '/profile',
handler: 'profile.getProfile',
},
{
method: 'PUT',
path: '/profile',
handler: 'profile.updateProfile',
},
]
}
Controller: src/api/profile/controllers/profile.js
async updateProfile(ctx) {
try {
const { id } = ctx.state?.user;
const user = strapi.query('admin::user').update({
where: { id },
data: {
username: "testUsername"
}
})
ctx.body = "User updated"
} catch(error) {
ctx.badRequest("Something went wrong", { error })
}
},
The above code returns "User updated", but the username does not update. I am executing the PUT call with a correct Bearer authorisation token and the user permissions for that user are set to enable "updateProfile".
Oddly enough, the same code, when changed to update a different API item, works perfectly fine:
async updateArticle(ctx) {
try {
const { id } = ctx.state?.user;
const article = strapi.query('api::article.article').update({
where: { author: id },
data: {
title: "New title"
}
})
ctx.body = article
} catch(error) {
ctx.badRequest("Something went wrong", { error })
}
},
I am also confused by different syntaxes appearing in the official Strapi documentation, for example some docs mention:
strapi.query('admin::user').update({ id }, data)
But in other places in the documentation its:
strapi.plugins['users-permissions'].services.user.update({ id });
And then elsewhere:
strapi.query('user', 'users-permissions').update(params, values);
Another question is: do I need to sanitise the input / output in any way? If yes, how? Importing sanitizeEntity from "Strapi-utils" doesn't work, but it's mentioned in several places on the internet.
Additionally, I cannot find a list of all ctx properties. Where can I read what is the difference between ctx.body and ctx.send?
The lack of good documentation is really hindering my development. Any help with this will be greatly appreciated.

How to POST correctly a form that have data and files with VueJS, Axios and Laravel?

I am posting here as a beginner of VueJS and Laravel. I am stuck with a problem that I can't fix by myself after hours of search.
I would like to know how correctly send and get back the inputs of a form (complex data and files).
Here is the submit method of the form:
onSubmit: function () {
var formData = new FormData();
formData.append("data", this.model.data);
formData.append("partData", this.model.partData);
if (this.model.symbolFile != null) {
formData.append("symbolFile", this.model.symbolFile);
}
if (this.model.footprintFile != null) {
formData.append("footprintFile", this.model.footprintFile);
}
axios
.post("/api/updatecomponent", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
},
The variable Data and PartData contains multiple string fields which will be stored in different tables in my database. Example :
Data
{
string Value,
string Tolerance,
string Power
}
Here is the method of the Controller in the server side:
public function updateComponent(Request $req)
{
$data = $req->input('data');
$partData = $req->input('partData');
$symbolFile = $req->file('symbolFile'); // is null if the user did not modify the symbol
$footprintFile = $req->file('symbolFile'); // is null if the user did not modify the footprint
// etc...
}
I am able to get the files, everything work for that and I can store and read them :)
But, the problem is that I am unable to get back properly my Data or PartDat.
When I do :
dd($partData);
I got as result in the console:
"[object Object]"
I am almost sure that I don't use correctly the FormData but after hours of search, I can't find the good way I should gave the Data and PartData to the FormData.
My code was working well for Data and PartData until I add FormData to support the file upload :(
Thank you for your help :)
Here my working code:
Client side:
var formData = new FormData(); // create FormData
formData.append("subcat", this.subcategory);// append simple type data
formData.append("data", JSON.stringify(this.model.data));// append complex type data
axios // send FormData
.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
Server side:
public function createComponent(Request $req)
{
$subcategory = $req->input('subcat'); // get the input parameter named 'subcat' (selected subcategory)
$data = json_decode($req->input('data'), true); // get the input, decode the jason format, force to return the result as an array
}
I hope it will help other peoples :)
Simple solution
let data = new FormData();
data.append('image',file_name.value);
_.each(form_data, (value, key) => {
data.append(key, value)
})
console.log('form data',data);
Now you can get data in laravel controller like:
$request->title
$request->description
$request->file

Apollo-fetch GraphQL Request

I am quite new to GraphQL I am struggling to fetch my data from my API on front-end.
I am using apollo-fetch to build the query and make the request, which is
const fetch = createApolloFetch({
uri: `${BASE_API_URL}/graphql`,
});
fetch({
query: `{
transactions(limit: 3) {
tid
terminalNo
issuerId
}
}`,
}).then(res => {
console.log('res', res);
}).catch(err => console.log(err));
I am receiving this error:"Syntax Error: Expected Name, found String "query"".
The weird thing is that using Postman, with pretty much the same Query I receive the correct data.
this is the query I am using on postman
query {
transactions(limit: 3) {
tid
terminalNo
issuerId
}
}
What am I doing wrong here ? I tried some variations on the query, but the result was the same.
Your query string does not have the keyword query and also has an additional bracket. It should be as follows
fetch({
query: `
query transactions {
transactions(limit: 3) {
tid
terminalNo
issuerId
}
}
`,
})
The solution I found was using plain javascript, not sure yet why apollo-fetch was having the error
fetch(`${BASE_API_URL}/graphql`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: `query {
transactions(limit: 3, offset: 0) {
tid
terminalNo
issuerId
}
}`,
})
.then(res => res.json())
.then(res => (
this.setState({ transactions: res.data.transactions })
))
.catch(error => console.log('error', error));
Hope it helps anyone with the same problem.

Writing Structural Expectations with Jest

I am looking to write what I am calling structural expectations with Jest and I am not sure how this could be accomplished.
To start I have a graphql server and a database with a number of todo items. I currently have the following test that just returns true if the content within the database is the same as the response that I have written. I want to check instead that the response looks like an object with data that could be anything.
Here is the code that I have:
describe('To Do:', () => {
it('add todo items', async () => {
const response = await axios.post('http://localhost:5000/graphql', {
query: `
query {
getTodoItems {
message
id
dateCreated
dateDue
}
}
`
});
const { data } = response;
expect(data).toMatchObject({
data: {
getTodoItems: [
{
message: "message",
id: "5bd9aec8406e0a2170e04494",
dateCreated: "1540992712052",
dateDue: "1111111111"
},
{
message: "message",
id: "5bd9aeec60a9b2579882a308",
dateCreated: "1540992748028",
dateDue: "1111111111"
},
{
message: "new message",
id: "5bd9af15922b27236c91837c",
dateCreated: "1540992789836",
dateDue: "1111111111"
}
]
}
})
});
});
Now I want to write something like this, where there can be any number of returned items and they follow similar structuring:
describe('To Do:', () => {
it('add todo items', async () => {
const response = await axios.post('http://localhost:5000/graphql', {
query: `
query {
getTodoItems {
message
id
dateCreated
dateDue
}
}
`
});
const { data } = response;
expect(data).toMatchObject({
data: {
getTodoItems: [
{
message: expect.any(String),
id: expect.any(String),
dateCreated: expect.any(String),
dateDue: expect.any(String)
} // There needs to be unlimited additional items here
]
}
})
});
});
I have been looking throught the docs and I even tried nesting the expectations but I can't seem to get the desired response. Let me know what yo think or if I can clarify in any way.
I figured out the best way for me to do it. I would love to hear better answers. I wrote a function within the scope of the test as a jest.fn and then I called it. In that function, I made custom checks to parse the data that was received in the response. From there I added an expect function with the 'toHaveReturnedWith' method to see what the response of my custom function was and finishing out the test.
const addTodoResponse = jest.fn(() => {
// Custom parsing and check here
// Returns true or false
});
addTodoResponse();
expect(addTodoResponse).toHaveReturnedWith(true);
Are there better ways to do this out there?

angular6 - I can't get response from Scopus API

I want to use the Scopus API to verify that a DOI exists. I'm using the "Cited By" option. I did a test of this "http://api.elsevier.com/content/search/scopus?query=DOI(10.1016/j.stem.2011.10.002)" link in POSTMAN and it works, but when I did the implementation in Angular this is what returns.
Angular code
let headers = new Headers({
'X-ELS-APIKey': apikey,
'Accept': 'application/json',
});
this._http.get('http://api.elsevier.com/content/search/scopus?query=DOI(' + doi + ')', { headers: headers }).pipe(map(res => res.json())).subscribe(
response => {
console.log("Response");
console.log(response);
},
error => {
console.log("Error");
console.log(error);
}
);
Any help is greatly appreciated :)
Finally I solved it, the problem was that the "doi" string needed to go through the encodeURIComponent() function. I leave the code in case someone needs it.
welcome.component.ts:
let doi = encodeURIComponent('10.1017/j.stem.2011.10.002');
this._scopusService.getPublication(doi).subscribe(
response => {
console.log("DOI exists");
},
error => {
console.log("DOI doesn't exists");
}
scopus.service.ts:
public getPublication(doi) {
let headers = new Headers({
'Accept': 'application/json',
'X-ELS-APIKey': this.apiKey
});
return this._http.get('https://api.elsevier.com/content/search/scopus?query=DOI(' + doi + ')', { headers: headers }).pipe(map(res => res.json()));
}

Resources