Acces JSON Object in google cloud functions - node.js

i'm trying to parse a response in a google cloud function.
The text response is:
{"data":{"Object_Create":{"id":107}}} and stored in var body.
i convert it this way:
var obj= JSON.parse(body)
Then i try to access the object:
var Object_Create= obj.data.Object_Create
and works.
The problem is when i try to get the id field with:
var id= obj.data.Object_Create.id
because it returns ReferenceError: id is not defined
I tried the same code from an online JS editor and it's working without any problems so it seems related to the cloud platform.
Did someone experienced the same problem?

There is no need to parse that response, as it is a Javascript object, which means there is no extra processing necessary.
If you do try to parse it, it should throw a syntax error
SyntaxError: Unexpected token o in JSON at position 1
you can just access it by
console.log(body.data.Object_Create.id)
I imagine you actually want to use that key however, so you could
const { Object_Create } = body.data
console.log(Object_Create.id)

Related

Body is not getting parsed in GET method

I am using mockoon for API simulation. I created 2 routes there with method GET and its body contains(responds with) JSON object. I noticed that my express app is not able to parse one of the routes. But the route that has JSON object in body which contains ARRAY is getting parsed. I tested both routes with Express(by console.log) and in chrome browser(I have JSON formatter extension) and it is behaving the same meaning response that does not contain ARRAY is not getting parsed but the response with array is getting parsed(behaving normally). Let me show the screenshots:
Express(by console.log):
With array:
Without array:
Chrome(JSON Formatter extension):
With array(extension is able to parse):
Without array(extension is not able to parse):
I tried adding Header(Content-Type: application/json) to the route in mockoon. But still, I am not aware of what is going on here. Someone please explain
The express code:
const iabs_client = await axios.get(
"http://localhost:3001/iabs-client
);
Here is the route created in Mockoon(without array inside JSON):
P.S mockoon is a program that creates endpoints in localhost, useful for API simulation when developing front-end without having backend yet
The trailing comma after "something" is not valid JSON. Edit your Mockoon body to remove the comma and it should work.

DocuSign API Javascript SDK - getDocument returns string

I am trying to call the api endpoint getDocument via Node, and am expecting a Buffer to be returned, however, it is returning a string. Even when I pass in different values for the encoding optional parameter, the data returned is always the same.
When I tested the same endpoint in C#, a MemoryStream is returned which is expected.
My code is as follows:
const document = await envelopesApi.getDocument(accountId, envelopeId, '1')
Where 1 is the documentId (page 1).
The contents of document looks like %PDF-1.5\n%ûüýþ\n%Writing objects... and so on
I am then trying to save this to a file:
fs.writeFileSync('test.pdf', Buffer.from(documentContent))
With no success. How do I get the api response and save it to a file for viewing?
Yes, this is correct, you will have to use the correct mime type for PDF (in this case) in order to show this file in the browser.
You can find a node.JS code example that shows you how to do this.
But the most important part in your case would be this line:
mimetype = "application/pdf";

NetSuite SuiteScript 2.0 How to parse content Text in suitescript

i am trying to update a vendor record status field using suitescript 2.0,passing the body in postman tool and is working fine for content JSON but the problem is when i try content as Text its getting error don't know how to read body value in suitescript 2.0.
input body from postman
sample code is
function doPut(context)
{
var obj=JSON.stringify(context.ids);-----here is the error context is empty
// tried JSON.parse also getting undefined
log.debug('str: '+obj);
return obj;
}
If you could provide the exact error message that would be helpful.
But in the mean time a few things that you should verify in your script, if you do not pass application/JSON in header, and your data is object, you need to explicitly parse it into JSON(i.e use JSON.parse() on the request-body), and your response type too should be in the same format i.e your response type should match content-type in the request.
looks like you may have the wrong Content-type. Should be Application-json. If not try Json.parse on the body if you're using text/plain. First step is to always log the context to console or run Object.keys(context) to see what's there. Also make sure doPut is exported as a function

Triggering Google Cloud function using console

I am trying to use the google cloud console to test a cloud function. Below is a snippet.
exports.requestCreated = functions.firestore
.document('users/{userId}/requests/{requestId}')
.onWrite((change, context) => {
// execute operation
});
I have tried all sorts of combination of JSON data. E.g.
{"userId":"Xl86pqOpF9T2MAn12p24OJAfYJW2","requestId":"abc1234"}
But I keep getting the following statement in logs:
Request created by {userId}
The actual userId is not being read from the JSON data in the console. Can you help?
This is not a problem with the execution of the cloud function. It's a problem with hardcoding the string.
'users/{userId}/requests/{requestId}' is a hardcoded string. Node.js will not automatically replace {userId} with the value of the variable userId.
Following this previous SO post, try something like this using template strings:
`users/${userId}/requests/${requestId}`
Please note it is surrounded by backticks (`), not single quotes (').
This assumes you already have a userId and requestId variables defined. You must restructure your cloud function like this to retrieve that data. Notice that the specific variable values must be extracted from the event variable.
Thank you, Nareddyt. The function is for Firestore, and the way it is written right now checks if a new document is created under the collection requests. I tried replacing the string as you suggested, but as you pointed out, it requires these variables to be defined. I do not quite understand how to restructure the cloud function because the syntax I have used is how event detection is suggested in the Firestore documentation. My function currently works in its entirety, but testing it is a major pain. I have to go through my mobile app and do the whole userflow to test this function. I am new to Node.js and any guidance would be appreciated.

node.js express.js Error handling in View

I am very new to node.js and express.js and in programming concepts. I already made a basic MVC modeled app on node and express.
My problem is how do you handle error, I got this following code:
exports.submitBloodRequest=function(kaiseki,resView,request){
var params = {
bloodCenterId:request.session.centerID,
bloodTypeId: request.body.bloodType,
requestQuantity:request.body.numberOfDonors
}
kaiseki.createObject('blood_center_request', params, function(err, res, body, success) {
if(success){
resView.redirect('/bloodRequest')
}else{
//WHAT TO DO HERE?
}
});
}
Kaiseki is just a middleware for parse.com, I don't know what to do if it got error. Usually I use ajaxForm.js to look for BadRequest then use javascript to display error message in my view.
I want my error to appear in the same page, where it is success, should I pass a json error to my view?
Or still use ajaxForm.js and instead of res.render or res.redirect I should use res.status(500)
Is there anyway to handle the error and showing it into the view. Without using any javascript to detect BadRequest?
And can a view have a optional variable? In my view If I didnt pass any value on it it gives me error like if i have #{variable} it asks for its value. Can it be made to be optional? Im using Jade Template
To respond to an XHR request with an error you can do something like return resView.status(500).send(err); which will send the err object back as JSON. If you want to render an HTML error page instead you can do return resView.status(500).locals({err: err}).render('/errorPage');
You didn't say which template engine you are using but most likely the #{} version will automatically escape HTML characters for you (turn < into <, etc) to avoid XSS attacks and rendering problems whereas !{} will render the contents of the variable directly without escaping, which is dangerous if the variable contains any user-generated content, but necessary if the variable has HTML you want rendered by the browser.

Resources