Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //----------------------------------------
  2. //handler.js
  3. //----------------------------------------
  4. import mysql from 'mysql2/promise';
  5. import db_config from './db_config.json';
  6. import { success, failure } from './libs/response-lib';
  7.  
  8. export const main = (event, context, callback) => {
  9.     console.log('start');
  10.  
  11.     const pool  = mysql.createPool({
  12.                     host     : db_config.dbendpoint,
  13.                     user     : db_config.dbuser,
  14.                     password : db_config.dbpwd,
  15.                     database : db_config.dbname
  16.                 });
  17.     const locationid = event.locationid;
  18.     const parameter = event.parameter;
  19.     //proof both event.* and db_config.* are working
  20.     console.log(parameter + " and " + db_config.dbport);
  21.    
  22.     //prevent timeout from waiting event loop
  23.     context.callbackWaitsForEmptyEventLoop = false;
  24.    
  25.     const resPromise = pool.getConnection()
  26.         .then((connection) => {
  27.             console.log("got connection");
  28.             // Use the connection
  29.             const res  = connection.execute(
  30.             'SELECT * FROM radar_pubweb r WHERE r.locationid = ? AND r.parameter = ?',
  31.             [locationid, parameter]);
  32.            
  33.             // And done with the connection.
  34.             connection.release();
  35.             return res;
  36.         }).then((result) => {
  37.             console.log(result);
  38.             return result;
  39.         }).catch((err) => {    
  40.             // And done with the connection.
  41.             console.log('error : ', err);
  42.             throw err;
  43.         })
  44.        
  45.     console.log("end");
  46.     return resPromise;
  47. }
  48.  
  49. //----------------------------------------
  50. //response-lib.js
  51. //----------------------------------------
  52. function buildResponse(statusCode, body) {
  53.   return {
  54.     statusCode,
  55.     headers: {
  56.       'Access-Control-Allow-Origin': '*',
  57.       'Access-Control-Allow-Credentials': true,
  58.     },
  59.     body: JSON.stringify(body),
  60.   };
  61. }
  62. export function internalError(err) {
  63.   return buildResponse(500, { message: err.message, type: 'internalError' });
  64. }
  65.  
  66. export function success(body) {
  67.   return buildResponse(200, body);
  68. }
  69.  
  70. export function failure(body) {
  71.   return buildResponse(500, body);
  72. }
  73.  
  74. export function notFound(obj) {
  75.   return buildResponse(404, { message: `The object ${obj} is not found`, type: 'notFound' });
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement