'use strict';

const util = require('util');

const aws = require('aws-sdk');

const lambda = new aws.Lambda({ apiVersion: '2015-03-31', region: 'ap-northeast-1' });
const dynamodb = new aws.DynamoDB({ apiVersion: '2012-08-10', region: 'ap-northeast-1' });
const dynamodbClient = new aws.DynamoDB.DocumentClient({ service: dynamodb });

function loadPreference(keys) {
  return new Promise((resolve, reject) => {
    const realKeys = [];

    if (util.isString(keys)) {
      realKeys.push({ name: keys });
    } else if (util.isArray(keys)) {
      for (const keyName of keys) {
        realKeys.push({ name: keyName });
      }
    } else {
      throw new Error('Invalid keys');
    }

    const params = {
      RequestItems: {
        CodeTengu_Preference: {
          Keys: realKeys,
        },
      },
    };

    dynamodbClient.batchGet(params, (err, data) => {
      if (err) {
        console.log('FAIL');
        console.log(util.inspect(err));

        reject(err);
      } else {
        const response = {};

        for (const config of data.Responses.CodeTengu_Preference) {
          response[config.name] = config;
        }

        resolve(response);
      }
    });
  });
}

function checkHTTPStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  throw new Error(`HTTP ${response.status}`);
}

module.exports = {
  lambda,
  dynamodbClient,
  loadPreference,
  checkHTTPStatus,
};

@@ -330,16 +330,489 @@
 db %7D);%0A%0A
+function invokeLambdaFunction(funcName, payload) %7B%0A  return new Promise((resolve, reject) =%3E %7B%0A    const params = %7B%0A      FunctionName: funcName,%0A      InvocationType: 'Event', // asynchronous execution%0A      Payload: JSON.stringify(payload),%0A    %7D;%0A%0A    lambda.invoke(params, (err, data) =%3E %7B%0A      if (err) %7B%0A        console.log('FAIL', params);%0A        console.log(util.inspect(err));%0A%0A        reject(err);%0A      %7D else %7B%0A        resolve(data);%0A      %7D%0A    %7D);%0A  %7D);%0A%7D%0A%0A
 function
@@ -1861,16 +1861,40 @@
 lambda,%0A
+  invokeLambdaFunction,%0A
   dynamo

add utils.invokeLambdaFunction()