how to hit a specific end point using json server - javascript

I have set up json-server using a react app and I had a quick question about end points
this is some of my data:
{
"products": [
{
"name": "football",
"id": "SPO-001",
"category": "sport",
"price": "40",
"coupons": ["daw124qdw", "a1212cxn"]
},
{
"name": "cricket bat",
"id": "SPO-002",
"category": "sport",
"price": "80"
}
]
}
and it all works fine when i do something like this:
axios.get('http://localhost:3004/products').then(({ data }) => {
// do something with data
})
and I know I can do: http://localhost:3004/products/SPO-001 which returns me the id for that. but how can I just return the coupons entry for that specific id? is that a possible endpoint?
I tried axios.get('http://localhost:3004/products/SPO-001/coupons') but I just got an empty object. any ideas?

You have 2 options:
1st
axios.get('http://localhost:3004/products')
.then(res => this.setState({product: res.data.productID.coupon})) // not sure how you want to use your response, this is just an example
2nd create your endpoint for each product, something like http://localhost:3004/:productID/coupon and then "hit" that endpoint with your axios get request, e.g. axios.get('http://localhost:3004/23/coupon').then(res => res.data)
I would have to say the 2nd option would be more robust.

Related

React. Streaming JSON file

I don't have any backend logic and database. For data I just use a json file of humans.
Here it is:
[
{
"id": 0,
"name": "Andrew"
},
{
"id": 1,
"name": "Daniel"
},
{
"id": 2,
"name": "John"
},
{
"id": 3,
"name": "Frank"
}
]
Can I somehow stream this JSON file in React (i.e. on client side) to, for example, retrieve only the first two notes and return the array? I tried FS module but it only works for SSR. Or there's no way I can runtime stream it getting desired data? I just don't wanna return the whole array since I'm trying to imitate a backend database

How to navigate to the last child of a hierarchical data stored in SQL database based on the JSON passed in the request body in nodeJS?

