hoodiehq / hoodie-account-client

:dog: Account client API for the browser
https://hoodiehq.github.io/hoodie-account-client
Apache License 2.0
11 stars 24 forks source link

replace undocumented `pre:{signin,signout}` and `post:{signin,signout}` events with a hook API for `signin` and `signout` #124

Open gr2m opened 7 years ago

gr2m commented 7 years ago

📋 part of https://github.com/hoodiehq/camp/issues/101


Hoodie client needs to do some asynchronous cross-module initialisation, see https://github.com/hoodiehq/hoodie-client/issues/3. Tradition events did not work for us as we for example need to be able to intercept a signout if the user has local changes and sync did fail.

For a lack of better alternatives, we introduced hidden events that pass options.hooks that can be used to add promises which have to be resolved before the actual method gets executed.

Example:

hoodie.account.on('pre:signout', function (options) {
  options.hooks.push(function () {
    return hoodie.store.push().catch(function (error) {
      if (error.status !== 401) { throw error }

      error.message = 'Local changes could not be synced, sign in first'
      throw error
    })
  })
})

Based on the discussion at https://github.com/hoodiehq/hoodie-client/issues/42 I created before-after-hook with which we can change the above to

hoodie.account.hook.before('signout', function (options) {
  return hoodie.store.push().catch(function (error) {
    if (error.status !== 401) { throw error }

    error.message = 'Local changes could not be synced, sign in first'
    throw error
  })
})