Array Parameters in Axios - vue.js

I have a problem regarding the string array params as per the below endpoint:
Endpoint: API/resource/Customer?fields=["*"]&filters=[["mobile_no","=","0722123456"]]
How do I serialize the mobile number?
My request should look as follows:
axios.get('api/resource/Customer', {
params: {
fields: ["*"],
filters: [["mobile_no", "=", "++"]],
}
})

Related

Apollo GraphQL Client formatting requests improperly

I have an Apollo GraphQL client running in react native. It connects to a lambda instance running graphQL. My problem is that I am trying to send a mutate request to the server (have not setup queries yet), and the server is getting the following and declaring a syntax error(Expected Name, found String \"operationName\").
When I was testing the graphQL server, the requests looked like the ones specified below. Is Apollo Client not formatting the requests properly (if so why not) or is it functioning as intended?
Body sent from Apollo client to graphQL lambda:
{
"operationName": "createUser",
"variables": {
"firstName": "Jane",
"lastName": "Doe",
"email": "jane#doe.com",
"username": "jane_doe.com",
"provider": "none"
"jwt": "none"
},
"query": "mutation createUser($firstName: String!, $lastName: String!, $email: String!, $username: String!, $provider: String, $jwt: String!) {
createUser(firstName: $firstName, lastName: $lastName, email: $email, username: $username, provider: $provider, jwt: $jwt) {
createdAt
__typename
}
}"}
A Normal request that works from Postman.
mutation {
createUser(firstName: "Jane", lastName: "Doe", email: "jane#doe.com", username: "jane_doe.com", jwt: "none", provider: "none") {
firstName
}
}
Code from react-native app
// The mutation in the render function
<Mutation mutation={createUserMutation}>
{(createUser, error) => {
console.log('error-----------', error);
// If there is an error throw the error
if (error) {
console.log('error----------', error);
}
if (createUser) {
// If the response has data load the response data via the createPlayer property.
return (
<LoginButton
onPress={() => {
this.signIn(createUser);
}}
/>
);
}
// By default it is loading the result so just return loading...
return <Text>Loading...</Text>;
}}
</Mutation>
// The signin function called when the user presses the login button
async signIn(createUser) {
...
try {
Auth.signIn(un, password)
.then(data => {
...
this.createUserFunc(
createUser,
'Jane',
'Doe',
'jane#doe.com',
'jane_doe.com',
'none',
'none'
);
}
...
}
// The create user function called from the signin function
createUserFunc = (func, firstName, lastName, email, username, provider, jwt) => {
const newUser = {
firstName,
lastName,
email,
username,
provider,
jwt,
};
func({variables: newUser});
};
// The gql syntax mutation
const createUserMutation = gql`
mutation createUser(
$firstName: String!
$lastName: String!
$email: String!
$username: String!
$provider: String
$jwt: String!
) {
createUser(
firstName: $firstName
lastName: $lastName
email: $email
username: $username
provider: $provider
jwt: $jwt
) {
createdAt
}
}
`;
Most GraphQL servers that accept requests over HTTP are listening to two different types of content (indicated with the Content-Type header): application/graphql and application/json. You server seems to only listen to requests with a application/graphql body.
The problem with Content-Type: application/graphql is that GraphQL execution consist out of up to three parameters that can be supplied by the client:
The query (required)
The variable values of the query
The operation name
This enables query documents to be entirely static. But if the content of the request is only the GraphQL query, the other parameters need to go somewhere else. In theory they could be supplied as GET parameters but usually all clients use the JSON format to supply all three as outlined here.
As Daniel has pointed out you can use a GraphQL server implementation for your framework/technology of choice to handle that for you.
Alternatively you would have to react to the header of the request yourself (which could be a good exercise but you are probably going to miss an edge case that the library authors have thought of).

How do I format an array passed to params of an axios get to this specific format: [0].mfr=mfr0&[0].mpn=mpn0&[1].mfr=mfr1&[1].mpn=mpn1

I'm making a axios get call to a web api that is looking to have the query string parameters in this specific format which seems uncommon: [0].mfr=mfr0&[0].mpn=mpn0&[1].mfr=mfr1&[1].mpn=mpn1
I've been trying to use the Qs library to stringify the params in the paramsSerializer option.
parts = [{ mfr: "mfr0", mpn: "mpn0" }, { mfr: "mfr1", mpn: "mpn1" }]
findParts(parts, token) {
return axios
.request({
url: "https://<serveraddress>/api/v1/parts/findparts",
method: "get",
params: parts,
headers: {
Authorization: "Bearer " + token,
"Content-Type": "text/plain"
}
})
.catch(error => {
console.log(error);
Vue.notify({
type: "error",
title: "Unable to find parts",
text: "Unable to find parts"
});
});
}
result
0={"mfr":"mfr0","mpn":"mpn0"}&1={"mfr":"mfr1","mpn":"mp1"}
paramsSerializer: function(params) {
return qs.stringify(params);
},
or
paramsSerializer: function(params) {
return qs.stringify(params, { arrayFormat: "brackets" });
},
or
paramsSerializer: function(params) {
return qs.stringify(params, { arrayFormat: "indices" });
},
result
0[mfr]=mfr0&0[mpn]=mpn0[mfr]=mfr1&1[mpn]=mpn1
paramsSerializer: function(params) {
return qs.stringify(params, { allowDots: true });
},
result
0.mfr=mf0&0.mpn=mpn0&1.mfr=mfr1&1.mpn=mpn1
I can create a custom paramsSerializer but I was wonder if there a way to manipulate qs or the passed parts array to get the correct query string results without having to manually create the query string and url encode the values?

How can I get the nested elements of JSON array from fetch API?

I am trying to get some data from server using fetch api in React Native. How can I get it in the JSON format with all fields showing including the nested ones?
I have already tried converting into JSON after getting data from the promise. However, the data is not properly formatted. Fetching the same data using postman gives me all the data and fields populated.
My fetch api looks like this:
fetch("https://someurl.com/apps/api/", {
method: "GET",
headers: {
api_key: "somekey",
"Content-Type": "application/json"
},
params: JSON.stringify({
device_latitude: deviceLat,
device_longitude: deviceLong
})
})
.then(response => response.json())
.then(restData => {
dispatch({
type: FETCH_REST,
payload: restData
});
})
.catch(error => {
console.error(error);
});
This is my response data from fetch api when I am doing a console log on restData in my reducer:
[
Object {
"restID":1,
"name":"Rest1",
"restLocation": null
},
Object {
"restID":2,
"name":"Rest2",
"restLocation": null
}
]
Below is the result when I am calling the endpoint using Postman.
Note: the restLocation field below has more data which is not present when using the fetch api as above:
[
{
"restID":1,
"name":"Rest1",
"restLocation":{
"id":2,
"distance":2
}
},
{
"restID":2,
"name":"Rest2",
"restLocation":{
"id":3,
"distance":1
}
}
]
GET parameters should be url encoded and put into the fetch url.
For example GET /test with postman PARAMS foo1=bar1 and foo2=bar2 should send a GET request to /test?foo1=bar1&foo2=bar2.
We can encode your params {device_latitude: deviceLat, device_longitude: deviceLong} as follows:
const url = `https://someurl.com/apps/api/?device_latitude=${deviceLat}&device_longitude=${deviceLong}`;
const fetchableUrl = encodeURI(url);
Then fetch it in the same way but drop the params because they belong in the url:
fetch(fetchableUrl, {
method: "GET",
headers: {
api_key: "somekey",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(restData => {
dispatch({
type: FETCH_REST,
payload: restData
});
})
.catch(error => {
console.error(error);
});

Getting no records when making Ajax request

I am trying to make a request to a server but im getting no records. When i run the code I am getting no error messages so I assume my code is working but when the callback function is executed on store load I just get a blank message.
var proxy = Ext.data.proxy.Ajax.create({
type:'ajax',
url:loginHostUri,
method:'POST',
headers:{
'Accept':'application/x-www-form-urlencoded'
},
extraParams:{
grant_type:'password',
username:username,
password:psswd,
client_id: consumerKey,
client_secret: consumerSecret
},
reader:{
type:'json',
root:''
}
});
var store = Ext.getStore('instance');
store.setProxy(proxy);
store.load({
callback:function(records,operation,success){
Ext.Msg.alert('INFO',records,Ext.emptyFn);
},
scope:this
});
The message is just blank but I know the Json response looks like this:
{
"":{
"id":"2332123",
"issued_at":"090342",
" instance_url":"instance",
"signature":"sig",
"access_token":"access"
}
}
define a fields or a model for the store
store.setFields({name: 'id', name: 'issued_id' ...});(put this before store.load())
Try that and console.log(records) under callback and reply back what you get...

How to use api attribute on proxy

I would like to know how to use the api attribute of a proxy in ST2
For now, I have this in my proxy configuration:
api: {
create : App.urls.create_object,
read : App.urls.load_object,
update : App.urls.update_object,
destroy : App.urls.destroy_object
}
But then, I don't know how to use it.
For instance, when I wanted to create a new object, I created an Ext.Ajax.request with these parameters :
url: App.urls.create_object,
params: {
'object': object
},
But now, how could I do the same with the api attribute ?
Could you help ?
Assuming you have a model like this:
Ext.define('User', {
fields: ['name', 'email'],
proxy: {
type: 'ajax',
api: {
create: 'my_create_url',
read: 'my_read_url',
update: 'my_update_url',
destroy: 'my_destroy_url'
}
}
});
create
var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed#sencha.com'});
user.save(); // will POST to the create url
update
var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed#sencha.com'});
user.save({
success: function(user) {
user.set('name', 'Robert Dougan');
user.save(); // will PUT update URL
}
});
read
Using a store:
var store = Ext.create('Ext.data.Store', {
model: 'User'
});
store.load(); // will GET to read URL
Using the model:
// will GET the read URL with the specified ID.
User.load(12, {
success: function(user) {
console.log(user);
}
});
destroy
var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed#sencha.com'});
user.save({
success: function(user) {
user.destroy(); // will DELETE destroy URL
}
});
There is more information about this on the Rest proxy in the Sencha Docs: http://docs.sencha.com/touch/2-0/#!/api/Ext.data.proxy.Rest
sync
You can also use the store sync method to batch create/update/destroy all the records in your store.
var store = Ext.create('Ext.data.Store', {
model: 'User'
});
store.add({ name: 'Robert Dougan', email: 'rob#sencha.com' });
store.sync(); // will batch update all the needed records