How to invoke a function in index.js written in Node.js

Viewed 1592

I'm new to NodeJS and this might be a very basic question but I would appreciate if you can assist me here.

Following is my index.js file:-

'use-strict';

const { myauth } = require('./src/authorizer');

let response;

exports.handler = (event, context, callback) => {
    logger.info('hello....function invoked');
    try {
        logger.info(event);
        const resp = myauth(event, context, callback, logger);
        response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    data: resp
                })
         }
    } catch (err) {
        logger.error('handler func', err);
        response = {
            'statusCode': 500,
            'body': JSON.stringify({
                message: err,
                data: false
            })
        }
    }
    return response;
}

Package.json:-

    {
  "name": "authorizer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^13.13.5"
  },
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^6.1.4"
  }
}

When I execute the command like npm start, it does not invoke the logic written inside function in Index.js file.

Please let me know how to execute this function. Thanks

1 Answers

im not sure what you mean with 'invoke', i presume you want to assign the returned function result at your variable. To do this, you can auto-invoke your function with this javascript sintax.

exports.handler = ((event, context, callback) => {
    logger.info('hello....function invoked');
    try {
        logger.info(event);
        const resp = myauth(event, context, callback, logger);
        response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    data: resp
                })
         }
    } catch (err) {
        logger.error('handler func', err);
        response = {
            'statusCode': 500,
            'body': JSON.stringify({
                message: err,
                data: false
            })
        }
    }
    return response;
})();

let me know. Thanks!

Related