MrJibus
MrJibus

Reputation: 113

AWS Lambda NodeJS with PG-Promise - get empty query result when calling a function from a module

This may be simple for the most of you but I have struggling on this for hours. I have an aws lambda function which execute several pgsql queries with pg-promise against a RDS pgsql database. In order to organize the code, I want to seperate some functions into modules.

I can execute and get results in the main file but when i try in another file and export it as module. I only get an empty object.

Files (truncated)

index.js

exports.handler = function (event, context, callback) {
    context.callbackWaitsForEmptyEventLoop = false;

    const db = require('./dbconfig');

    const helpers = require('./helpers');

    var userid = 1; // testing purpose

    var tagexist = helpers.tagexist

    var istagexist = tagexist(tags, userid);

    callback(null, {"message" : istagexist});
};

Expected behavior : "message" : id, actual result : "message" : {}

helpers.js

const db = require('./dbconfig');

module.exports = {

    tagexist : function (tags, uid) {
        db.oneOrNone('SELECT id FROM table_tags WHERE tag = $1 and uid = $2', [tags, uid])
        .then((id) => {
            return id;
        })
        .catch((err) => {return err;})
        .then(() => {db.$pool.end()});
    }
};

dbconf.js

const pgp = require('pg-promise')();
const dbconfig = {
    user: 'sandbox',
    host: 'host',
    database: 'sandbox',
    password: 'pass',
    port: 5432,  
}
const db = pgp(dbconfig);

module.exports = db;

Upvotes: 0

Views: 554

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

Your helper.js should look like this, Basically you need to return the promise.


const db = require('./dbconfig');

module.exports = {

    tagexist : function (tags, uid) {
        return db.oneOrNone('SELECT id FROM table_tags WHERE tag = $1 and uid = $2', [tags, uid])
        .then((id) => {
            return id;
        })
        .catch((err) => {return err;})
        .then(() => {db.$pool.end()});
    }
};

The index.js should look like this. basically you need waut for promise to resolve. Since you are already using promises so you can simplify the code by using asyn/await and not use callback.

exports.handler = async function (event) {

    const db = require('./dbconfig');

    const helpers = require('./helpers');

    var userid = 1; // testing purpose

    var tagexist = helpers.tagexist

    var istagexist = await tagexist(tags, userid);

    return {"message" : istagexist};
};

Upvotes: 1

Related Questions