创建简单的 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`>