-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
81 lines (65 loc) · 2.21 KB
/
index.js
File metadata and controls
81 lines (65 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const serverless = require('serverless-http');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const AWS = require('aws-sdk');
// const jsonData = require('./database.json')
const dynamoDb = new AWS.DynamoDB.DocumentClient();
app.use(bodyParser.json({ strict: false }));
const INGREDIENTS_TABLE = process.env.INGREDIENTS_TABLE || 'ingredients-dev';
const params = {
TableName: INGREDIENTS_TABLE,
};
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.get('/health', function (req, res) {
res.send('Health Check!!')
});
app.get('/ingredient/:ingredient', function(req,res) {
const newParams = {
...params,
Key: {
ingredient: req.params.ingredient
}
};
dynamoDb.get(newParams, (err, resp) => {
err ? res.status(400).json(err) : res.status(200).json(resp);
})
});
// take in array of objects with ingred structure
app.post('/add-ingredients', function(req, res) {
// data = array of ingredients
const {data} = req.body;
console.log(req.body.data, ' DATA');
// stringify the "tags",
// add name to property
// early return if data is not an array
if(!Array.isArray(data)) return res.status(400).json({err: "data must be an array"});
const errs = [];
data.map((ingredient, i) => {
let newParams = {
...params,
Item: {
ingredient: ingredient.name,
test: ingredient.text,
tags: JSON.stringify(ingredient.tags)
}
};
console.log(newParams, ' NEW PARAMS');
dynamoDb.put(newParams, (err) => {
err ? errs.push(`Error happened at index ${i} : err: ${err}`) : null;
});
})
res.json({message: "successfully added data", errors: errs});
});
// TODO: bulk import (database.json file above)
app.post('/add-all-ingredients', function(req, res) {
// data = array of ingredients
// const {data} = req.body;
// data will be an array of ingredient objects
// res.json(jsonData);
});
// when testing locally either run below or run app in serverless local mode
// app.listen(3000);
module.exports.handler = serverless(app);