I completed a Node app tutorial and went back to rewrite the code with async/await to better learn how it's done. However I have a route handler the I can't get right without using promises:
getProfile: function(id){
return new Promise(function(resolve, reject){
Profile.findById(id, function(err, profile){
if (err){
reject(err)
return
}
resolve(profile.summary())
})
})
}
which I rewrote as:
getProfile: async (req, res, next) => {
const profileId = req.params.id;
const profile = await Profile.findById(profileId);
res.status(200).json(profile)
}
EDIT 2: OK i also realized I rewrote:
create: function(params){
return new Promise(function(resolve, reject){
var password = params.password
params['password'] = bcrypt.hashSync(password, 10)
Profile.create(params, function(err, profile){
if (err){
reject(err)
return
}
resolve(profile.summary())
})
})
}
as
newProfile: async (params, res, next) => {
const newProfile = new Profile(params);
const password = params.password
params['password'] = bcrypt.hashSync(password, 10)
const profile = await newProfile.save();
return profile.summary()
},
which could very well be causing an issue with the jsonwebtokens :<
The API endpoint I am having trouble with uses jsonwebtokens:
var token = req.session.token
utils.JWT.verify(token, process.env.TOKEN_SECRET)
.then(function(decode){
return controllers.profile.getProfile(decode.id)
})
.then(function(profile){
res.json({
confirmation: 'success',
profile: profile
})
})
.catch(function(err){
res.json({
confirmation: 'fail',
message: 'Invalid Token'
})
})
}
The async code works for both the GET and POST requests to /profile route but keeps getting the 'Invalid Token' message in the API catch block. I am new to both promises and async code so Im sure theres a lot I'm not understanding right now.
So my questions is how could I have rewritten the promise to pass off the profile object in the correct format?
Full Files:
controllers/ProfileController.js
var Profile = require('../models/Profile')
var Album = require('../models/Album')
var Promise = require('bluebird')
var bcrypt = require('bcryptjs')
module.exports = {
index: async (req, res, next) => {
const profiles = await Profile.find({});
const summaries = []
profiles.forEach(function(profile){
summaries.push(profile.summary())
})
res.status(200).json(summaries)
},
newProfile: async (params, res, next) => {
const newProfile = new Profile(params);
const password = params.password
params['password'] = bcrypt.hashSync(password, 10)
const profile = await newProfile.save();
return profile.summary()
},
getProfile: function(id){
return new Promise(function(resolve, reject){
Profile.findById(id, function(err, profile){
if (err){
reject(err)
return
}
resolve(profile.summary())
})
})
},
updateProfile: async (req, res, next) => {
const { profileId } = req.params;
const newProfile = req.body;
const result = await Profile.findByIdAndUpdate(profileId, newProfile);
res.status(200).json({success: true})
},
getProfileAlbums: async (req, res, next) => {
const profileId = req.params.id;
const profile = await Profile.findById(profileId);
},
newProfileAlbum: async (req, res, next) => {
const newAlbum = new Album(req.body);
console.log('newAlbum', newAlbum)
}
}
routes/profile.js:
var express = require('express');
const router = require('express-promise-router')();
const ProfileController = require('../controllers/ProfileController')
router.route('/')
.get(ProfileController.index)
.post(ProfileController.newProfile);
router.route('/:id')
.get(ProfileController.getProfile)
.patch(ProfileController.updateProfile);
router.route('/:id/album')
.get(ProfileController.getProfileAlbums)
.post(ProfileController.newProfileAlbum);
module.exports = router;
routes/account.js:
var express = require('express')
var router = express.Router()
var controllers = require('../controllers')
var bcrypt = require('bcryptjs')
var utils = require('../utils')
router.get('/:action', function(req, res, next){
var action = req.params.action
if (action == 'logout'){
req.session.reset()
res.json({
confirmation: 'success'
})
}
if (action == 'currentuser'){
if (req.session == null) {
res.json({
confirmation: 'success',
message: 'user not logged in'
})
return
}
if (req.session.token == null) {
res.json({
confirmation: 'success',
message: 'user not logged in'
})
return
}
var token = req.session.token
utils.JWT.verify(token, process.env.TOKEN_SECRET)
.then(function(decode){
return controllers.profile.getProfile(decode.id)
})
.then(function(profile){
res.json({
confirmation: 'success',
profile: profile
})
})
.catch(function(err){
res.json({
confirmation: 'fail',
message: 'Invalid Token'
})
})
}
})
router.post('/register', function(req, res, next){
var credentials = req.body
controllers.profile
.newProfile(credentials)
.then(function(profile){
var token = utils.JWT.sign({id: profile.id}, process.env.TOKEN_SECRET)
req.session.token = token
res.json({
confirmation: 'success',
profile: profile,
token: token
})
})
.catch(function(err){
res.json({
confirmation: 'fail',
message: err.message || err
})
})
})
router.post('/login', function(req, res, next){
var credentials = req.body
controllers.profile
.find({userName: credentials.userName}, true)
.then(function(profiles){
if (profiles.length == 0){
res.json({
confirmation: 'fail',
message: 'Profile not found'
})
return
}
var profile = profiles[0]
var passwordCorrect = bcrypt.compareSync(credentials.password, profile.password)
if (passwordCorrect == false){
res.json({
confirmation: 'fail',
message: 'Incorrect password'
})
return
}
var token = utils.JWT.sign({id: profile._id}, process.env.TOKEN_SECRET)
req.session.token = token
res.json({
confirmation: 'success',
profile: profile.summary(),
token: token
})
})
.catch(function(err){
res.json({
confirmation: 'fail',
message: err
})
})
})
module.exports = router
utils/JWT.js:
var jwt = require('jsonwebtoken')
var Promise = require('bluebird')
module.exports = {
sign: function(obj, secret){
return jwt.sign(obj, secret)
},
verify: function(token, secret){
return new Promise(function(resolve, reject){
jwt.verify(token, secret, function(err, decode){
if (err){
reject(err)
return
}
resolve(decode)
})
})
}
}
getProfile
without async should have been written asreturn Profile.findById(id).then(profile => profile.summary())
, FWIW. – Hortaconsole.error(err)
the error instead of failing with an indeterminate message, so that you know what the actual problem is. – CystolithProfile.findById
already returns a promise instead of taking a callback. – Cystolithreturn profile.summary()
which I was hoping would be the same result asresolve(profile.summary())
– BroadsProfile.findById
directly it would work. – Beggarmodels/Profile
file, and change the function to not use a callback, but rather return a promise, your change should work. If you want to post themodels/Profile
file I can edit it to show you what I mean. – Beggar