HapiJS JSON Formatting - javascript

I'm writing a small CRUD app and I'd like to have some formatting on the JSON responses I'm getting (mostly for ease of reading).
Is there a setting I'm missing?

I wouldn't recommend forcing your API consumers to have a pretty JSON format. If you want to see the JSON in a nice format I'd recommend installing the Chrome JSON Formatter Plugin or using something like Postman.

After digging some more through the API documentation (RTFM, right?), I found the actual setting that enables the behavior I was looking for.
server.connection({
port: 3000,
routes: {
json: {
space: 4
}
}
});
While the Chrome extension is a good answer, this will work with other browsers.

If you want to apply the pretty JSON format dynamically, based on a query param or header, you can use the following code (tested in v20.2.2):
srv.ext('onPreResponse', (req : Request, h : ResponseToolkit) => {
const { response } : any = req;
if (req.query._pretty) {
response.spaces(2).takeover();
}
return h.continue;
});
If you call whatever method with a paramlike _prettyfor instance:
curl -XGET http://localhost:3003/api/foo?_pretty=1
You'll get a response like:
{
"id": 1253,
"name": "Everything OK"
}
But if you don't add the param:
curl -XGET http://localhost:3003/api/foo
Then the JSON output is collapsed:
{"id":1253,"name":"Everything OK"}
The name of the parameter could be whatever thing that won't be used in your app, so add a prefix like _ or whatever else, you can also use a specific header instead a query param if you prefer.

Related

How to interpret extended json data

Description of the problem
I will not write any codes as much of my problem is something linked with the knowledge to interpret some data. I am doing a project and had to use a nonsql database to store data the sampled information from a microcontroller. The chosen db was mondodb. I wrote all the code that stores the info and now i want to exhibit the date on a html page. The problem is that when i do the request using restapi to the mongodb, the json that was stored there comes in the extened json format, i.e.:
"_id": {
"$oid": "6230d05dcf81542c5aabc30b"
},
"sensor": {
"$numberDouble": "1"
}
But it should have come as the data is stored in the db:
"{
_id": "6230d05dcf81542c5aabc30b",
"sensor": 1.0
}
As you can see, the the json comes with extra information linked to the type of the variable that is stored. But i don't really know how to use that information in javascript. I would just read it for example as json.sensor.$numberDouble if i wanted to get the information about the sensor instead of json.sensor if the json was in the normal way. I don't see much of an use to the extended version. Is something i am doing wrong?
Make sure, that you Parse API response, like-
response.json()
It looks like you're getting back an EJSON response. If you want to send back standard JSON response then that should be set as the Content-Type on the server response.
function(req, res) {
data = { ... }; // Your data here
res.setHeader("Content-Type", "application/json");
res.setBody(JSON.stringify(data));
}
If you don't have control over the server side, then convert the EJSON back to plain JSON using the meteor EJSON library.

Express req.param deprecated syntax

On Node.js I am getting this error, in some JavaScript code:
express deprecated req.param(name): Use req.params, req.body,
Here is the relevant code:
response.render('pages/' + displayPage, {
MYVAR: request.param('MYVAR'),
MYVAR2: request.MYVAR,
MYVAR3: request.params.MYVAR
});
In other words this line is deprecated
MYVAR: request.param('MYVAR'),
But, it does the job (at least for now).
And the other type of syntax I tried, by guessing or by finding on the net after searching, all failed.
Including these lines:
MYVAR2: request.MYVAR,
MYVAR3: request.params.MYVAR
and a few more options that would be pointless to list here.
So the question is: what is the right syntax to use?
Here is some more information, added by editing the post after reading some comments:
I send the request parameters this way:
https://myapp.herokuapp.com/branch?MYVAR=64.39
Inside index.js the code processing the /branch is:
response.render('pages/' + displayPage, {
MYVAR: request.param('MYVAR'),
MYVAR2: request.params.MYVAR,
MYVAR3: request.params['MYVAR']
});
Inside the branch.ejs file I have placed the following in order to see what I am getting:
<body bgcolor=#221122E>
<b>MYVAR=<%= MYVAR %></b><br/>
<b>MYVAR2=<%= MYVAR2 %></b><br/>
<b>MYVAR3=<%= MYVAR3 %></b><br/>
......
And finally this is what I can see in the browser, displayed by branch.ejs:
MYVAR=64.39
MYVAR2=
MYVAR3=
It shows that the variable passed with the old syntax arrives as expected, but not the other ones.
Which of the variants is needed depends on how you send request parameters:
You need to use req.query.MYVAR if your request uses the GET method with parameters after the ? like /path?MYVAR=123.
If you have your parameters in the path (e.g. /path/:MYVAR in your express get call), req.params.MYVAR is correct.
If you use POST or PUT, you need to use req.body.MYVAR, because of the data is transferred in the body. Since express doesn't parse the body , you need to include and use an additional package like body-parser
Instead of using:
request.param('MYVAR')
You are supposed to use:
request.params['MYVAR']
// Or this:
request.params.MYVAR

