Monday, 2 September 2019

Need help with receiving an item that contains an array of items and storing it in dynamo

New to Node and JS altogether. Welcome all! Hope someone can direct me in the right direction here.In an attempt to learn what I'm doing I was writing a meal planner to play around with. Dynamo is my NoSQL database and my API is using lambda and API gateway in aws. when I call my API my req receives a JSON body that looks like the below:{`"mealname":"Tacos",` `"preferredcook": "person",` `"cooktime":45,` `"ingredients": {` `"Item1" : {` `"ItemType": "Ground Beef",` `"ItemWeight": 2,` `"ItemWeightType": "Pounds",` `"ItemInStock": 1` `},` `"Item2" : {` `"ItemType": "Taco Sauce",` `"ItemWeight": 16,` `"ItemWeightType": "oz"` `"ItemInStock": 1` `}` `}` }​I've written code to handle everything except the ingredients which I've pasted below. Can someone assist me in how to post an array of ingredients with my meal...or maybe I'm doing this completely wrong?​'use strict';const uuid = require('uuid');const AWS = require('aws-sdk');AWS.config.setPromisesDependency(require('bluebird'));const dynamoDb = new AWS.DynamoDB.DocumentClient();module.exports.submit = (event, context, callback) => {const requestBody = JSON.parse(event.body);const mealname = requestBody.mealname;const preferredcook = requestBody.preferredcook;const cooktime = requestBody.cooktime;if (typeof mealname !== 'string' || typeof preferredcook !== 'string' || typeof cooktime !== 'number') {console.error('Validation Failed');callback(new Error('Couldn\'t submit meal because of validation errors.'));return;}submitMealP(mealInfo(mealname, preferredcook, cooktime)).then(res => {callback(null, {statusCode: 200,body: JSON.stringify({message: \Sucessfully submitted meal with name ${mealname}`, mealId: res.id }) }); }) .catch(err => { console.log(err); callback(null, { statusCode: 500, body: JSON.stringify({ message: `Unable to submit meal with name ${mealname}` }) }) }); };`const submitMealP = meal => {console.log('Submitting Meal');const mealInfo = {TableName: process.env.MEAL_TABLE,Item: meal,};return dynamoDb.put(mealInfo).promise().then(res => meal);};const mealInfo = (mealname, preferredcook, cooktime) => {const timestamp = new Date().getTime();return {id: uuid.v1(),mealname: mealname,preferredcook: preferredcook,cooktime: cooktime,submittedAt: timestamp,updatedAt: timestamp,};};

Submitted September 03, 2019 at 03:09AM by funkel1989

No comments:

Post a Comment