File tree 1 file changed +26
-8
lines changed
1 file changed +26
-8
lines changed Original file line number Diff line number Diff line change @@ -116,34 +116,52 @@ userSchema.pre('save', function checkPassword(next) {
116
116
* API keys hash middleware
117
117
*/
118
118
userSchema . pre ( 'save' , function checkApiKey ( next ) {
119
- // eslint-disable-line consistent-return
120
119
const user = this ;
121
120
if ( ! user . isModified ( 'apiKeys' ) ) {
122
121
next ( ) ;
123
122
return ;
124
123
}
124
+
125
125
let hasNew = false ;
126
+ let pendingTasks = 0 ;
127
+ let nextCalled = false ;
128
+
129
+ const done = ( err ) => {
130
+ if ( nextCalled ) return ;
131
+ if ( err ) {
132
+ nextCalled = true ;
133
+ next ( err ) ;
134
+ return ;
135
+ }
136
+ pendingTasks -= 1 ;
137
+ if ( pendingTasks === 0 ) {
138
+ nextCalled = true ;
139
+ next ( ) ;
140
+ }
141
+ } ;
142
+
126
143
user . apiKeys . forEach ( ( k ) => {
127
144
if ( k . isNew ) {
128
145
hasNew = true ;
146
+ pendingTasks += 1 ;
129
147
bcrypt . genSalt ( 10 , ( err , salt ) => {
130
- // eslint-disable-line consistent-return
131
148
if ( err ) {
132
- next ( err ) ;
133
- return ;
149
+ done ( err ) ;
134
150
}
135
151
bcrypt . hash ( k . hashedKey , salt , ( innerErr , hash ) => {
136
152
if ( innerErr ) {
137
- next ( innerErr ) ;
138
- return ;
153
+ done ( innerErr ) ;
139
154
}
140
155
k . hashedKey = hash ;
141
- next ( ) ;
156
+ done ( ) ;
142
157
} ) ;
143
158
} ) ;
144
159
}
145
160
} ) ;
146
- if ( ! hasNew ) next ( ) ;
161
+
162
+ if ( ! hasNew ) {
163
+ next ( ) ;
164
+ }
147
165
} ) ;
148
166
149
167
userSchema . virtual ( 'id' ) . get ( function idToString ( ) {
You can’t perform that action at this time.
0 commit comments