MailParser-mit returns undefined for attachments result - async-await

I am parsing email using mailparser-mit npm module. Below is the code.
const MailParser = require('mailparser-mit').MailParser;
const getAttachments = async(fullEmailBody) => {
try {
const mailparser = new MailParser();
mailparser.on('end', async function (mail_object) {
attachments = mail_object.attachments; // extract attachment from email
return attachments // attachment is present, I can console.log it as well but when i return it, it is not present at the caller
});
mailparser.write(fullEmailBody);
mailparser.end();
} catch (err) {
logger.error('Error:::::' + JSON.stringify(err));
}
}
let result = getAttachments(emailBody);
console.log("Result", result); // undefined
How can I get the results ?
I have tried using await at saveAttachmentToCos but still it is undefined

Related

Vonage browser to browser audio call return some error

I am using Laravel, and trying add browser to browser audio calling. I am using Vonage (Tookbox) API for this, but I am getting some error.
here is my code:
async function audioCall() {
var publisher;
var targetElement = 'publisher';
var pubOptions = {publishAudio:true, publishVideo:false};
publisher = OT.initPublisher(targetElement, pubOptions, function(error) {
if (error) {
alert("The client cannot publish.");
} else {
console.log('Publisher initialized.');
}
});
// Setting an audio source to a new MediaStreamTrack
const stream = await OT.getUserMedia({
videoSource: null
});
const [audioSource] = stream.getAudioTracks();
publisher.setAudioSource(audioSource).then(() => console.log('Audio source updated'));
// Cycling through microphone inputs
let audioInputs;
let currentIndex = 0;
OT.getDevices((err, devices) => {
audioInputs = devices.filter((device) => device.kind === 'audioInput');
// Find the right starting index for cycleMicrophone
audioInputs.forEach((device, idx) => {
if (device.label === publisher.getAudioSource().label) {
currentIndex = idx;
}
});
});
const cycleMicrophone = () => {
currentIndex += 1;
let deviceId = audioInputs[currentIndex % audioInputs.length].deviceId;
publisher.setAudioSource(deviceId);
};
}
This code return an error on console:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
I believe the issue is that you have
device.kind === 'audioInput'
and I'm pretty sure device.kind comes out like 'audioinput' (all lowercase).
examples:
https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/kind
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices#examples
That would make audioInputs empty (try to console.log it to verify) and gives you the error because there is no device.
Try:
device.kind.toLowerCase() === 'audioinput'
Hope it works out.

Google Sheet Api get function returns undefined value in NestJs

