Advertisement
Guest User

Untitled

a guest
Jul 19th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.13 KB | None | 0 0
  1.  
  2. import {Router} from 'express';
  3. import models from '../models/index';
  4. import Promise from 'bluebird';
  5. import Helper from './helpers';
  6. import uuid from 'uuid';
  7. import reactCookie from 'react-cookie';
  8. import * as email from './emails';
  9.  
  10. // Initial verison of error handler.
  11. // Helper.errorHandler is slightly modified!
  12. function errorHandler(err, req, res, next) {
  13. console.log('error object:', err);
  14. if (err) { res.send({message: 'errors found!', error: err}) }
  15. }
  16.  
  17. var app = Router();
  18.  
  19. //////////////////////////
  20. // CREATE
  21. //////////////////////////
  22.  
  23. // Create a new Account
  24. app.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
  88. app.post('/email/new', 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
  97. app.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
  105. app.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. app.get('/emails/:id', function (req, res, next) {
  142. email.findEmails(req, res, next);
  143. })
  144.  
  145. // find one user by email
  146. app.get('/user/:email', function (req, res, next) {
  147. console.log("attempting to find an email: ");
  148. console.log(req.params);
  149. models.Account
  150. .find({
  151. where: {
  152. email: req.params.email
  153. }
  154. }) // convert req.params.id to integer
  155. .catch(function (err) {
  156. Helper.handleCatchError(err, res);
  157. })
  158. .then(function (account) {
  159. models.Email
  160. .find({
  161. where: {
  162. AccountId: account.dataValues.id
  163. }
  164. })
  165. .then(email => {
  166. console.log('# # # REQ SESSION # # #');
  167. // Create UUID for sessions
  168. // add to req.session.id
  169. // send to client cookie
  170. // check if UUID already exists from Redis
  171. // req.session.userSessionId = uuid.v4();
  172. req.session.userId = account.dataValues.id;
  173. req.session.email = email.dataValues.emailAddress
  174. req.session.save();
  175. reactCookie.setRawCookie(req.headers.cookie);
  176. console.log(req.session);
  177. console.log(req.session.id)
  178. console.log(' ');
  179. console.log('-== ReQ headers ==-');
  180. console.log(' ');
  181. console.log(req.headers)
  182. console.log(' ');console.log(' ');
  183. console.log('--- res cookie ---');
  184. console.log(' ');console.log(' ');
  185. // // console.log (req.session.blah);
  186. // res.setHeader('SetCookie', req.session.id)
  187. // res.setHeader('Set-Cookie', req.session.id.toString())
  188. res.cookie('sessIdResCookie', req.session.id.toString());
  189. console.log(res.cookie);
  190. // console.log(res);
  191. res.send({
  192. sessionId: req.session.id,
  193. userId: account.dataValues.id,
  194. email: account.dataValues.email
  195. })
  196. })
  197. })
  198. })
  199.  
  200. // LOGIN : Read/Find one user by id and username or email then check password
  201. app.post('/login/', function (req, res, next) {
  202. models.Account
  203. .find({
  204. where: {
  205. id: req.body.id,
  206. username: req.body.username,
  207. password: req.body.password
  208. }
  209. })
  210. .catch(function (err) {
  211. Helper.handleCatchError(err, res);
  212. })
  213. .then(function (account) {
  214. models.Email
  215. .find({
  216. where: {
  217. AccountId: account.dataValues.id
  218. }
  219. })
  220. .then(email => {
  221. res.send({
  222. userDetails: {
  223. userId: account.dataValues.id,
  224. username: account.dataValues.username,
  225. firstName: account.dataValues.firstName,
  226. lastName: account.dataValues.lastName,
  227. email: email.dataValues.emailAddress
  228. }
  229. })
  230. })
  231. })
  232.  
  233. })
  234.  
  235. //////////////////////////
  236. // UPDATE
  237. //////////////////////////
  238.  
  239. // Update one account's email, phone number, or password all at once
  240. // ### ? ? ? How to update multiple columns at once if one or more inputs are null ? ? ? ###
  241. // The solution below is not optimized
  242. app.post('/update/:id/:username', function (req, res, next) {
  243. console.log({message: 'attempting to update one account with:', body: req.body, params: req.params, trimmedSpace: req.body.email.replace(/\s+/g, '')});
  244. var data = {},
  245. response = {};
  246.  
  247. for (var [key, val] of Object.entries(req.body)) {
  248. if (req.body.hasOwnProperty(key)) {
  249. if (val === null || val.replace(/\s+/g, '') === '') {
  250. data[key] = null;
  251. }
  252. else {
  253. data[key] = val;
  254. }
  255. }
  256. console.log('here is the updated data object: ', data);
  257. }
  258.  
  259. // console.log(typeof Helper);
  260. // console.log(typeof Helper.updateEmail);
  261. if (data.email !== null) {
  262. Helper.updateEmail(res, Number(req.params.id), req.params.username, data)
  263. }
  264. if (data.alias !== null) {
  265. Helper.updateAlias(res, Number(req.params.id), req.params.username, data)
  266. }
  267. if (data.phoneNumber !== null) {
  268. Helper.updatePhoneNumber(res, Number(req.params.id), req.params.username, data)
  269. }
  270. })
  271.  
  272. // update email address name
  273. app.post('/email/update', function (req, res, next) {
  274. email.updateEmail(req, res, next);
  275. })
  276.  
  277. // update primary email
  278. app.post('/email/primary', function (req, res, next) {
  279. email.updatePrimaryEmail(req, res, next);
  280. })
  281.  
  282. // update blog boost status
  283.  
  284. //Update all
  285.  
  286. //////////////////////////
  287. // DELETE
  288. //////////////////////////
  289.  
  290. // Delete One
  291.  
  292. // retrieve a single Account
  293. // router.get('/:id', function(req,res){
  294. // models.Account.find({
  295. // where: {
  296. // id: req.params.id
  297. // }
  298. // }).then(function(account){
  299. // res.json(account);
  300. // });
  301. // });
  302.  
  303.  
  304. // // applying middleware to all routes defined in this router
  305. // router.use(function(req,res,next){
  306. // // do something
  307. // });
  308.  
  309. export default app;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement