I have a refreshdata() function which executes a call to get IDs of certain events:
function refreshdata()
{
$http({
url: “…/GetIDs”,
method: "POST",
data: jsonData,
dataType: "json",
timeout: 7000,
contentType: 'application/json; charset=utf-8'
}).success(function(data, status, headers, config) {
responseNew=data.d;
meetings = JSON.parse(responseNew);
console.log("Got meetings");
meetingsanddetails(meetings);
}).error(function(data, status, headers, config) {
alert("Unable to refresh data.”);
});
}
meetings is something like:
{
"Result":"success",
"Key":"12345",
"Data":[
{"ID":"GFDCV34","lastChangedDate":"2015-12-03 11:14:27"},
{"ID":"IDJHE23","lastChangedDate":"2015-12-03 15:17:47"},
{"ID":"KDJBD34","lastChangedDate":"2015-12-03 05:25:11"}
]
}
Next, I do meetingsanddetails(meetings):
res = meetings;
var i = 0;
var tmp = [];
promises = [];
res.Data.map(function (val) {
promises.push(getdetails2(val.ID).then(function (data) {
tmp = JSON.parse(data);
Object.keys(tmp.Data[0]).map(function (v, j) {
val[v] = tmp.Data[0][v];
});
}, function (error) {
console.log(error)
}));
});
$q.all(promises).then(function () {
$timeout(function () {$ionicLoading.hide()}, 500);
$window.localStorage['data'] = JSON.stringify(res);
});
res is now something like:
{
"Result": "success",
"Key": "12345",
"Data":[
{
"ID": "GFDCV34",
"name": "Name of event 1",
"date": "date of event 1",
"location": "location of event 1",
"lastChangedDate": "2015-12-03 11:14:27"
},
{
"ID": "IDJHE23",
"name": "Name of event 2",
"date": "date of event 2",
"location": "location of event 2",
"lastChangedDate": "2015-12-03 15:17:47"
},
{
"ID": "KDJBD34",
"name": "Name of event 3",
"date": "date of event 3",
"location": "location of event 3",
"lastChangedDate":"2015-12-03 05:25:11"
}
]
}
(credit to maurycy)
(Info: getdetails2(id) returns the details of an event with a given ID).
This works fine, but the getdetails2 calls take a long time to load. That is way I would like to make it work like this:
If …/GetIDs returns IDs that weren’t already in $window.localStorage['data'], they should be added with their details.
The IDs that …/GetIDs returns that were already in $window.localStorage['data’], should only be updated if the lastChangedDate of the new call is more recent.
IDs that are present in $window.localStorage['data’], but not in the new call, should be deleted.
Anyone who can point me in the right direction? I keep messing up this array hocus pocus.
First of all, don't rely on localStorage: in private mode in Safari it does not work, so you need to have some fallback to prevent errors.
What you want to achieve is a caching thing. You have two possibilities: do it on your own which would take some time and probably will have some bugs (I did it couple of times and it was not fun at all) or use ready solutions, e.g. this advanced angular-cache. It allows to choose the storage type, can be natively used with $http / $resource and allows operations with the cache such as deleting cached responses (that's what you would need to do when you get a newer timestamp). It is quite easy to use, just check the docs and examples.
Related
I have an array of objects questions.json which looks like
"id": "2",
"ques": "here is my second code ?",
"quesBrief": "I can't seem to find it too.",
"hashes": "#javascript , #goodlord",
"author": "slowdeathv123",
"dateTime": "2021-09-22 18:13:12",
"date": "2021-09-22",
"sortOrder": -99,
"code": " - utlis (folder contains GO files)\n ---sendMail.go \n--templates (folder)\n --- reset_code.html\n - main.go"
I want to add answers array of objects to it to make it a nested object and add more objects to answers array using a fetch/axios/async await request to make it like
"id": "2",
"ques": "here is my second code ?",
"quesBrief": "I can't seem to find it too.",
"hashes": "#javascript , #goodlord",
"author": "slowdeathv123",
"dateTime": "2021-09-22 18:13:12",
"date": "2021-09-22",
"sortOrder": -99,
"code": " - utlis (folder contains GO files)\n ---sendMail.go \n--templates (folder)\n --- reset_code.html\n - main.go"
"answers": [
{
"answerBrief": "Check under the bed",
"answerCode": "no code sorry",
"answerAuthor": "Sonya"
},
{
"answerBrief": "Any other random solution",
"answerCode": "no code sorry",
"answerAuthor": "ABC"
}
],
How to create a post request to add an array of objects inside an object while checking if the answers array already exists, if not create one and add objects to it?
Does this make sense?
let data = {
"id": "2",
"ques": "here is my second code ?",
"quesBrief": "I can't seem to find it too.",
"hashes": "#javascript , #goodlord",
"author": "slowdeathv123",
"dateTime": "2021-09-22 18:13:12",
"date": "2021-09-22",
"sortOrder": -99,
"code": " - utlis (folder contains GO files)\n ---sendMail.go \n--templates (folder)\n --- reset_code.html\n - main.go",
};
const newAnswer = {
"answerBrief": "Check under the bed",
"answerCode": "no code sorry",
"answerAuthor": "Sonya"
};
const answers = [...data.answers || [], newAnswer];
data = {
...data,
answers
}
If you need to add answers that comes after POST request:
fetch('your-api-url-to-add-answers', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // data with answers i think?
})
.then(res => res.json())
.then(answersData => {
const answers = [...data.answers || [], answeersData];
data = {
...data,
answers
}
});
If you need to send data with updated answers:
const answers = [...data.answers || [], answeersData];
const payload = {
...data,
answers
}
fetch('your-api-url-to-add-answers', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload) // data with answers i think?
})
.then(res => res.json())
.then(answersData => {});
But for a more accurate answer, provide a little more detail. What data needs to be sent in a post request, and what kind of response you receive from the server.
So I am reasonably new to using API's with Js but I am struggling a lot to understand how the Google Fit API works. I am attempting to add a new Workout's data to the API by adding a session and some data for the intensity (heart points) of the session. I can get the session to appear correctly but run into constant errors when I try to create a dataSource and add a point to it for the session. It would be greatly appreciated if someone could help me to fix my code to achieve this or could direct me to a more thorough example of similar code as the API docs don't seem to be too well detailed with examples etc. Thanks in advance.
Here's the 3 api calls that I have written so far, one for creating the DataSource, one for the DataPoint and one for the Session. The session works correctly and adds a session of 1 hr for the correct activity but I am unable to get any of the other API requests to work.
Data Source :
``gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {"field":[{
"format": "floatPoint",
"name": "com.google.heart_minutes"
}],
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000019",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
``
Data Point :
``
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:292824132082:op:6:1000019",
"userId": "me",
"datasetId": "1592087806561000000-1592287806561000000",
"resource": {
"minStartTimeNs": "1592087806561000000",
"maxEndTimeNs": "1592287806561000000",
"dataSourceId": "raw:com.google.heart_minutes:292824132082:op:6:1000019",
"point": [
{
"startTimeNanos": "1592087806561000000",
"endTimeNanos": "1592287806561000000",
"value": [
{
"fpVal": 89.1
}
],
"dataTypeName": "com.google.heart_minutes"
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
``
Session :
``gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": "someSessionId19",
"id": "someSessionId19",
"name": "Awesome Workout19",
"description": "A very intense workout",
"startTimeMillis": new Date().getTime() - 3600000,
"endTimeMillis": new Date().getTime(),
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": 3600000
}).then((res) => {console.log(res)});
console.log('res')
//request.execute((res) => {console.log(res);console.log('executrd')})
console.log(auth2.currentUser.get().getBasicProfile().getGivenName());
var request2 = gapi.client.fitness.users.sessions.list({
"userId":"me"
}).then((res) => {console.log(res)})
``
Error message
{message: "Unable to fetch DataSource for Dataset: raw:com.google.heart_minutes:292824132082:op:6:1000019", domain: "global", reason: "invalidArgument"}
It looks like it could be that you're trying to pass in the wrong fields for the data type: if you want to use a standard data type (like com.google.heart_minutes), you should either pass the exact fields of the standard data type (the field should be called "intensity"); or just pass the data type name, and the backend will fill them in for you.
So, if you change the data type to
"dataType": {"name": "com.google.heart_minutes"}
It should work.
Then, you need to use the data source ID returned from that request for the data points.
Awesome, so after some support in the comments I have some working code to add a new session with data from a previously defined data source using 3 API calls. The first call is to create a data source and only needs to be run once. The second and third then add a data point to a data set and creates a new session for the workout respectively. Here's the final working code:
Data Source:
/*
gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000020",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
*/
Data and Data Set:
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:108881196053:op:6:1000020",
"userId": "me",
"datasetId": z,
"resource": {
"minStartTimeNs": workoutStartTime * 1000000,
"maxEndTimeNs": workoutEndTime * 1000000,
"dataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"point": [
{
"originDataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"value": [
{
"fpVal": 8
}
],
"dataTypeName": "com.google.heart_minutes",
"endTimeNanos": workoutEndTime * 1000000,
"startTimeNanos": workoutStartTime * 1000000,
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
Session:
gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": id,
"id": id,
"name": "Morning Workout",
"description": "A very intense workout",
"startTimeMillis": workoutStartTime,
"endTimeMillis": workoutEndTime,
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": workoutEndTime - workoutStartTime
}).then((res) => {console.log(res)});
console.log('res')
When I try to parse this JSON (Discord webhook):
{
"content": "this `supports` __a__ **subset** *of* ~~markdown~~ 😃 ```js\nfunction foo(bar) {\n console.log(bar);\n}\n\nfoo(1);```",
"embed": {
"title": "title ~~(did you know you can have markdown here too?)~~",
"description": "this supports [named links](https://discordapp.com) on top of the previously shown subset of markdown. ```\nyes, even code blocks```",
"url": "https://discordapp.com",
"color": 16324973,
"timestamp": "2018-12-18T09:22:12.841Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png",
"text": "footer text"
},
"thumbnail": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"image": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"author": {
"name": "author name",
"url": "https://discordapp.com",
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"fields": [
{
"name": "🤔",
"value": "some of these properties have certain limits..."
},
{
"name": "😱",
"value": "try exceeding some of them!"
},
{
"name": "🙄",
"value": "an informative error should show up, and this view will remain as-is until all issues are fixed"
},
{
"name": "<:thonkang:219069250692841473>",
"value": "these last two",
"inline": true
},
{
"name": "<:thonkang:219069250692841473>",
"value": "are inline fields",
"inline": true
}
]
}
}
Using this code:
var parsed = JSON.parse(req.body)
I get this error:
SyntaxError: Unexpected token o in JSON at position 1
But if I use a website such as
https://jsonformatter.curiousconcept.com
To validate the JSON, it says the JSON is valid.
What is wrong here?
UPDATE
I'm using an express server to simulate discord server, so it sends web hooks to the express server instead, I get the JSON using req.body.
This happens because JSON is a global object (it's the same object where you read the method parse!), so when you invoke JSON.parse(JSON) javascript thinks you want to parse it.
The same thing doesn't happen when you pass the variable to the validator, because it will be assigned to a local variable:
let JSON = "{}";
validate(JSON);
function(x) {
JSON.parse(x); // here JSON is again your global object!
}
EDIT
According to your updated question, maybe it happens because you already use bodyParser.json() as middleware, and when you use it, req.body is already an object and you don't need to parse it again.
Trying to parsing an already parsed object will throw an error.
It would be something like without using JSONStream:
http.request(options, function(res) {
var buffers = []
res
.on('data', function(chunk) {
buffers.push(chunk)
})
.on('end', function() {
JSON.parse(Buffer.concat(buffers).toString())
})
})
For using it with JSONStream, it would be something like:
http.request(options, function(res) {
var stream = JSONStream.parse('*')
res.pipe(stream)
stream.on('data', console.log.bind(console, 'an item'))
})
(OR)
Here is the Some Steps for this issue..
You Can use lodash for resolving this.
import the lodash and call unescape().
const _ = require('lodash');
let htmlDecoder = function(encodedStr){
return _.unescape(encodedStr);
}
htmlDecoder(JSON);
I am using backbone's fetch method to retrieve a set of JSON from the server. Inside the fetch call, I have a success callback that correctly assigns attributes to a model for each object found.
var foo = assetCollection.fetch({
reset: true,
success: function(response){
var data = response.models[0].attributes.collection.items;
data.forEach(function(data){
assetCollection.add([
{src_href: data.data[0].value,
title: data.data[1].value
}
]);
});
console.log(assetCollection.models)
}
})
Right now I am working with a static set of JSON that has two objects. However, logging assetCollection.models returns three objects: the first is the initial server JSON response, while the next two are correctly parsed Backbone models.
How do I keep Backbone from adding the first object (the entire response from the server) to its set of models, and instead just add the two JSON objects that I am interested in?
The JSON object returned from the server is as follows:
{
"collection": {
"version": "1.0",
"items": [
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://cdn.images.express.co.uk/img/dynamic/36/590x/robin-williams-night-at-the-museum-498385.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Robin as Teddy Roosevelt"
}
]
},
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://b.vimeocdn.com/ts/164/830/164830426_640.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Mrs. Doubtfire"
}
]
}
]
}
}
You should modufy collection.
Probably you should change parse method:
yourCollection = Backbone.Collection.extend({
parse: function(data) {
return data.models[0].attributes.collection.items;
}
})
When you use fetch Backbone parse result and add all elements what you return in parse.
i have the following Problem. Sorry for my bad english that way.
I want to read a jsonfile and count the Number of Persons in it.
This result i will write to an variable.This variable is connected to the TileContainer. So when i write an new entry in my Json File i want that the TileContainer number is increased to.
Here my Code from my Company.json File:
{
"mitarbeiter": [
{ "Lastname": "Mustermann",
"Firstname": "Max",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "männlich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Softwareentwickler"
},
{ "Lastname": "Fischer",
"Firstname": "Elke",
"icon": "sap-icon://globe",
"adress": "Hamburg",
"geschlecht": "weiblich",
"plz": "31441",
"street": "Am Fischmarkt 12",
"jobinfo": "Verwaltungsassistentin"
},
{ "Lastname": "Mustermann",
"Firstname": "Heike",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "weiblich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Vorstandsvorsitzende"
}
]
}
on my controller.js
onInit: function() {
this.getView().addDelegate({onBeforeShow: function(evt) {
if (this.direction != "back") {
var model = new sap.ui.model.json.JSONModel();
model.loadData("JsonModels/Company.json");
alert(model.getJSON());
var XYZ;
var jsonModel =
{
"Tiles":[
{"Tile":
{ id : "idModelTile1",
title : "Mitarbeiter",
info: "Mitarbeiterdaten",
icon:"sap-icon://company-view",
activeIcon:"inbox",
number: XYZ,
appto: "idListPage"
//numberUnit: "positions"
},
}, ......
I want that the variable XYZ gets the Length Value, bevor the TileContainer is rendered. So the Number of Company-Employess is given on the Selectionscreen View.
Hope some one can help me. I make some implementations with jquery and so but nothing really work fine.
Dear,
Christian
When i add
alert(model.getProperty("/mitarbeiter/length"));
i get the alert message "undefined"...
Since the length property of an array can be read, you could simply use
var XYZ = model.getProperty("/mitarbeiter/length");
EDIT: here's a code example for the comment I gave below
onInit: function() {
jQuery.ajax({
url: "JsonModels/Company.json",
dataType: "json",
success: function(data, textStatus, jqXHR) {
var mitarbeiterCount = data.length;
var oTileModel = new sap.ui.model.json.JSONModel();
oTileModel.setData({
tiles :[{
tile : {
id : "idModelTile1",
title : "Mitarbeiter",
info : "Mitarbeiterdaten",
icon :"sap-icon://company-view",
activeIcon:"inbox",
number : mitarbeiterCount,
appto : "idListPage"
},
}]
});
sap.ui.getCore().setModel(oTileModel);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Oh no, an error occurred");
}
});
}
In your view, if you now bind your tile's number property, it should automagically work:
var oTileTemplate = new sap.m.StandardTile({
icon : "{icon}",
number : "{number}",
numberUnit: "mitarbeiter",
title : "{title}",
info : "{info}"
});
var oTileContainer = new sap.m.TileContainer().bindAggregation("tiles", "/", oTileTemplate);
//Etc...