Amazon Web Services

node.js로 MySQL 조회 Lambda 함수 만들기

주말만기다려·2019년 9월 21일·조회 5,595

1. 개요


2. 작업

2.1. 작업할 로컬 디렉토리 생성

2.2. 로컬 디렉토리에서 필요 모듈 다운로드

우선 npm init 실행한 후 필요한 정보를 입력한다.

그러면 package.json이 생성된다.

이어서 mysql 모듈을 받는다.

$ npm install --save mysql
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN recent-tech-note@1.0.0 No description
npm WARN recent-tech-note@1.0.0 No repository field.

+ mysql@2.17.1
added 11 packages from 15 contributors and audited 13 packages in 0.747s
found 0 vulnerabilities

이번엔 async 모듈을 받는다.

$ npm install --save async
npm WARN recent-tech-note@1.0.0 No description
npm WARN recent-tech-note@1.0.0 No repository field.

+ async@3.1.0
added 1 package from 1 contributor and audited 14 packages in 0.583s
found 0 vulnerabilities

2.3. js 파일 생성

파일명과 Lambda 함수의 hander 이름은 같아야 한다.

예를 들어 username.js 라면 handler 이름은 username.hander임.

var BreakException = {};
var mysql = require('mysql');
var async = require('async');

var conn  = mysql.createPool({
    host     : 'xxxx.rds.amazonaws.com',
    user     : 'aaaa',
    password : 'bbbb',
    port     : '3306',
    database : 'cccc'
});

exports.handler = function(event, context, callback){
    async.waterfall([
        function (cb) {
            conn.query(
                'SELECT name, dept FROM content WHERE ... ORDER BY ... desc LIMIT 30',
                function(err, rows, fields) {
                    if (!err) {
                        cb(null, rows);
                    } else {
                        console.log('Error while performing Query.', err);
                        cb(500);
                    }
                }
            );
        }],
        function (err, result) {
            if (!err) {
                if (result.length > 0) {
                    var res = [];

                    try {
                        result.forEach(function(value, index) {
                            var temp = {};
                            temp.name = value.name;
                            temp.dept = value.dept;
                            res.push(temp);
                        });
                    } catch (e) {
                        if (e !== BreakException) throw e;
                    }
                    context.succeed(res);
                } else {
                    context.succeed('');
                }
            } else {
                if (err === 400) {
                    context.fail('Bad Request: You submitted invalid input');
                } else {
                    context.fail('Internal Error: Internal Error');
                }
            }
        }
    );
};

2.4. zip 파일 패키징

로컬 디렉토리 상에서 zip -r myfunction.zip ./ 처럼 압축한 후 업로드한다. 

댓글 0

로그인 후 댓글을 남길 수 있습니다.

아직 댓글이 없습니다.