diff --git a/src/components/auth/Register.svelte b/src/components/auth/Register.svelte index b631598..924b2da 100644 --- a/src/components/auth/Register.svelte +++ b/src/components/auth/Register.svelte @@ -13,8 +13,6 @@ usernameValid = await isUsernameValid(username) - console.log(username, ' is valid: ', usernameValid) - if (usernameValid) { usernameAvailable = await isUsernameAvailable(username) console.log(username, ' is available: ', usernameAvailable) diff --git a/src/lib/common/utils.ts b/src/lib/common/utils.ts new file mode 100644 index 0000000..0a03944 --- /dev/null +++ b/src/lib/common/utils.ts @@ -0,0 +1,25 @@ +export function asyncDebounce( + fn: (...args: A) => Promise, + wait: number +): (...args: A) => Promise { + let lastTimeoutId: ReturnType | undefined = undefined + + return (...args: A): Promise => { + clearTimeout(lastTimeoutId) + + return new Promise((resolve, reject) => { + const currentTimeoutId = setTimeout(async () => { + try { + if (currentTimeoutId === lastTimeoutId) { + const result = await fn(...args) + resolve(result) + } + } catch (err) { + reject(err) + } + }, wait) + + lastTimeoutId = currentTimeoutId + }) + } +} \ No newline at end of file diff --git a/src/lib/common/webnative.ts b/src/lib/common/webnative.ts index d8270ae..e947f62 100644 --- a/src/lib/common/webnative.ts +++ b/src/lib/common/webnative.ts @@ -3,6 +3,7 @@ import * as webnative from 'webnative' import type FileSystem from 'webnative/fs/index' import { USE_WNFS_IMPLEMENTATION } from 'webnative/auth/implementation/use-wnfs' import { setup } from 'webnative' +import { asyncDebounce } from '$lib/common/utils' // runfission.net = staging setup.endpoints({ api: 'https://runfission.net', user: 'fissionuser.net' }) @@ -61,9 +62,12 @@ export const isUsernameValid = async (username: string): Promise => { return webnative.account.isUsernameValid(username) } +const debouncedIsUsernameAvailable = asyncDebounce(webnative.account.isUsernameAvailable, 300) + export const isUsernameAvailable = async (username: string): Promise => { - return webnative.account.isUsernameAvailable(username) + return debouncedIsUsernameAvailable(username) } + // interface StateFS { // fs?: FileSystem // }