I have a procedure for saving users in the database.
These are the steps I take:
1) First, I validate the request.
2) Next, I hash the password.
3) Finally, I store the user details in the users collection along with the hashed password.
Below is the code where I subscribe to the hashPassword
method, get the hashed string, create the user with the hashed string, and then subscribe to the save
method. Instead of subscribing multiple times, how can I achieve this using the zip()
or map()
operator?
createUser(req: Request, res: Response): Observable<mongoose.Document> {
const body = req.body
const self = this
return singleObservable(Observable.create((observer: Observer<mongoose.Document>) => {
const errorMessage = new UserValidator(req).validateRequest()
if (errorMessage) {
observer.error(errorMessage)
} else {
self.hashPassword(req.body.password).subscribe(new BaseObserver(
(value) => {
const newUser = new this.userModule({ email: req.body.email, username: req.body.username, password: value })
this.save(newUser).subscribe(new BaseObserver((value) => {
observer.next(value)
}, (err) => {
observer.error(err)
}))
}, (error) => observer.error(error)))
}
}))
}
private hashPassword(password: string): Observable<string> {
return singleObservable(Observable.create((observer: Observer<string>) => {
bcrypt.hash(password, 10, (err, result) => {
result.length > 0 ? observer.next(result) : observer.error(err)
})
}))
}
save<T extends mongoose.Document>(model: mongoose.Document): Observable<T> {
return singleObservable(Observable.create(function (observer: Observer<mongoose.Document>) {
model.save(function (err, object) {
emitResult(observer, object, err)
})
}))
}
emitResult<T, E>(observer: Observer<T>, result: T | null, err: E) {
result ? observer.next(result) : observer.error(err);
}
singleObservable<T>(observable: Observable<T>) : Observable<T> {
return observable.pipe(first())
}