· 10 years ago · Jul 19, 2016, 06:24 PM
1
2import {Router} from 'express';
3import models from '../models/index';
4import Promise from 'bluebird';
5import Helper from './helpers';
6import uuid from 'uuid';
7import reactCookie from 'react-cookie';
8import email from './emails';
9
10// Initial verison of error handler.
11// Helper.errorHandler is slightly modified!
12function errorHandler(err, req, res, next) {
13 console.log('error object:', err);
14 if (err) { res.send({message: 'errors found!', error: err}) }
15}
16
17var app = Router();
18
19//////////////////////////
20// CREATE
21//////////////////////////
22
23// Create a new Account
24app.post('/', function (req, res, next) {
25 // res.send({foo: 'bar'});
26 var userDetails = {};
27
28 models.Account
29 .create({
30 firstName: req.body.firstName,
31 lastName: req.body.lastName,
32 // email: req.body.email,
33 phoneNumber: req.body.phoneNumber,
34 username: req.body.username,
35 password: req.body.password
36 })
37 .catch(function (err) {
38 Helper.handleCatchError(err, res);
39 })
40 .then(function (account) {
41 models.Email
42 .create({
43 emailAddress: req.body.email,
44 isPrimary: true
45 })
46 .catch(function (err) {
47 Helper.handleCatchError(err, res);
48 })
49 .then(function (email) {
50 if (account) {
51 userDetails.userId = account.dataValues.id // : userDetails.Err = {err: account};
52 // userDetails.username = account.dataValues.username
53 userDetails.firstName = account.dataValues.firstName
54 userDetails.lastName = account.dataValues.lastName
55 userDetails.email = email.dataValues.email
56 // ========================================
57 // Remember to include assocId in .create!
58 // ========================================
59 models.Address
60 .create({
61 // addressLine1: req.body.addressLine1,
62 // addressLine2: req.body.addressLine2,
63 city: req.body.city,
64 province: req.body.province,
65 region: req.body.region,
66 postalCode: req.body.postalCode,
67 country: req.body.country,
68 AccountId: account.dataValues.id
69 })
70 .catch(function (err) {
71 Helper.handleCatchError(err, res);
72 })
73 .then(function (address) {
74 // OPTIONAL RESPONSE -- used for checking if reg is successful
75 res.send(userDetails);
76 })
77 }
78 })
79 })
80 // .catch(function (err) {
81 // // res.status(500).send({message: 'At end of outer then statement... Error: ', err: err})
82 // console.log('in outer catch...',err)
83 // errorHandler(err, req, res, next);
84 // })
85})
86
87/////////////////////////////////////////////
88// Internal use only!
89/////////////////////////////////////////////
90
91// Create fields in interests table by user id
92app.post('/interests/create', function (req, res, next) {
93 Helper.createInterests(req, res, next);
94})
95
96//////////////////////////
97// READ / FIND
98//////////////////////////
99// Read/Find one user via :id
100app.get('/user/:email/:username', function (req, res, next) {
101 models.Account
102 .find({
103 where: {
104 id: Number(req.params.id),
105 username: req.params.username
106 }
107 }) // convert req.params.id to integer
108 .catch(function (err) {
109 Helper.handleCatchError(err, res);
110 })
111 .then(function (account) {
112 var results = {}
113 if (account) {
114 results.account = account.dataValues
115 models.Address
116 .find({
117 where: {
118 id: Number(req.params.id),
119 username: req.params.username
120 }
121 })
122 .catch(function (err) {
123 errorHandler(err.errors, req, res, next);
124 })
125 .then(function (address) {
126 if (address) {
127 results.address = address.dataValues
128 res.send(results);
129 }
130 })
131 }
132 })
133})
134
135// find one user by email
136app.get('/user/:email', function (req, res, next) {
137 console.log("attempting to find an email: ");
138 console.log(req.params);
139 models.Account
140 .find({
141 where: {
142 email: req.params.email
143 }
144 }) // convert req.params.id to integer
145 .catch(function (err) {
146 Helper.handleCatchError(err, res);
147 })
148 .then(function (account) {
149 console.log('# # # REQ SESSION # # #');
150 // Create UUID for sessions
151 // add to req.session.id
152 // send to client cookie
153 // check if UUID already exists from Redis
154 // req.session.userSessionId = uuid.v4();
155 req.session.userId = account.dataValues.id;
156 req.session.email = account.dataValues.email
157 req.session.save();
158 reactCookie.setRawCookie(req.headers.cookie);
159 console.log(req.session);
160 console.log(req.session.id)
161 console.log(' ');
162 console.log('-== ReQ headers ==-');
163 console.log(' ');
164 console.log(req.headers)
165 console.log(' ');console.log(' ');
166 console.log('--- res cookie ---');
167 console.log(' ');console.log(' ');
168 // // console.log (req.session.blah);
169 // res.setHeader('SetCookie', req.session.id)
170 // res.setHeader('Set-Cookie', req.session.id.toString())
171 res.cookie('sessIdResCookie', req.session.id.toString());
172 console.log(res.cookie);
173 // console.log(res);
174 res.send({
175 sessionId: req.session.id,
176 userId: account.dataValues.id,
177 email: account.dataValues.email
178 })
179 })
180})
181
182// LOGIN : Read/Find one user by id and username or email then check password
183app.post('/login/', function (req, res, next) {
184 models.Account
185 .find({
186 where: {
187 id: req.body.id,
188 username: req.body.username,
189 password: req.body.password
190 }
191 })
192 .catch(function (err) {
193 Helper.handleCatchError(err, res);
194 })
195 .then(function (account) {
196 res.send({
197 userDetails: {
198 userId: account.dataValues.id,
199 username: account.dataValues.username,
200 firstName: account.dataValues.firstName,
201 lastName: account.dataValues.lastName,
202 email: account.dataValues.email
203 }
204 })
205 })
206
207})
208
209//////////////////////////
210// UPDATE
211//////////////////////////
212
213// Update one account's email, phone number, or password all at once
214// ### ? ? ? How to update multiple columns at once if one or more inputs are null ? ? ? ###
215// The solution below is not optimized
216app.post('/update/:id/:username', function (req, res, next) {
217 console.log({message: 'attempting to update one account with:', body: req.body, params: req.params, trimmedSpace: req.body.email.replace(/\s+/g, '')});
218 var data = {},
219 response = {};
220
221 for (var [key, val] of Object.entries(req.body)) {
222 if (req.body.hasOwnProperty(key)) {
223 if (val === null || val.replace(/\s+/g, '') === '') {
224 data[key] = null;
225 }
226 else {
227 data[key] = val;
228 }
229 }
230 console.log('here is the updated data object: ', data);
231 }
232
233 // console.log(typeof Helper);
234 // console.log(typeof Helper.updateEmail);
235 if (data.email !== null) {
236 Helper.updateEmail(res, Number(req.params.id), req.params.username, data)
237 }
238 if (data.alias !== null) {
239 Helper.updateAlias(res, Number(req.params.id), req.params.username, data)
240 }
241 if (data.phoneNumber !== null) {
242 Helper.updatePhoneNumber(res, Number(req.params.id), req.params.username, data)
243 }
244})
245
246
247
248// update blog boost status
249
250//Update all
251
252//////////////////////////
253// DELETE
254//////////////////////////
255
256// Delete One
257
258// retrieve a single Account
259// router.get('/:id', function(req,res){
260// models.Account.find({
261// where: {
262// id: req.params.id
263// }
264// }).then(function(account){
265// res.json(account);
266// });
267// });
268
269
270// // applying middleware to all routes defined in this router
271// router.use(function(req,res,next){
272// // do something
273// });
274
275export default app;