| 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | // SPDX-License-Identifier: MIT |
| 3 | |
| 4 | 'use strict'; |
| 5 | |
| 6 | // Require |
| 7 | const express = require('express') |
| 8 | const AWS = require('aws-sdk') |
| 9 | |
| 10 | // Constants |
| 11 | const PORT = 8080 |
| 12 | const DynamoDBTable = process.env.DynamoDBTable |
| 13 | const dynamodbDocumentClient = new AWS.DynamoDB.DocumentClient() |
| 14 | const app = express() |
| 15 | |
| 16 | // Express app to ue JSON |
| 17 | app.use(express.json()) |
| 18 | |
| 19 | // PUT Route |
| 20 | app.put('/foodstore/foods/:foodId', (req, res, next) => { |
| 21 | |
| 22 | var foodId = req.params.foodId |
| 23 | var elData = req.body |
| 24 | |
| 25 | if( 'foodId' in elData && elData.foodId != foodId ){ |
| 26 | return next({ status: 400, message: "foodId in path is different from foodId in payload" }) |
| 27 | } |
| 28 | |
| 29 | elData.foodId = foodId |
| 30 | var params = { |
| 31 | Item: elData, |
| 32 | TableName: DynamoDBTable |
| 33 | } |
| 34 | |
| 35 | dynamodbDocumentClient.put(params, (err, data) => { |
| 36 | if (err) next(err) |
| 37 | else res.status(200).json( params.Item ) |
| 38 | }) |
| 39 | |
| 40 | }) |
| 41 | |
| 42 | // GET Route |
| 43 | app.get('/foodstore/foods/:foodId', (req, res, next) => { |
| 44 | |
| 45 | var foodId = req.params.foodId |
| 46 | var params = { |
| 47 | Key: { "foodId": foodId }, |
| 48 | TableName: DynamoDBTable |
| 49 | } |
| 50 | |
| 51 | dynamodbDocumentClient.get(params, (err, data) => { |
| 52 | if (err) next(err) |
| 53 | else res.status(200).json( data.Item || {} ) |
| 54 | }) |
| 55 | |
| 56 | }) |
| 57 | |
| 58 | // Handle generic error |
| 59 | app.use((err, req, res, next) => { |
| 60 | console.log(err) |
| 61 | res.status( err.status || err.statusCode|| 500 ).json({ message: err.message }) |
| 62 | }) |
| 63 | |
| 64 | // Handle 404 error |
| 65 | app.use((req, res, next) => { |
| 66 | res.status(404).json({ message: 'Not found' }) |
| 67 | }) |
| 68 | |
| 69 | // Express app to listen |
| 70 | app.listen( PORT, () => console.log(`Foodstore container listening on port ${PORT}!`) ) |