【发布时间】:2022-11-26 15:24:28
【问题描述】:
我正在使用 AWS 在 Nodejs 中构建 REST API。我期待邮递员的回应说 “
Your Bid Must Be Higher than ${auction.highestBid.amount}
“ 但相反,我在 Postman 上收到内部服务器错误,而 AWS Cloudwatch 上的错误如下所示: enter image description here。 但是,我在 Postman 上发送请求为: enter image description here 请帮忙!!
我期待这样的回应: 您的出价必须高于
${auction.highestBid.amount}
补丁请求正文如下所示: enter image description here 虽然创建请求看起来像: enter image description here
//placeBid.js
const AWS = require('aws-sdk');
const createError = require('http-errors');
const {getAuctionById} = require('./getAuction');
const dynamodb = new AWS.DynamoDB.DocumentClient();
async function placeBid(req) {
const { id } = req.pathParameters;
const { amount } = JSON.parse(req.body);
const auction = getAuctionById(id);
if(amount <= auction.highestBid.amount)
throw new createError.Forbidden(`Your Bid Must Be Higher than ${auction.highestBid.amount}`);
const params = {
TableName: 'AuctionsTable',
Key : {id},
UpdateExpression : 'set highestBid.amount = :amount',
ExpressionAttributeValues: {
':amount' : amount
},
ReturnValues : 'ALL_NEW'
}
let updatedAuction;
try {
const result = await dynamodb.update(params).promise();
updatedAuction = result.Attributes;
} catch (error) {
console.error(error);
throw new createError.InternalServerError(error);
}
return{
statusCode : 200,
body : JSON.stringify(updatedAuction)
}
}
module.exports.handler = placeBid;
//getAuction.js
const AWS = require('aws-sdk');
const createError = require('http-errors');
const dynamodb = new AWS.DynamoDB.DocumentClient();
module.exports.getAuctionById = async(id) => {
let auction;
try {
const result = await dynamodb.get({
TableName : 'AuctionsTable',
Key : {id}
}).promise()
auction = result.Item;
} catch (error) {
console.error(error);
throw new createError.InternalServerError(error);
}
if(!auction){
throw new createError.NotFound(`Auction with ID ${id} not found`);
}
return auction;
}
async function getAuction(req) {
const { id } = req.pathParameters;
const auction = await getAuctionById(id);
return{
statusCode : 200,
body : JSON.stringify(auction)
}
}
module.exports.handler = getAuction
【问题讨论】:
标签: node.js amazon-web-services rest aws-lambda