建立簡單的 CRUD 操作

使用無伺服器框架建立簡單的 CRUD 操作

全域性安裝無伺服器框架

npm install serverless -g

建立簡單的 Lambda 服務

serverless create --template aws-nodejs --path myService

轉到它應包含的 myService 目錄

  1. serverless.yml
  2. handler.js
  3. event.json

所有無伺服器服務配置均由 serverless.yml 管理。
更改其內容以定義 CRUD 服務。

示例 serverless.yml 檔案

service: serverless-crud

provider:
  name: aws
  runtime: nodejs4.3
  region: us-east-1
  stage: dev
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:us-east-1:*:*"

functions:
  create:
    handler: handler.create
    events:
      - http:
          path: todos
          method: post
          cors: true
  readAll:
    handler: handler.readAll
    events:
      - http:
          path: todos
          method: get
          cors: true
  readOne:
    handler: handler.readOne
    events:
      - http:
          path: todos/{id}
          method: get
          cors: true
  update:
    handler: handler.update
    events:
      - http:
          path: todos/{id}
          method: put
          cors: true
  delete:
    handler: handler.delete
    events:
      - http:
          path: todos/{id}
          method: delete
          cors: true

resources:
  Resources:
    TodosDynamoDbTable:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          -
            AttributeName: id
            AttributeType: S
        KeySchema:
          -
            AttributeName: id
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: 'todos' 

這個檔案定義

  1. Lambda 函式程式語言
  2. Lambda 函式執行策略
  3. Dynamodb 表建立及其策略
  4. HTTP 端點(API 閘道器端點)

然後你必須在 handler.js 檔案中定義 lambda 函式(例如 node.js),你可以定義它。

'use strict';

const todosCreate = require('./todos-create.js');
const todosReadAll = require('./todos-read-all.js');
const todosReadOne = require('./todos-read-one.js');
const todosUpdate = require('./todos-update.js');
const todosDelete = require('./todos-delete.js');

module.exports.create = (event, context, callback) => {
  todosCreate(event, (error, result) => {
    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin" : "*"
      },
      body: JSON.stringify(result),
    };

    context.succeed(response);
  });
};

module.exports.readAll = (event, context, callback) => {
  todosReadAll(event, (error, result) => {
    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin" : "*"
      },
      body: JSON.stringify(result),
    };

    context.succeed(response);
  });
};

module.exports.readOne = (event, context, callback) => {
  todosReadOne(event, (error, result) => {
    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin" : "*"
      },
      body: JSON.stringify(result),
    };

    context.succeed(response);
  });
};

module.exports.update = (event, context, callback) => {
  todosUpdate(event, (error, result) => {
    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin" : "*"
      },
      body: JSON.stringify(result),
    };

    context.succeed(response);
  });
};

module.exports.delete = (event, context, callback) => {
  todosDelete(event, (error, result) => {
    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin" : "*"
      },
      body: JSON.stringify(result),
    };

    context.succeed(response);
  });
};

然後,你必須建立新檔案以定義 CRUD 函式
建立這些檔案

  1. 待辦事項,create.js
  2. 待辦事項讀 -all.js
  3. 待辦事項 - 讀 one.js
  4. 待辦事項,update.js
  5. 待辦事項,delete.js

然後在每個檔案中定義這些函式。

對於 todos-create.js

'use strict';

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const uuid = require('uuid');

module.exports = (event, callback) => {
  const data = JSON.parse(event.body);

  data.id = uuid.v1();
  data.updatedAt = new Date().getTime();

  const params = {
    TableName: 'todos',
    Item: data
  };

  return dynamoDb.put(params, (error, data) => {
    if (error) {
      callback(error);
    }
    callback(error, params.Item);
  });
};

對於 todos-read-all.js

    'use strict';
    
    const AWS = require('aws-sdk');
    const dynamoDb = new AWS.DynamoDB.DocumentClient();
    
    module.exports = (event, callback) => {
      const params = {
        TableName: 'todos',
      };
    
      return dynamoDb.scan(params, (error, data) => {
        if (error) {
          callback(error);
        }
        callback(error, data.Items);
      });
    };

For todos-read-one.js <br>

'use strict';

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();

module.exports = (event, callback) => {
  const params = {
    TableName: 'todos',
    Key: {
      id: event.pathParameters.id
    }
  };

  return dynamoDb.get(params, (error, data) => {
    if (error) {
      callback(error);
    }
    callback(error, data.Item);
  });
};

對於 todos-update.js

'use strict';

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();

module.exports = (event, callback) => {
  const data = JSON.parse(event.body);

  data.id = event.pathParameters.id;
  data.updatedAt = new Date().getTime();

  const params = {
    TableName : 'todos',
    Item: data
  };

  return dynamoDb.put(params, (error, data) => {
    if (error) {
      callback(error);
    }
    callback(error, params.Item);
  });
};

對於 todos-delete.js

'use strict';

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();

module.exports = (event, callback) => {
  const params = {
    TableName : 'todos',
    Key: {
      id: event.pathParameters.id
    }
  };

  return dynamoDb.delete(params, (error, data) => {
    if (error) {
      callback(error);
    }
    callback(error, params.Key);
  });
};

要執行這些應用程式,你需要安裝 npm 依賴項

  1. npm init npm 初始化
  2. npm install aws-sdk --save 安裝 aws-sdk
  3. npm install uuid --save

部署
現在你可以部署這些專案
cd myService 驗證你是否在專案目錄中,然後你可以部署你的程式碼

serverless deploy

使用端點
如果你已成功部署,則在控制檯中檢視 api 閘道器埠名稱。

測試建立端點

curl -X POST https://XXXX.execute-api.region.amazonaws.com/dev/todos --data '{ "body" : "Learn Serverless" }'

測試讀取終點(全部讀取)

curl https://XXXX.execute-api.region.amazonaws.com/dev/todos

測試讀取終點(讀一)

curl https://XXXX.execute-api.region.amazonaws.com/dev/todos/<id>

測試更新終點

curl -X PUT https://XXXX.execute-api.region.amazonaws.com/dev/todos/<id> --data '{ "body" : "Understand Serverless" }'

測試刪除終點

`curl -X DELETE https://XXXX.execute-api.region.amazonaws.com/dev/todos/<id`>