使用AWS和NodeJS进行无服务器环境的构建步骤四
首先
这次我们将在上次的基础上继续开发DELETE(删除特定用户)、GET(获取所有用户)、PATCH(更新特定用户)功能。
删除(针对目标用户的删除)
根据指定的id,将删除目标用户。
创建和配置Lambda函数
源泉
'use strict';
const AWS = require('aws-sdk');
const myRegion = "us-east-2";
AWS.config.update({ region: myRegion});
exports.handler = async (event, context) => {
const documentClient = new AWS.DynamoDB.DocumentClient({ region: myRegion});
let responseBody = "";
let statusCode = 0;
const { id } = event.pathParameters;
const params = {
TableName: "Users",
Key: {
id: id
}
};
try {
const data = await documentClient.delete(params).promise();
responseBody = JSON.stringify(data);
statusCode = 204;
} catch (err) {
responseBody = `Unable to delete user: ${err}`;
statusCode = 403;
}
const response = {
statusCode: statusCode,
headers: {
"Content-Type": "application/json"
},
body: responseBody
};
return response;
};
创建和设置方法 (CJ-Language Model)
执行测试并确认
获取(获取所有用户)
当执行GET方法时,确保所有用户都被获取。
创建和设置Lambda函数
'use strict';
const AWS = require('aws-sdk');
const myRegion = "us-east-2";
AWS.config.update({ region: myRegion});
exports.handler = async (event, context) => {
const documentClient = new AWS.DynamoDB.DocumentClient({ region: myRegion});
let responseBody = "";
let statusCode = 0;
const params = {
TableName: "Users"
};
try {
const data = await documentClient.scan(params).promise();
responseBody = JSON.stringify(data);
statusCode = 200;
} catch (err) {
responseBody = `Unable to get users: ${err}`;
statusCode = 403;
}
const response = {
statusCode: statusCode,
headers: {
"Content-Type": "application/json"
},
body: responseBody
};
return response;
};
创建和设置方法
进行考试并确认
进行补丁(更新目标用户)
当执行PATCH方法时,确保目标用户已被更新。
创建和配置Lambda函数
/**
* 対象のユーザ情報を更新する
*/
'use strict';
const AWS = require('aws-sdk');
const myRegion = "us-east-2";
AWS.config.update({ region: myRegion});
exports.handler = async (event, context) => {
const documentClient = new AWS.DynamoDB.DocumentClient({ region: myRegion});
let responseBody = "";
let statusCode = 0;
const { id, firstname, lastname } = JSON.parse(event.body);
const params = {
TableName: "Users",
Key: {
id: id
},
UpdateExpression: "set firstname = :fname, lastname = :lname",
ExpressionAttributeValues: {
":fname": firstname,
":lname": lastname
},
ReturnValues: "UPDATED_NEW"
};
try {
const data = await documentClient.update(params).promise();
responseBody = JSON.stringify(data);
statusCode = 204;
} catch (err) {
responseBody = `Unable to patch user ${err}`;
statusCode = 403;
}
const response = {
statusCode: statusCode,
headers: {
"Content-Type": "application/json"
},
body: responseBody
};
return response;
};
创建和设置方法
进行测试并确认
{
"id": "02",
"firstname": "update_firstname",
"lastname": "update_lastname"
}
结束
我已经使用无服务器REST API创建了CRUD环境的配置。
下一步,我打算结合API网关+Lambda(NodeJS)+S3。