I have a need to get the last child of a hierarchy based on the JSON data passed from the request body.
The request body looks like this:
{
"hierarchy": [
{
"id": 1,
"name": "A",
"level": 0,
"labels": [
"grandparent",
"parent",
"child"
],
"categories": [
{
"id": 2,
"name": "B",
"level": 1,
"action": "kill",
"categories": [
{
"id": 3,
"name": "C",
"level": 2,
"action": "kill",
"categories": []
}
]
}
],
"action": "kill"
}
]
}
The data will be stored in the SQL database like this:
Based on the data sent from the req body, I need to navigate to the last child in the database , in this case: C and then delete them.
Currently Im using this:
const killfamily = async (id, transaction, header = {}) => {
//need recursive method here
await family.destroy({ where: { parent_id: id }, transaction: transaction });
const result = await family.destroy({ where: { fid: id }, transaction: transaction });
return result;
Current approach is not working as im trying to delete the parent first. I want to achieve this using recursive method i.e Go to the inner most/ last child and perform destroy on it.
Any help is appreciated. Thank you

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

Rally: Fields from multiple tables

I am using the Rally WSAPI 2.0p5 with and the JSON return
I am looking to get fields from multiple tables in a single response. Is this possible? For example I am trying to get the User Story and also get the Iteration.State in the same data response. I know it is possible to do client side and if that is the only way. Can someone provide and example how I handle the async response to build the table (array).
Simply add State to the list of attributes included in your fetch. Rally's WSAPI will populate the value for sub objects even if the main type being queried does not have that field.
launch: function() {
var userStories = Ext.create('Rally.data.WsapiDataStore', {
model: 'HierarchicalRequirement',
fetch: ['Iteration', 'State'],
autoLoad: true,
filters: [
{
property: 'Iteration.State',
value: 'Accepted'
}
],
limit: 10000,
listeners: { load: this._onDataLoaded, scope: this }
});
}
As a follow up for my original question. I recently came across the alpha release of the Batch Query WSAPI in Rally's WSAPI documentation. I would suggest the usage of the Batch Query to retrieve multiple Object Models in a single response.
As an example to get User Stories and get the Iteration Status in a single query.
{
"stories" : "/HierarchicalRequirement?fetch=Name,Iteration,State&query=(Iteration.State = Accepted)"
}
The result is something that is more usable and doesn't require multiple queries to the server. i.e.
"Results": [{
"_rallyAPIMajor": "1",
"_rallyAPIMinor": "40",
"_ref": "https://rally1.rallydev.com/slm/webservice/x/hierarchicalrequirement/xxxxxxxx.js",
"_objectVersion": "17",
"_refObjectName": "<user role> I would like <feature> for <benifit>",
"Name": "As a <user role> I would like <feature> for <benifit>",
"Iteration": {
"_rallyAPIMajor": "1",
"_rallyAPIMinor": "40",
"_ref": "https://rally1.rallydev.com/slm/webservice/x/iteration/xxxxxxxx.js",
"_objectVersion": "4",
"_refObjectName": "Sprint #",
"Name": "Sprint #",
"State": "Accepted",
"_type": "Iteration"
},
"Project": {
"_rallyAPIMajor": "1",
"_rallyAPIMinor": "40",
"_ref": "https://rally1.rallydev.com/slm/webservice/x/project/xxxxxxxx.js",
"_refObjectName": "Name",
"_type": "Project"
},
"_type": "HierarchicalRequirement"
},
....
]
For more information and a few resources:
https://rally1.rallydev.com/slm/doc/webservice/index.jsp?version=1.40
https://rally1.rallydev.com/slm/doc/webservice/batch.jsp
https://rally1.rallydev.com/slm/doc/webservice/BatchScratchPad.jsp

How to access the data from return JSON from webservice in javascript or jquery

Hi i have a return json data which returns the webservice
The structure of webservice is like that:
jsonp1332655154667({"products": [{"uid": "37",
"samsid": "hjk",
"name": "Science%20Essentials%2010%20AC%20edn",
"shortname": "scienceessentials10",
"description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"generated": "3/25/2012%205:59:19%20AM",
"Description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"PublishingCompany": "Macmillan%20Australia",
"Service": "OneStopScience",
"Service": "OneStopDigital",
"Icon": "http://curriculumplatform.s3.amazonaws.com/prod/icons/brain48.png",
"Country": "Australia",
"Shortname": "scienceessentials10",
"MarketingSite": "http%3a%2f%2fwww.macmillan.com.au%2fsecondary%2fonix%2fall%2f6F597241EFC0E43DCA257791001CAFC0%3fopen%26div%3dSecondary%26cat%3dScience%253EAustralian%252BCurriculum%26template%3ddomSecondary%26ed%3dsite%2fseced31.nsf",
"Skin": "OneStopScience%20Green"},
"tag":"s_science"'
"tag":"s_maths"'
"tag":"s_arts",
{"uid": "5",}]})
I have three "tag" elements. but when we access the products.tag it gives always last element like:s_arts.
Is there any way to find out all the elements eg:s_science,s_maths,s_arts.
please help.
It is invalid json, your tag should be:
...,
"tag": ["s_science", "s_maths", "s_arts" ],
...
Then product.tag would be an array that you could access successfully
Regards
If you have multiple keys in the same object, you're going to get undefined behaviour. Only one will be preserved, and since pairs are not ordered, you can't guarantee which you'll get.
In short: the webservice is returning you faulty data. If multiple tags are expected, the service should return an array of values in the tag attribute:
...
"tag":["s_science", "s_maths", "s_arts"],
...
You need to send the tags as an array:
jsonp1332655154667({"products": [{"uid": "37",
"samsid": "hjk",
"name": "Science%20Essentials%2010%20AC%20edn",
"shortname": "scienceessentials10",
"description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"generated": "3/25/2012%205:59:19%20AM",
"Description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"PublishingCompany": "Macmillan%20Australia",
"Service": "OneStopScience",
"Service": "OneStopDigital",
"Icon": "http://curriculumplatform.s3.amazonaws.com/prod/icons/brain48.png",
"Country": "Australia",
"Shortname": "scienceessentials10",
"MarketingSite": "http%3a%2f%2fwww.macmillan.com.au%2fsecondary%2fonix%2fall%2f6F597241EFC0E43DCA257791001CAFC0%3fopen%26div%3dSecondary%26cat%3dScience%253EAustralian%252BCurriculum%26template%3ddomSecondary%26ed%3dsite%2fseced31.nsf",
"Skin": "OneStopScience%20Green"},
"tags": [
"s_science"'
"s_maths"'
"s_arts"
],
{"uid": "5",}]})
Then you reference them as data.tags[0], data.tags[1], data.tags[2].
if your response is in this format
YourResponse = {
"products" : [
{"uid" :"5", ......., "whtever":"someval"},
{"uid" :"6", ......., "whtever":"someval1"}
]
};
you can use this
$(YourResponse).each(
function(objName, objValue) {
console.log(objName); // wil get object name like uid, whtever
console.log(objValue); // wil get object's value
});
so to get Tags you will have to take Tuan's suggestion; send them in array

Categories