Categories
Node.js Tips

Node.js Tips — Mail, Mocha Tests, S3 and JSON

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

‘UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block’ Error in Express Apps

We’ve to handle all promise errors manually in our Express apps.

For instance, we should write:

router.get("/fetch-email", authCheck, async (req, res, next) => {
  try {
    const emailFetch = await gmaiLHelper.getEmails(req.user.id, '/messages', req.user.accessToken)
    emailFetch = emailFetch.data
    res.send(emailFetch);
  } catch (err) {
    next(err);
  }
})

In our async route handler function, we have a catch block to catch errors.

Then we call next to call our error handling middleware.

The error handler middleware should be added after the routes so that next will call it.

Sort Sequelize.js Query by Date

We can sort a Sequelie query by date by adding an order property to the object we pass into findAll .

For instance, we can write:

Post.findAll({ limit: 50, order: '"updatedAt" DESC' })

Then we sort the updateAt column in descending order.

Sending an Email to Multiple Recipients with nodemailer

We can send an email to multiple recipients with nodemailer .

To do that, we can set the to property to an array.

For instance, we can write:

const mailList = [
  'foo@bar.com',
  'baz@bar.com',
  'qux@bar.com',
];

const msg = {
  from: "from@bar.com",
  subject: "Hello",
  text: "Hello",
  cc: "cc@bar.com",
  to: mailList
}

smtpTransport.sendMail(msg, (err) => {
  if (err) {
    return console.log(err);
  }
});

We just set to to our mailList array and send the message with sendMail .

Also, we can pass in a comma-separated string to do the same thing.

For instance, we can write:

const mailList = [
    'foo@bar.com',
    'baz@bar.com',
    'qux@bar.com',
  ]
  .join(',');
const msg = {
  from: "from@bar.com",
  subject: "Hello",
  text: "Hello",
  cc: "cc@bar.com",
  to: mailList
}
smtpTransport.sendMail(msg, (err) => {
  if (err) {
    return console.log(err);
  }
});

We called join to join the email address by commas.

Then the rest is the same.

Socket.io custom client ID

We can generate a custom ID for a client with socket.io.

We create our own generateId method to do so.

For instance, we can write:

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);

io.engine.generateId = (req) => {
  return 1
}

io.on('connection', (socket) => {
  console.log(socket.id);
})

We add the generateId method, then we can access the returned result with socket.id .

We can replace 1 with our own auto-generated ID.

Expect Mocha to Fail a Test

We can expect Mocha to fail a test with assert.fail .

For instance, we can write:

it("should fail", () => {
  assert.fail("actual", "expected", "Error message");
});

We pass in the actual result, expected result, and error message if something isn’t expected.

Wait for All Images to load with Puppeteer Then Take Screenshot

We can call goto with the waitUntil option.

For instance, we can write:

await page.goto('https://www.example.com/', {"waitUntil" : "networkidle0" });

'networkidle0' means navigation is considered finished when there are no more than 0 network connections for at least 500 ms.

There’s also 'networkidle2' which means no more than 2 network connections for at least 500 ms.

Then we can call page.screenshot to take the screenshot after this line.

Parse Stream to Object with S3 Download

If we have a download from S3, we can parse it to an object with data.Body.toString() .

For example, we can write:

const options = {
  BucketName: 'mybucket',
  ObjectName: 'path/to/my.json',
  ResponseContentType: 'application/json'
};

s3.GetObject(options, (err, data) => {
  const fileContents = data.Body.toString();
  const json = JSON.parse(fileContents);
  console.log(json);
});

We pass in the bucket, pathname, and response data type.

We use s3.GetObject to do the download with the given options.

Since we have JSON, we can convert it to a string with data.Body.toString() .

Then we can use JSON.parse to parse it to an object.

Conclusion

We can convert an item downloaded from S3 into a string.

We’ve to handle errors in Express route handlers ourselves.

Also, we can send email to multiple recipients with nodemailer.

We can sort by date with Sequelize queries.

With socket.io, we can generate our own IDs.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *