-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (73 loc) · 2.34 KB
/
index.js
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
82
83
84
const express = require('express')
const serverlessHttp = require('serverless-http')
const path = require('path')
const bodyParser = require('body-parser')
const AWS = require('aws-sdk')
const app = express();
const USERS_TABLE = process.env.USERS_TABLE;
console.log()
const dynamoDb = new AWS.DynamoDB.DocumentClient();
app.use(bodyParser.json({ strict : false }));
//send index file on root path.
app.get("/",(req,res)=>{
res.sendFile(path.resolve(__dirname,"index.html"));
});
app.get("/user/:email",(req,res)=>{
const params = {
TableName : USERS_TABLE,
key : {
email : req.params.email
}
};
try{
dynamoDb.get(params, (error,result) => {
if(error){
console.log(error);
res.status(400).send({error: "Could not get User"});
}
if(result.Item){
const {email,firstname,lastname} = result.Item;
res.status(200).status({ email, firstname, lastname });
}else{
res.status(400).send({error : "could not get user"});
}
})
}
catch(err){
res.status(404).send({error : "could not get user"});
}
});
app.post("/user",(req,res)=>{
const { firstname,lastname,email,password } = req.body;
if(typeof email !== 'string'){
res.status(400).send({error:"Email must be string"});
} else if (typeof firstname !== 'string'){
res.status(400).send({error:"firstname must be string"});
}else if(typeof lastname !== 'string'){
res.status(400).send({error:"lastname must be string"});
}else if(typeof password !== 'string'){
res.status(400).send({error:"password must be string"});
}
const params = {
TableName : USERS_TABLE,
Item : {
email : email,
firstName : firstname,
lastName : lastname,
password : password
}
};
try{
dynamoDb.put(params,(error)=>{
if(error){
console.log(error);
res.status(400).send({error: "Not able to create user"});
}
res.status(200).send({email,firstname,lastname});
});
}
catch(err){
res.status(404).send({"message" : "OOps someyjing went wrong."});
}
});
module.exports.handler = serverlessHttp(app);