Node.js: Lambda で MariaDB のデータを作成 (Create)

フォルダー構造

```text
$ tree -a
.
├── .env
├── function_update.sh
├── index.js
└── test_local.js
```

```js:maria_create/index.js
// ---------------------------------------------------------------
//	maria_create/index.js
//
//					Jun/07/2020
//
// ---------------------------------------------------------------
var mysql = require('mysql2/promise')
// ---------------------------------------------------------------
function dict_append_proc (dict_aa,id_in,name_in,population_in,date_mod_in)
{
	var unit_aa = {}
	unit_aa['name'] = name_in
	unit_aa['population'] = population_in
	unit_aa['date_mod'] = date_mod_in

	dict_aa[id_in] = unit_aa

	return	dict_aa
}

// ---------------------------------------------------------------
function data_prepare_proc ()
{
	var dict_aa = new Object ()

	dict_aa = dict_append_proc (dict_aa,'t3321','岡山',128763,'1950-10-23')
	dict_aa = dict_append_proc (dict_aa,'t3322','倉敷',832567,'1950-7-15')
	dict_aa = dict_append_proc (dict_aa,'t3323','津山',753241,'1950-1-2')
	dict_aa = dict_append_proc (dict_aa,'t3324','玉野',318642,'1950-6-22')
	dict_aa = dict_append_proc (dict_aa,'t3325','笠岡',769358,'1950-8-14')
	dict_aa = dict_append_proc (dict_aa,'t3326','井原',865792,'1950-9-12')
	dict_aa = dict_append_proc (dict_aa,'t3327','総社',438251,'1950-3-21')
	dict_aa = dict_append_proc (dict_aa,'t3328','高梁',352486,'1950-8-26')
	dict_aa = dict_append_proc (dict_aa,'t3329','新見',695182,'1950-11-2')
	

	return	dict_aa
}

// ---------------------------------------------------------------
async function main()
{
	const dict_aa = data_prepare_proc ()

	const host = `${process.env.host}`
	const user = `${process.env.user}`
	const password = `${process.env.password}`
	const data_base = `${process.env.data_base}`

	console.error("host = " + host)
	console.error("user = " + user)
	console.error("password = " + password)
	console.error("data_base = " + data_base)

	try {
	var conn = await mysql.createConnection ({
		host: host,
		user: user,
		password: password,
		database: data_base
		})

	console.error("*** maria_create *** before drop ***")
	const sql_str_drop = 'drop table if exists cities'
	await conn.execute(sql_str_drop)
	console.error("*** maria_create *** after drop ***")

	var sql_str_create = 'create table cities '
	sql_str_create += '(id varchar(10), name varchar(20),'
	sql_str_create += ' population int, date_mod date)'
	await conn.execute(sql_str_create)
	console.error("*** maria_create *** after create ***")

	for (var key in dict_aa)
	{
	console.error("*** key = " + key)
	var sql_str = "insert into cities "
	sql_str += "(id,name,population,date_mod) values ("

	const str_data = "'" + key + "','" + dict_aa[key].name + "',"
		+ dict_aa[key].population + ",'" + dict_aa[key].date_mod + "')"

	sql_str += str_data
	await conn.execute(sql_str)
	}

	} catch (ee) {
		console.log(ee)
		console.error(ee)
		return ''
	} finally {
		if (conn && conn.connection) {
		conn.end()
		console.error("*** maria_create *** conn.end() ***")
		}
	}

}

// ---------------------------------------------------------------
console.log ("*** 開始 ***")
exports.handler = async (event) => {
	console.error("***** start maria_create PM 15:58 ***")
	var rvalue = {}
	rvalue['message'] = 'Hello from maria_create'

	await main()

	const response = {
		statusCode: 200,
		body: JSON.stringify(rvalue),
		}

	console.error("***** end maria_create ***")
	return response
	}
//
// ---------------------------------------------------------------
```

```js:maria_create/test_local.js
#! /usr/bin/node
// ---------------------------------------------------------------
//	test_local.js
//
//					Jun/07/2020
//
// ---------------------------------------------------------------
var maria_create = require('./')
// ---------------------------------------------------------------
console.error ("*** 開始 *** test_local.js ***")

const event = {
}

rvalue = maria_create.handler(event)
console.log(rvalue)

console.error ("*** 終了 *** test_local.js ***")
// ---------------------------------------------------------------
```

実行スクリプト

```bash
export NODE_PATH=/usr/lib/node_modules
node -r dotenv/config ./test_local.js
```

AWS のプログラムを更新するスクリプト

```bash:function_update.sh
FUNCTION='maria_create'
ZIP_FILE=$FUNCTION".zip"
#
rm -f *.zip
#
zip -r $ZIP_FILE index.js
#
#
aws lambda update-function-code \
	--function-name $FUNCTION \
	--zip-file fileb://$ZIP_FILE
#
```

AWS のプログラム
![maria_create_jun08.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/54bbbca0-b9e0-b8b4-ede6-93f9050d68e9.png)

AWS で実行するにはレイアーと環境変数の設定が必要

レイアー
![aws_layer_jun08.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/ce85ed21-e54c-c182-9750-73d5057b7055.png)

環境変数
![aws_environment_jun08.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/3bca5a45-52a4-73a3-e956-cd2fecbe8c8e.png)

AWS のプログラムを cli で実行する方法

```bash:cli_exec.sh
#
aws lambda invoke --invocation-type Event \
    --function-name maria_create --region ap-northeast-1 \
    --payload '{}' \
 outputfile.txt
```

実行結果

```text
$ ./cli_exec.sh 
{
    "StatusCode": 202
}
```