Handlebars and AWS Lambda example


Andres Canavesi
Sep 10, 2022
featured image
      
const handlebars = require('handlebars');
const {promises: {readFile}} = require("fs");

let templateSource;

const renderToString = async (data) => {
    if(!templateSource) templateSource = await readFile('./views/content.hbs', {encoding:'utf8', flag:'r'})
    const template = handlebars.compile(templateSource);
    return template(data);
}

let response;
let html;
const lambdaLoadedDate = new Date().toISOString();

exports.lambdaHandler = async (event, context) => {
    try {
        const now = new Date().toISOString();
        html = await renderToString({title: 'im the title', now: now, lambda_date: lambdaLoadedDate});
        response = {
            statusCode: 200,
            headers: {
                'Content-Type': 'text/html',
            },
            body: html
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};