cache remote username check response

This commit is contained in:
Ben Wheeler 2019-08-27 15:16:30 -04:00
parent c58735f7e0
commit 0d4d6a9adc

View file

@ -27,12 +27,15 @@ class UsernameStep extends React.Component {
'validatePasswordIfPresent', 'validatePasswordIfPresent',
'validatePasswordConfirmIfPresent', 'validatePasswordConfirmIfPresent',
'validateUsernameIfPresent', 'validateUsernameIfPresent',
'validateUsernameRemotelyWithCache',
'validateForm' 'validateForm'
]); ]);
this.state = { this.state = {
focused: null, focused: null,
showPassword: false showPassword: false
}; };
// keeps us from submitting multiple remote requests for a single username
this.usernameRemoteCache = {};
} }
componentDidMount () { componentDidMount () {
// automatically start with focus on username field // automatically start with focus on username field
@ -49,12 +52,24 @@ class UsernameStep extends React.Component {
handleSetUsernameRef (usernameInputRef) { handleSetUsernameRef (usernameInputRef) {
this.usernameInput = usernameInputRef; this.usernameInput = usernameInputRef;
} }
validateUsernameRemotelyWithCache (username) {
if (this.usernameRemoteCache.hasOwnProperty(username)) {
return Promise.resolve(this.usernameRemoteCache[username]);
}
// username is not in our cache
return validate.validateUsernameRemotely(username).then(
remoteResult => {
this.usernameRemoteCache[username] = remoteResult;
return remoteResult;
}
);
}
// we allow username to be empty on blur, since you might not have typed anything yet // we allow username to be empty on blur, since you might not have typed anything yet
validateUsernameIfPresent (username) { validateUsernameIfPresent (username) {
if (!username) return null; // skip validation if username is blank; null indicates valid if (!username) return null; // skip validation if username is blank; null indicates valid
// if username is not blank, run both local and remote validations // if username is not blank, run both local and remote validations
const localResult = validate.validateUsernameLocally(username); const localResult = validate.validateUsernameLocally(username);
return validate.validateUsernameRemotely(username).then( return this.validateUsernameRemotelyWithCache(username).then(
remoteResult => { remoteResult => {
// there may be multiple validation errors. Prioritize vulgarity, then // there may be multiple validation errors. Prioritize vulgarity, then
// length, then having invalid chars, then all other remote reports // length, then having invalid chars, then all other remote reports