JSON as Javascript object in Azure http trigger function - node.js

const df = require("durable-functions");
module.exports = async function (context, req) {
const client = df.getClient(context);
context.log(`Function Name = '${req.params.functionName}'.`);
context.log(`Body = '${req.body}'.`);
const instanceId = await client.startNew(req.params.functionName, undefined, req.body);
context.log(`Started orchestration with ID = '${instanceId}'.`);
return client.createCheckStatusResponse(context.bindingData.req, instanceId);
};
I have tried to use POSTMAN or https://reqbin.com/ for testing but I always get object.
It is a simple case but I don't understand why it is not JSON object.
I read this one
TypeScript Azure Function Read Body of POST method as JSON
but it didn't help me.

Everything is fine!
It is already deserialized json object.
It looks like the normal string in a log after
JSON.stringify(req.body)
My fault was that I wrongly got it in the orchestrator function from the context.

Related

findOne function not working with condition

I am passing a string to REST API and from the auth service class I am calling the following method from the user service class
async abc(email: string): Promise<any> {
const userInDb:Users = await this.usersRepository.findOne({email});
}
but it returns an undefined object but if I try the following code:
const userInDb:Users = await this.usersRepository.findOne(email);
it works fine. I want the above code to work.
I have found the problem. My controller was sending me email in the JSON format.

How to use async json data?

I'm using node.js.
I've managed to load and parse my .json file using async.
The whole concept is very new to me, I can see my .json data in console but I'm not really sure how to actually use my data now,..
async function getJsonFile() {
let response = await fetch('example.json');
let responsejson = await response.json();
let str = JSON.stringify(responsejson);
let jsonData = JSON.parse(str);
return jsonData;
};
getJsonFile().then(console.log); // I see my .json file in console, how can I use it ?
}
I think that's the way to do it:
var json = await getJsonData();
// use it
If you are trying to use your data which is inside your json you can do this :
// Use this in an async function
const data = await getJsonFile();
// Then get value of one key
console.log(data.key); // from {key: "value"}, you'll get value
To actually use what is in the JSON you need to store it as a variable and then access it in ways that are useful to you. You can access properties of objects using property accessors.
// Save as variable
var json = await getJsonData();
// Do something with properties of data
console.log(json['key']);

How to get the query parameters in nock callback

I want to access the query parameter in nock reply callback.
The request object that is exposed contains the path that has them as a string. But I would like to access them as a map so that I will not have to deal with parsing the string
const scope = nock('http://www.google.com')
.get('/cat-poems')
.reply(function(uri, requestBody) {
console.log('path:', this.req.path)
console.log('headers:', this.req.headers)
// ...
})
I would expect the query params to be a separate map that I can access
Does anyone know of a way to achieve this?
The value of this.req inside a reply function is an instance of a ClientRequest that has been slightly modified.
Unfortunately for your use case, ClientRequest does not provide an easy way to access just the query params. But you do have access to the full path, from which you can parse the query params out.
const nock = require('nock')
const http = require('http')
const url = require('url')
const scope = nock('http://www.google.com')
.get('/cat-poems')
.query(true)
.reply(function(uri, requestBody) {
const parsed = new url.URL(this.req.path, 'http://example.com')
console.log('query params:', parsed.searchParams)
return [200, 'OK']
})
const req = http.get('http://www.google.com/cat-poems?page=12')
// output >> query params: URLSearchParams { 'page' => '12' }
The object being logged is a URLSearchParams instance.
Using the URL constructor is the preferred method over url.parse now, so I've used that for the example. Keep in mind that URL won't parse relative paths alone, it requires an origin, but since you don't care about the host in the end it can be a dummy value (hence the use of "example.com").

In lambda, Could not parse request body into json

I try to make backend with lambda.
So I make the sample of it and post the data by postman.
I select form-data and put data in key and value.
and it returns like that.
{"message": "Could not parse request body into json: Unrecognized token \'Idx\': was expecting \'null\', \'true\', \'false\' or NaN\n at [Source: [B#745d4999; line: 1, column: 5]"}
So I find the some of docs, if I use postman to test lambda, select row and post the data like
{
"key" : "params"
}
But I want to receive the data in lambda when I post the data by form-data type.
It is simple test of it
In lambda,
exports.handler = (event, context, callback) => {
// TODO implement
const Idx = event.Idx * 2;
callback(null, Idx);
};
and, when I post the data json type
and when I post the data form-data type
When using form data your event.body is not a JSON, it’s a string that you need to parse. Specifically, it’s a query string. So in your case, it is:Idx=2
What you need to do is parse it to a JSON and then operate on it.
You can use a module for that
const querystring = require('querystring');
And inside the lambda
const body = querystring.parse(event.body)
Now you can access the Idx using body[‘Idx’]
You can use typeof to differentiate if it is an object or a string like so:
if (typeof(event.body) === ‘object’)
Edit: full code
const querystring = require('querystring');
exports.handler = (event, context, callback) => {
// TODO implement
console.log(event.body);
var Idx = null;
if (typeof(event.body) === ‘object’) {
Idx = event.Idx * 2;
} else if (typeof(event.body) === ‘string’) {
Idx = querystring.parse(event.body)[‘Idx’];
}
callback(null, Idx);
};

Kong service with POST request to Lambda function and JSON payload

I'm just starting with Kong and setup a Lambda plugin on a service to try things out. The Lambda function I use had a simple method to parse the JSON body:
const getBody = (event: any): IBody => {
const body = JSON.parse(event.body)
return new Body(body)
}
So, although I was able to call the function and get a response from it, all I got was an error message similar to:
{"status":500,"message":"SyntaxError: Unexpected token u in JSON
at position 0"}
This is due the fact a Lambda request is different when invoked from the cli and when called from AWS API Gateway.
Basically event.body is only available when calling from the API Gateway, whilst when called from the cli, the correct property name is event.request_body.
So modifiying the method to the one below will allow me to receive calls both from AWS API Gateway and cli:
const getBody = (event: any): IBody => {
const body = JSON.parse(Object.is(event.request_body, undefined) ? event.body : event.request_body)
return new Body(body)
}

Resources