0
2

More than 1 year has passed since last update.

Vue 3.0 composition apiによるAWS サーバーレス開発  シリーズ② サーバー側環境設定

Last updated at Posted at 2022-07-13

サーバー:Nodejs 16.0 + サーバーレスフレームワーク + serverless-layersプラグイン + sequelize

##アクセス構成
AWS Api -> Lambda(sequelize) -> DBアクセス

DBの構築 Test用テーブル追加

CREATE TABLE IF NOT EXISTS `member` (
   `id`        INTEGER      NOT NULL  AUTO_INCREMENT,
   `first_name`      VARCHAR(255) NOT NULL,
   `last_name`      VARCHAR(255) NOT NULL,
   `age`      INTEGER,
   `createdAt` DATETIME     ,
   `updatedAt` DATETIME     ,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB;
insert into member(first_name,last_name,age) value("fname1","lname2",33);

AWS 設定

AWS-cliをインストール(aws --versionでインストールしたaws-cliのバージョン情報を確認できる。)
C:\Users\ユーザー名.aws\credentials を開き、以下の項目を追加

 [default]
aws_access_key_id=自分のキーを設定
aws_secret_access_key=自分のキーを設定
role_arn=自分のロールARN
source_profile=default

sls deployを実行できるように設定

cmdでコマンドプロンプトを開き

set AWS_PROFILE=default

開発用Nodejsのパッケージインストール(インストール済みパス)

Nodejsをインストール

サーバーレスフレームワークでの開発

npm install -g serverless
sls create -t aws-nodejs -p server-app(プロジェクト名)
cd server-app

serverless-layersプラグインを追加

npm init
npm install --save serverless
npx sls plugin install --name serverless-layers

必要なパッケージインストール 今回主にsequelizeを利用する(利点:Data Injectionを防げる, 楽観的排他が容易に)

npm install --save sequelize-cli -g(一回限りのInstall)
npm install --save sequelize
npm install --save mysql2

sequelize設定

今回例:メーカー側の受注一覧

コマンドライン上で以下のコマンドを(Windows:コマンドプロンプト)
sequelize init
sequelize model:generate --name member --attributes id:integer,first_name:text,last_name:text,age:integer
/models/member.jsを開き、以下のように修正
idの修正
freezeTableName:trueを追加(追加箇所は下記引用を参照)

修正後
--member.js

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class member extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  member.init({
    id: {type:DataTypes.INTEGER,primaryKey: true,autoIncrement: true},
    first_name: DataTypes.TEXT,
    last_name: DataTypes.TEXT,
    age: DataTypes.INTEGER
  }, {
    sequelize,
    modelName: 'member',
    freezeTableName:true
  });
  return member;
};

/config/config.jsonを開き、自分の環境を設定 

"development": {
    "username": "自分のユーザー名",
    "password": "自分のパスワード",
    "database": "自分のDB",
    "host": "自分のホスト",
    "dialect": "mysql",
    "connectTimeout ": 30000

handler.js を下記のように書き変え

'use strict';
const { resolve } = require("path");

let member_json = "";
let db = require('./models/');

const show_member_list = () =>{
  return  new Promise((resolve)=> {
    db.member.findAll().then(member=>{
      member_json = member;
      resolve(console.log("showed table t_order_management"));
    });
  });
}

module.exports.hello = async (event) => {
  try{
    await show_member_list();
  }catch(e){
    console.log("message sending error e=",e);
  }

  return {
    statusCode: 200,
    body: JSON.stringify(member_json)
  }


  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // return { message: 'Go Serverless v1.0! Your function executed successfully!', event };
};

serverless.yml以下のように設定する

# Welcome to Serverless!
#
# This file is the main config file for your service.
# It's very minimal at this point and uses default values.
# You can always add more config options for more control.
# We've included some commented out config examples here.
# Just uncomment any of them to get that config option.
#
# For full config options, check the docs:
#    docs.serverless.com
#
# Happy Coding!

service: test
# app and org for use with dashboard.serverless.com
#app: your-app-name
#org: your-org-name

# You can pin your service to only deploy with a specific Serverless version
# Check out our docs for more details
frameworkVersion: '3'

provider:
  name: aws
  runtime: nodejs16.x

# you can overwrite defaults here
  stage: dev
#  region: us-east-1
  region: ap-northeast-1
  role: 自分のロール

  vpc:
    securityGroupIds:
      - 自分がセキュリティグループID
    subnetIds:
      -自分のsubnetID
      -自分のsubnetID

# you can add statements to the Lambda function's IAM Role here
#  iam:
#    role:
#      statements:
#        - Effect: "Allow"
#          Action:
#            - "s3:ListBucket"
#          Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ]  }
#        - Effect: "Allow"
#          Action:
#            - "s3:PutObject"
#          Resource:
#            Fn::Join:
#              - ""
#              - - "arn:aws:s3:::"
#                - "Ref" : "ServerlessDeploymentBucket"
#                - "/*"

# you can define service wide environment variables here
#  environment:
#    variable1: value1

# you can add packaging information here
#package:
#  patterns:
#    - '!exclude-me.js'
#    - '!exclude-me-dir/**'
#    - include-me.js
#    - include-me-dir/**

functions:
  member_list:
    handler: handler.hello
#    The following are a few example events you can configure
#    NOTE: Please make sure to change your handler code to work with those events
#    Check the event documentation for details
    events:
      - httpApi:
          path: /get_member
          method: get
custom:
  serverless-layers:
    layersDeploymentBucket: AWS上の自分のバケット
#      - websocket: $connect
#      - s3: ${env:BUCKET}
#      - schedule: rate(10 minutes)
#      - sns: greeter-topic
#      - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000
#      - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx
#      - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx
#      - iot:
#          sql: "SELECT * FROM 'some_topic'"
#      - cloudwatchEvent:
#          event:
#            source:
#              - "aws.ec2"
#            detail-type:
#              - "EC2 Instance State-change Notification"
#            detail:
#              state:
#                - pending
#      - cloudwatchLog: '/aws/lambda/hello'
#      - cognitoUserPool:
#          pool: MyUserPool
#          trigger: PreSignUp
#      - alb:
#          listenerArn: arn:aws:elasticloadbalancing:us-east-1:XXXXXX:listener/app/my-load-balancer/50dc6c495c0c9188/
#          priority: 1
#          conditions:
#            host: example.com
#            path: /hello

#    Define function environment variables here
#    environment:
#      variable2: value2

# you can add CloudFormation resource templates here
#resources:
#  Resources:
#    NewResource:
#      Type: AWS::S3::Bucket
#      Properties:
#        BucketName: my-new-bucket
#  Outputs:
#     NewOutput:
#       Description: "Description for the output"
#       Value: "Some output value"

plugins:
  - serverless-layers

deploy 一回目 layerまで作られる

sls deploy

deploy 二回目以降 sls deploy function -f lambdaファンクション名

sls deploy function -f member_list

結果のリンクをChromeでアクセスすれば、memberテーブルの一覧が表示される。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2