Javascript promises fetching json data - javascript

I am trying to learn promises in javascript and I came across this short video tutorial, there is a complete code from it on plunker.
What I wonder about in this code is in this line in promises.js file:
return $.get('tweets.json?id=' + profile.id);
First of all, why do we even need to pass any parameters there, since there is no profile.id field in tweets.json file, and when removing it I get the same results. If there was that field in tweets.json how would we achieve to get only tweets from the users that we pass with get request?
I have tried something like this but it doesn't work:
In promises.json I have changed the get request to:
return $.get('tweets.json?profile=' + profile.id);
And have added a new field to the tweets.json file, but only to the first tweet:
{
"id": 1,
"profile": 12302151,
"tweet": "OMG, worst day ever, my BF #BobbyBoo dumped me",
"usersMentioned": [
{
"id": 10,
"username": "BobbyBoo"
}
]
},
I was then expecting that I will only get that one tweet for that user, but I am still getting the whole list

Related

How to turn a json string into a properly beautified string to be used in email using a Logic App

Logic App
"Send_an_email_(V2)": {
"inputs": {
"body": {
"Body": "<p><br></p>\n<pre><code>Message 1<br>\n<br>\n#{variables('Message1')}<br>\n<br>\nMessage 2<br>\n<br>\n#{variables('Message2')}</code></pre>\n<pre><code><br>\n<br>\n<br>\n<br>\n</code></pre>",
"Importance": "Normal",
"Subject": "Test",
"To": "test#test.com"
}
This is how it looks like in the email. I know the Message 2 has it already nicely formatted but I would want both to look the same.
Any ideas are appreciated.
After reproducing issue from my side, I got the expected results by taking Parse Json Action after initialize variable action.
As shown in below images i have taken initialize variable actions and send email.
With out parse Json action I got below output in email.
As shown in below image in Parse Json action take Content as Message 1 from dynamic content .
Schema :
{
"Request_Date": "2023-07-18",
"Number_of_Adults": "5",
"Number_of_Children": "1",
"Total_Cost": "690"
}
Then in Send Email action in body take your required data from dynamic content of parse Json 1 as shown in below image.
Then the logic App ran successfully and email got received with expected output format.
Reference MS document for parse Json.
replace(replace(replace(variables('Message1'),',',',<br> '),'{','{<br> '),'}','<br>}')

Creating a new Phabricator task with javascript

I am trying to connect to Phabricator conduit API and create a task via a javascript bonded to a google sheet.
The Conduit API Docs linked here doesn't really explain as much. I have seen better API documentations!
Below is what I have in mind but this is a cURL and I have no idea how to make it Javascript or wither this would work or not? I appreciate the help
curl https://secure.phabricator.com/api/maniphest.edit \
-d api.token=api-token \
-d param= [
{
"type": "title",
"value": "A value from a cell on the googlesheet"
},
{
"type": "description",
"value": "A value from a cell on the googlesheet"
},
{
"type": "subscribers.add",
"value": "A value from a cell on the googlesheet"
}
] \
Generally speaking the steps are:
First, generate an API token in:
https://phabricator.yourdomain.com/settings/user/username/page/apitokens/
where phabricator.yourdomain.com must be changed by the subdomain you have Phabricator installed and username must be changed by your administration user name.
Then, let's say you have installed Phabricator in phabricator.yourdomain.com, you can request the API methods with URLs of the following type
https://phabricator.yourdomain.com/api/method_name?parameter1=value1&parameter2=value2...
where method_name must be replaced by the descriptor of a real method from this catalog:
https://secure.phabricator.com/conduit/
For example, if you want to read the contents of task number 125, with a generated API token of value api-svhcp2a3qmgkkjfa5f6sh7cm4joz, use the method maniphest.info to complete a URL like this:
http://phabricator.yourdomain.com/api/maniphest.info?api.token=api-svhcp2a3qmgkkjfa5f6sh7cm4joz&task_id=125&output=json
This URL can be directly tested in your preferred browser to obtain a JSON response with the information about task number 125 (make sure that task ID exists). Firefox will even show the returned JSON in a human-readable fashion.
These working URLs can be then inserted in Javascript as
window.location.href=http://phabricator.yourdomain.com/api/maniphest.info?api.token=api-svhcp2a3qmgkkjfa5f6sh7cm4joz&task_id=125&output=json
or as an asynchronous Ajax call.
I had a similar problem as you (I used HTTParty with Ruby).
To solve it I used the following body (using your example):
"transactions[0][type]=title&transactions[0][value][0]=A value from a cell on the googlesheet&transactions[1][type]=description&transactions[1][value]=A value from a cell on the googlesheet&transactions[2][type]=subscribers.add&transactions[2][value][0]=A value from a cell on the googlesheet"

I have some raw JSON stored in a variable and just want to post it to an API

I have been traversing through Stackoverflow and everywhere else on the web to try and find a solution to my issue..
I am working in Javascript and attempting to POST a small section of JSON to an endpoint in the API i know is working (I have completes the GET and POST manually in Postman)
Here is my issue..
I want dont really want to do the "GET" in my programme I just want to either reference the file or even just store it in a little variable.
So for example I have in my code:
var OauthUpload = {
"objects": [
{
"name": "api",
"serviceID": 16,
"properties": {}
}
],
"version": "integration",
"environment": "redshift"
}
Then I am trying to reference this in the JS function:
function ApiPostOauth (port) {
$.post(OauthUpload, "http://docker.dc.test.com:" + getActualPort(port) + "/rest/v1/oauth/import", runner);
}
But I am having no joy! I have seen a few different silutions but none seem to fit for me.
Basically I want a way to just:
Reference my own JSON as a variable and then insert tht so my function "ApiPostOauth" has that inserted before it runs?
Thanks guys
Steve
I have put together an example for your use. When executing this code, the server will return the same object it is sent. So the 'OauthUpload` object is sent as the request body and the server returns the exact same object. Note: if you don't see output in the output panel when running the sample I will need to restart the server (leave a comment). This is here to demonstrate:
[EDIT] - after re-reading your question, it appears you would like to pass the 'OauthUpload` object into the function. I've updated the example.
You have a mistake in your call to jQuery post() method. As shown in the comments, the first two arguments are reversed in the call to post().
Since you didn't pick up on that, I decided to provide an example using your code. Since I don't have your server, I stood up a server for this example. So the URL and port will be different, but the AJAX call will be the same.
Please pay close attention to the OauthUpload object. Notice the property names are no longer surrounded by ". I removed these quotes because they seemed to be causing you confusion about JavaScript objects and JSON strings (there is no such thing as a JSON Object regardless of what you read on the web - JSON is a string format).
Next, look at the differences between the call made to $.post() in my example and your code. You will see the URL comes first in that call.
let url = "//SimpleCORSEnabledServer--randycasburn.repl.co/rest/v1/oauth/import";
let OauthUpload = {
objects: [{
name: "api",
serviceID: 16,
properties: {}
}],
version: "integration",
environment: "redshift"
}
ApiPostOauth(OauthUpload);
function ApiPostOauth(data) {
$.post(url, data, runner)
}
function runner(data) {
document.querySelector('pre').textContent = JSON.stringify(data, null, 2);
}
<pre></pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Required JSON file not returning all properties every time

I have an API in a Node.js which requires a JSON file, and on some requests maps in content from it. Simple enough, and works perfectly for the first request.
On subsequent requests one of the properties is left off. This is obviously a stripped down version of the code, but is all I'm doing to get the content.
Essentially my JSON looks like:
{"sections": {
"city": {
"title": "Seattle",
"info": "some info",
"tips": [ "tip 1", "tip 2" ]
}
}
}
and I require it:
var Content = require("content");
// some code
return req.status(200).json({ data: data, content: Content.sections.city });
The first request returns the whole content object. Every request after that returns only title and info, but not tips.
Edit -- I'm a dummy. In the //some code section, I work with the tips and eventually call delete on this version of the object. Apparently passing by reference still hasn't sunken in.

JSON Response from web service - best practices question

I'm writing a simple web service that return a JSON response. It'll be heavily used, so I want to try and make the JSON response as small as possible for performance reasons. I'm on the fence over a design decision; penny for your thoughts!
My JSON response from the server looks like this:
{
"customers":
[
{
"id": "337",
"key": "APIfe45904c"
},
{
"id": "338",
"key": "somethingDifferent"
},
{
"id": "339",
"key": "APIfe45904c"
},
{
"id": "340",
"key": "APIfe45904c"
}
]
}
The APIfe45904c here is used in about 60-70% of the records, so I could also modify the the JSON response to remove the repeated information and add a default_key i.e. if there's no key specified, the client should assume the default_key like this:
{
"default_key": "APIfe45904c",
"customers":
[
{
"id": "337"
},
{
"id": "338",
"key": "somethingDifferent"
},
{
"id": "339"
},
{
"id": "340"
}
]
}
No client is using the web service yet, so this wouldn't break anything. Is this good practice? It works, and makes for a small JSON response, but I'm conflicted. I like the KISS principle for developers using the service, but I also want as small a JSON response as possible.
I was tempted to replace customers with c, id with i and key with k to aid reducing the file size, but I figured this will be a problem if I want to get other clients to start using it. Should I drop the idea of default_key for the same reason?
Each JSON response will likely be no more 200 lines of id/key pairs, so I don't need to incorporate pagination, etc.
I would keep it simple as you say, and then use gzip to compress it. It should compress very well as it is repetitive, and remains convenient for programmers.
See here for pointers in outputting gzip headers for AJAX: Is gzip encoding compatible with JSON?
Unless you have very special performance needs, I would always choose clarity over brevity. Especially for an API that is going to be used by many developers.
You should use the consistent format where each record has an id and a key field. What you lose in bandwidth you gain from not having to pre-process the JSON on the client-side.
I tend to analyze my JSON data structure like you but in the end it isn't worth the tiny bit of space you save. Your JSON data structure looks good... have you seen Twitter's JSON data structure? Now that is ugly.
I would go with the default key idea, but I wouldn't go as far as shortening the attribute names since that can be confusing. Perhaps you can take an argument from the web service call (from query string) that specifies whether or not the client desires to have shortened attribute names.

Categories