· 10 years ago · Jul 19, 2016, 06:51 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 * as 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 phoneNumber: req.body.phoneNumber,
33 username: req.body.username,
34 password: req.body.password
35 })
36 .catch(function (err) {
37 Helper.handleCatchError(err, res);
38 })
39 .then(function (account) {
40 models.Email
41 .create({
42 emailAddress: req.body.email,
43 isPrimary: true,
44 AccountId: account.dataValues.id
45 })
46 .catch(function (err) {
47 Helper.handleCatchError(err, res);email
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.emailAddress
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// add new email
88app.post('/new/email', function (req, res, next) {
89 email.createEmail(req, res, next)
90})
91
92/////////////////////////////////////////////
93// Internal use only!
94/////////////////////////////////////////////
95
96// Create fields in interests table by user id
97app.post('/interests/create', function (req, res, next) {
98 Helper.createInterests(req, res, next);
99})
100
101//////////////////////////
102// READ / FIND
103//////////////////////////
104// Read/Find one user via :id
105app.get('/user/:email/:username', function (req, res, next) {
106 models.Account
107 .find({
108 where: {
109 id: Number(req.params.id),
110 username: req.params.username
111 }
112 }) // convert req.params.id to integer
113 .catch(function (err) {
114 Helper.handleCatchError(err, res);
115 })
116 .then(function (account) {
117 var results = {}
118 if (account) {
119 results.account = account.dataValues
120 models.Address
121 .find({
122 where: {
123 id: Number(req.params.id),
124 username: req.params.username
125 }
126 })
127 .catch(function (err) {
128 errorHandler(err.errors, req, res, next);
129 })
130 .then(function (address) {
131 if (address) {
132 results.address = address.dataValues
133 res.send(results);
134 }
135 })
136 }
137 })
138})
139
140// find all user's email
141
142// find one user by email
143app.get('/user/:email', function (req, res, next) {
144 console.log("attempting to find an email: ");
145 console.log(req.params);
146 models.Account
147 .find({
148 where: {
149 email: req.params.email
150 }
151 }) // convert req.params.id to integer
152 .catch(function (err) {
153 Helper.handleCatchError(err, res);
154 })
155 .then(function (account) {
156 console.log('# # # REQ SESSION # # #');
157 // Create UUID for sessions
158 // add to req.session.id
159 // send to client cookie
160 // check if UUID already exists from Redis
161 // req.session.userSessionId = uuid.v4();
162 req.session.userId = account.dataValues.id;
163 req.session.email = account.dataValues.email
164 req.session.save();
165 reactCookie.setRawCookie(req.headers.cookie);
166 console.log(req.session);
167 console.log(req.session.id)
168 console.log(' ');
169 console.log('-== ReQ headers ==-');
170 console.log(' ');
171 console.log(req.headers)
172 console.log(' ');console.log(' ');
173 console.log('--- res cookie ---');
174 console.log(' ');console.log(' ');
175 // // console.log (req.session.blah);
176 // res.setHeader('SetCookie', req.session.id)
177 // res.setHeader('Set-Cookie', req.session.id.toString())
178 res.cookie('sessIdResCookie', req.session.id.toString());
179 console.log(res.cookie);
180 // console.log(res);
181 res.send({
182 sessionId: req.session.id,
183 userId: account.dataValues.id,
184 email: account.dataValues.email
185 })
186 })
187})
188
189// LOGIN : Read/Find one user by id and username or email then check password
190app.post('/login/', function (req, res, next) {
191 models.Account
192 .find({
193 where: {
194 id: req.body.id,
195 username: req.body.username,
196 password: req.body.password
197 }
198 })
199 .catch(function (err) {
200 Helper.handleCatchError(err, res);
201 })
202 .then(function (account) {
203 res.send({
204 userDetails: {
205 userId: account.dataValues.id,
206 username: account.dataValues.username,
207 firstName: account.dataValues.firstName,
208 lastName: account.dataValues.lastName,
209 email: account.dataValues.email
210 }
211 })
212 })
213
214})
215
216//////////////////////////
217// UPDATE
218//////////////////////////
219
220// Update one account's email, phone number, or password all at once
221// ### ? ? ? How to update multiple columns at once if one or more inputs are null ? ? ? ###
222// The solution below is not optimized
223app.post('/update/:id/:username', function (req, res, next) {
224 console.log({message: 'attempting to update one account with:', body: req.body, params: req.params, trimmedSpace: req.body.email.replace(/\s+/g, '')});
225 var data = {},
226 response = {};
227
228 for (var [key, val] of Object.entries(req.body)) {
229 if (req.body.hasOwnProperty(key)) {
230 if (val === null || val.replace(/\s+/g, '') === '') {
231 data[key] = null;
232 }
233 else {
234 data[key] = val;
235 }
236 }
237 console.log('here is the updated data object: ', data);
238 }
239
240 // console.log(typeof Helper);
241 // console.log(typeof Helper.updateEmail);
242 if (data.email !== null) {
243 Helper.updateEmail(res, Number(req.params.id), req.params.username, data)
244 }
245 if (data.alias !== null) {
246 Helper.updateAlias(res, Number(req.params.id), req.params.username, data)
247 }
248 if (data.phoneNumber !== null) {
249 Helper.updatePhoneNumber(res, Number(req.params.id), req.params.username, data)
250 }
251})
252
253// update email address name
254
255// update primary email
256
257// update blog boost status
258
259//Update all
260
261//////////////////////////
262// DELETE
263//////////////////////////
264
265// Delete One
266
267// retrieve a single Account
268// router.get('/:id', function(req,res){
269// models.Account.find({
270// where: {
271// id: req.params.id
272// }
273// }).then(function(account){
274// res.json(account);
275// });
276// });
277
278
279// // applying middleware to all routes defined in this router
280// router.use(function(req,res,next){
281// // do something
282// });
283
284export default app;