Accessing JSON data when response contains both JSON data and text

Initially the content from the server was JSON data.And I was able to access the data perfectly.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Now the response from the server has been changed to json data + text data.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Properties for service:
=======================
ServiceEndpoint: https://somedomain:1200/web/Servlet/SOAP/Services
Certificates: false
DocumentName: note.pdf
So whether changing the content-type to application-text and using split method is the only way we can solve this or Is there any better approach?
As mentioned in the comments, mixing JSON and pure text data is wrong (as it defeats the advantage of using standardized data format) and should be avoided. Maybe that is some kind of debug log that was accidentally included in the production code?
If not, you should read just the first line of response and parse it as JSON data, ignoring the rest, hoping for no more changes in response structure ;)
You really should overthink your API design.
What about adding the text part as part of your JSON?
{
... // your JSON properties here
"serviceProperties": { // properties for service
"ServiceEndpoint": "https://somedomain:1200/web/Servlet/SOAP/Services",
"Certificates": false,
"DocumentName": "note.pdf"
}
}

Reddit Api Error trying to get reddit self text via snoocore node.js

I'm tryng to get the self.text on a post and using this route:
reddit('/r/Denmark/comments/2jc5yk/how_to_live_in_denmark.json').listing({
context: 1,
limit: 10,
sort: 'hot',
})
.then(function(result) {
console.log(result);
});
I have also tried using .get(), without .json and without /how_to_live_in_denmark but still the same error.
When I input the route in my browser, I get the desired JSON.
The error i get:
Uncaught Error: Invalid path provided! This endpoint does not exist. Make sure that your call matches the routes that are defined in Reddit's API documentation
What am i doing wrong?
Update: 2015-02-09
Snoocore now accepts URLS's with embedded values and does not require placeholders if you do not wish to use them.
I'm the creator of this API wrapper. I'll have to monitor StackOverflow a little bit more to catch these quicker. Feel free to open new issues on GitHub as well when you get stuck on something for a quicker response!
It looks like you are trying to call this endpoint:
GET /r/[subreddit]/comments/article
Basically anything that is in brackets is optional in Snoocore, and anything in italics is an URL parameter that you will need to define placeholders for in the call (using $parameter). More information on this can be read in the documentation (feel free to ask questions or improve upon the documentation if it isn't clear!)
So in your case, you will want to do this:
reddit('/r/$subreddit/comments/$article').get({
$subreddit: 'Denmark',
$article: '2jc5yk',
context: 1,
limit: 10,
sort: 'hot'
}).done(function(result) {
console.log(result);
});
Note that instead of defining the url parameters in the call, the are now referenced by $subreddit and $article respectivly.
Note that comments are not a listing, and therefore can't use the listings interface as you tried to do in your question.

Apache server, JSON parser

I'm looking for json parser that can be used inside httpd.conf file in combination with url rewrite:
Here is the json file for the example:
{
"employees": [
{ "emp1":"Andy" },
{ "emp2":"David" },
]
}
For example i got this url (http://someurl.com/employees/emp1/)
employees is rewrite by the apache server to employees.json
So far so good if i just want the file, But lets say i want specific item as the url(http://someurl.com/employees/emp1/) show i want emp1:
The first thing i was looking is a way to fetch the item directly from the url for example to rewrite:
http://someurl.com/employees/emp1/
To:
http://someurl.com/employees.json:emp1/ // Just an example for a possibility that there is a syntax to fetch single item directly from the url
Another thing to consider is the use of PHP/JS to process the URL than parse and return the item (emp1 value).
So the last thing i was thinking is the use of JSON parser that can work inside the apache configuration file(httpd.conf) in combination with url rewrite process.
I'd love to hear what is the best solution, Thank you all and have a nice day.

Categories

Resources