I have async function getTables() which using Google Sheet API to get google spreadsheet data. But on response it returns undefined value. this.getClient() returns OAuth2Client data. Could you check my async function, maybe it is written not properly?
async getTables(): Promise<any> {
try {
const sheets = google.sheets({
version: "v4",
auth: await this.getClient()
});
const res = await sheets.spreadsheets.values.get({
spreadsheetId: "sheetId",
range: "A1:B100"
});
return res;
} catch (err) {
throw new HttpException("The API returned an error: " + err, 500);
}
This is getClient async function which authorize client.
async getClient(): Promise<OAuth2Client> {
if (!this.oAuth2Client) {
return await this.authorize();
}
return this.oAuth2Client;
}
private async authorize() {
const credentials = {
access_token: this.auth.access_token,
refresh_token: null
};
this.oAuth2Client = new google.auth.OAuth2(this.CLIENT_ID, this.clientSecret, this.redirectUrl);
this.oAuth2Client.setCredentials(credentials);
return this.oAuth2Client;
}
It was my mistake, I just updated the version of Google API and everything is work, it returns array of data.

Async Lambda function returning null on calling DynamoDB

I am new to async functions and promises. I have written a Lambda function which queries a DynamoDB table and returns the result. The code is executing inside the callback success block and I am able to see the response in the log from the console.log(res) line. However the Lambda response is always showing as null, i.e. the response object below is not returned at all. I was able to make this work using a Synchronous Lambda function using a callback to return the data. Can you please suggest what I may be doing incorrectly.
const doc = require('dynamodb-doc');
var dynamodbclient;
const tablename = process.env.TABLE_NAME;
exports.handler = async(event) => {
if (!dynamodbclient) {
dynamodbclient = new doc.DynamoDB();
}
let id = event.params.id;
let queryparams = {
TableName: 'table-name',
Key: { id: id }
};[![enter image description here][1]][1]
var getItemsCallback = (err, res) => {
console.log('inside');
if (err) {
}
else {
console.log('success');
console.log(res);
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
}
};
var item = await dynamodbclient.getItem(queryparams, getItemsCallback).promise();
};
Your callback is still executing after the promise resolves, so the lambda will terminate and your callback will not finish.
Try:
try {
const item = await dynamodbclient.getItem(queryparams).promise();
} catch (err) {}
console.log('success');
console.log(item);
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;

mocha stub using sinon in node.js

I would like to know if I am missing anything with regard to sinon.js I have tried using sinon.stub().returns and yields but am unable to get the result. Any pointers would be helpful
I have a module which calls another module that returns the value from the DB
var users = require('/users');
module.exports.getProfileImage = function (req, res) {
var profile = {};
else {
users.findOne("email", req.session.user.email, function (err, user) {
if (err) {
res.status(400).send();
}
else if (!user) {
//return default image
}
else if (user) {
//Do some other logic here
}
});
};
I am using mocha as the testing framework and am also using sinon. The problem that I am facing is when i create a stub of users.findOne to return a value the control does not come to my else if (user) condition.
my unit test case is as follows
describe("Return image of user",function(){
var validRequest = null;
validRequest={
session:{
user:{
email:'testUser#test.com',
role:'Hiring Company'
}
}
};
it("Should return an image from the file if the user is present in db",function(done){
var findOneUserResponse ={
companyName:"xyz",
email:"xyz#abc.com"
};
var findOne = sinon.stub(mongoose.Model, "findOne");
findOne.callsArgWith(1,null,findOneUserResponse);
user.getProfileImage(validRequest,response);
var actualImage = response._getData();
findOne.restore();
done();
};
};
So I went through the sinon.js documentation http://sinonjs.org/docs/ and came across what I was missing
describe("Return image of user",function(){
var validRequest = null;
validRequest={
session:{
user:{
email:'testUser#test.com',
role:'Hiring Company'
}
}
};
it("Should return an image from the file if the user is present in db",function(done){
var findOneUserResponse ={
companyName:"xyz",
email:"xyz#abc.com"
};
var findOne = sinon.stub(mongoose.Model, "findOne",function(err,callback){
callback(null,findOneUserResponse);
)};
user.getProfileImage(validRequest,response);
var actualImage = response._getData();
findOne.restore();
done();
};
};

fetch returning promise rather than value

Hopefully the code below communicates the problem clearly. The issue is that in the module which uses the get method of fetchData, the value being returned is the actual Promise, rather than the JSON as desired. Any thoughts on this?
// fetchData.js module
var _ = require('lodash');
function get() {
var endpoint1 = `/endpoint1`;
var endpoint2 = `/endpoint2`;
return fetch(endpoint1)
.then((endpoint1Response) => {
return endpoint1Response.json()
.then((endpoint1JSON) => {
return fetch(endpoint2)
.then((endpoint2Response) => {
return endpoint2Response.json()
.then((endpoint2JSON) => {
var data = _.merge({}, {json1: endpoint1JSON}, {json2: endpoint2JSON});
console.log('data in fetch', data); // this logs the json
return data;
});
});
});
});
}
exports.get = get;
// module which uses get method of fetchData get
var fetchData = require('fetchData');
var data = fetchData.get();
console.log('returned from fetchData', data); // this logs a Promise
Yes, that's exactly what's supposed to happen. The whole point of promises is that their result value is not immediately available and that doesn't change just because you're obtaining one from a separate module.
You can access the value like this:
var fetchData = require('fetchData');
fetchData.get().then(data =>
console.log('returned from fetchData', data);
);
Also note that you are using promises in a non-idiomatic way and creating a "tower of doom." This is much easier on the eyes and accomplishes the same thing:
function fetchJson(endpoint) {
return fetch(endpoint)
.then(endpointResponse => endpointResponse.json());
}
function get() {
var endpoint1 = `/endpoint1`;
var endpoint2 = `/endpoint2`;
return Promise.all([fetchJson(endpoint1), fetchJson(endpoint2)])
.then(responses => {
var data = { json1: responses[0], json2: responses[1] };
console.log('data in fetch', data); // this logs the json
return data;
});
}
Edit I haven't used async/await in JavaScript, but to answer your question, I presume this would work:
async function fetchJson(endpoint) {
var res = await fetch(endpoint);
return res.json();
}
async function get() {
var endpoint1 = `/endpoint1`;
var endpoint2 = `/endpoint2`;
var data = {
json1: await fetchJson(endpoint1),
json2: await fetchJson(endpoint2)
};
console.log('data in fetch', data); // this logs the json
return data;
}
// module which uses get method of fetchData get
async function main() {
var fetchData = require('fetchData');
var data = await fetchData.get();
console.log('returned from fetchData', data);
}
return main();

Resources