Chaining ES6 Promises in Mongoose with Typescript
Add control flow to the existing user by using a existing
flag on the promise's response.Example:
public static signup(req: express.Request, res: express.Response) { UserModel.findOne({ email: req.body.email }).exec() .then(existingUser => { if(existingUser) { return Promise.resolve({ user: existing, existing: true }); } return UserModel.create({ firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email, password: req.body.password }).then((user) => { return Promise.resolve({ existing: false, user: user }); }); }) .then(response => { if (response.existing) { return res.send({ message: `Email ${response.user.email} is in use` }); } else return res.send({ token: AuthUtils.createJWT(response.user)}); }) .catch(err => { console.log(err); }); }
I actually ended up building my project for ES6 so that I could use async/await
It allowed me to simplify the code drastically.
public static async signup(req: express.Request, res: express.Response) { try { let user = await UserModel.findOne({ email: req.body.email }).exec() if(user) { throw `Email ${user.email} is in use`; } if(environment.debug) console.log(`Creating new user ${req.body.firstName} ${req.body.lastName} with email ${req.body.email}`); user = await UserModel.create({ firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email, password: req.body.password }); return res.send({ token: AuthUtils.createJWT(user)}); } catch(e) { console.log(e); res.send({ error: e }); }}