-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
226 lines (195 loc) · 7.68 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
const express = require('express');
const axios = require('axios');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const url = 'mongodb+srv://dbUser:[email protected]/NamazonDB?retryWrites=true&w=majority';
const UserModel = require('./User');
const StoreItemModel = require('./StoreItem');
const CartItemModel = require('./CartItem');
const jwt = require('jsonwebtoken');
const accessTokenSecret = "upDownLeftRightUpDownLeftRight";
const app = express();
app.use(express.json());
const router = express.Router();
const dbName = 'NamazonDB';
// API Key for randommer imports
const config = {
headers: {
'X-Api-Key': '7542e71a409f40da97408a0992a9e53e'
}
}
let database;
// connecting to and initializing database
const initDatabase = async () => {
database = await mongoose.connect(url);
if (database) {
app.use(session({
secret: "allYourBaseAreBelongToUs",
store: new MongoStore({mongooseConnection: mongoose.connection})
}));
app.use(router);
console.log("Successfully connected to my DB");
} else {
console.log("error connecting to my DB");
}
}
initDatabase(); //testing connection
/********************************************************
* Functions to populate shopping items and users *
********************************************************/
// Generate random users and add them to the array of users
const getNameDataInParallel = async () => {
const firstNamePromise = axios.get('https://randommer.io/api/Name?nameType=firstname&quantity=20', config);
const lastNamePromise = axios.get('https://randommer.io/api/Name?nameType=surname&quantity=20', config);
const users = [];
let results = await Promise.all([firstNamePromise, lastNamePromise]);
for (j = 0; j < results[0].data.length; j++) {
const newUser = {
name: {
firstName: results[0].data[j],
lastName: results[1].data[j]
},
login: `${results[0].data[j]}.${results[1].data[j]}`,
password: 'userPw',
cart: [],
email: results[0].data[j] + results[1].data[j] + "@ex.com"
};
for (let i = 0; i < Math.floor(Math.random() * 10); ++i) {
const item = await StoreItemModel.findOne().skip(Math.floor(Math.random() * 100))
const quantity = Math.floor(Math.random() * 10);
const newCartItem = {item, quantity};
newUser.cart.push(await CartItemModel.create(newCartItem));
}
users.push(newUser);
}
await UserModel.create(users);
}
// Generate a bunch of random items for the store
const getStoreItems = async () => {
const storeItems = [];
const itemResult = await axios.get('https://randommer.io/api/Name/Suggestions?startingWords=item', config);
itemResult.data.forEach((itemName, index) => {
let newItem = {
storeItemName: itemName,
storeItemQuantity: Math.floor(Math.random() * 10)
};
storeItems.push(newItem);
})
await StoreItemModel.create(storeItems);
}
// Syncs up functions that populate users and items
const initializeData = async () => {
await getStoreItems();
await getNameDataInParallel();
}
//initializeData(); // uncomment to populate the database
/********************************************************
* GET functions to return requested information *
********************************************************/
// Get all of the users
router.get('/users', async (req, res) => {
const foundUsers = await UserModel.find().populate('User');
res.send(foundUsers);
})
// Get user by ID
router.get('/user/:id', async (req, res) => {
const reqUserId = await UserModel.findById(req.params.id).populate('cart');
res.send(reqUserId ? reqUserId : 404);
});
// Get a store item by ID
router.get('/StoreItem/:id', async (req, res) => {
let reqStoreItemId = await StoreItemModel.find({_id:req.params.id}).populate('StoreItem');
if(!req.session.lastItemsViewed){
req.session.lastItemsViewed = [reqStoreItemId];
}
else{
req.session.lastItemsViewed.push(reqStoreItemId);
}
res.send(reqStoreItemId ? reqStoreItemId : 404);
});
// Get last items viewed TODO NOT WORKING
router.get('/StoreItem/Recent/', async(req, res) => {
res.send(req.session);
});
// Get the cart of a specified user
router.get('/user/:UserId/cart', async (req, res) => {
let foundUser = await UserModel.find({_id:req.params.UserId}).populate('cart');
res.send(foundUser ? foundUser : 404);
});
// Get a store item regex query of part of the item's name
router.get('/StoreItem', async (req, res) => {
let foundStoreItem = await StoreItemModel.find({
storeItemName: new RegExp(req.query.storeItemName)
}).populate('storeitems');
if(!req.session.lastItemsViewed){
req.session.lastItemsViewed = [foundStoreItem];
}
else{
req.session.lastItemsViewed.push(foundStoreItem);
}
res.send(foundStoreItem ? foundStoreItem : 404);
});
/********************************************************
* POST functions to create new entries *
********************************************************/
// Create a user using a post
router.post('/user', async(req, res) => {
const newUser = await UserModel.create(req.body);
res.send(newUser ? newUser : 500);
})
// Add a new item to specified user's cart TODO fix this
router.post('/cart/:id/cartItem', async (req, res) => {
const foundUserForItem1 = await UserModel.findById(req.params.id);
const newcartitem = foundUserForItem1.cart.push(req.body);
foundUserForItem1.save();
res.send(newcartitem ? newcartitem : 500);
})
/********************************************************
* DELETE functions to delete specified entries *
********************************************************/
// Empties specific user's cart
router.delete('/user/:UserId/cart', async(req, res) => {
const foundUser1 = await UserModel.findById(req.params.UserId).populate('cart');
const deletedItem = foundUser1.cart.pop() // NOTE: this removes the last element from the cart. Call until cart empty.
await foundUser1.save();
res.send(deletedItem ? deletedItem : 404);
});
//Deletes the index of the item in the specified user's cart and sends remaining items back
router.delete('/cart/:UserId/:cartItemId', async (req, res) => {
const founduser = await UserModel.findById(req.params.UserId).populate('cart');
const deleteditem = founduser.cart.pull(req.params.cartItemId)
await founduser.save();
res.send(deleteditem ? deleteditem : 404); // This is sending what is left in the cart, item was deleted
});
/********************************************************
* JWT routes. Create jwt token and require for routes *
********************************************************/
// require token for routes
app.use(async (req, res, next) =>{
try {
const authHeader = req.headers.authorization;
if (authHeader) {
const jwtToken = authHeader.split(' ')[1];
const user = jwt.verify(jwtToken, accessTokenSecret);
req.user = user;
}
}
catch(err){
res.send(403);
}
next();
})
// create access token if the user has a valid login
router.post('/user/login', async(req, res) => {
const {login, password} = req.body;
const foundUser = await UserModel.findOne({login, password});
if(foundUser){
// user found, create token
const accessToken = jwt.sign({user:foundUser}, accessTokenSecret);
res.send(accessToken);
}else{
res.send(403);
}
})
app.listen(3000);