-
Notifications
You must be signed in to change notification settings - Fork 25
/
init.js
102 lines (86 loc) · 2.65 KB
/
init.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
module.exports = init
function init (hoodie) {
// In order to prevent data loss, we want to move all data that has been
// created without an account (e.g. while offline) to the user’s account
// on signin. So before the signin happens, we store the user account’s id
// and data and store it again after the signin
hoodie.account.hook.before('signin', function (options) {
return Promise.all([
hoodie.account.get('id'),
hoodie.store.findAll()
]).then(function (results) {
options.beforeSignin = {
accountId: results[0],
docs: results[1]
}
})
})
hoodie.account.hook.after('signin', function (account, options) {
// when signing in to a newly created account, the account.id does not
// change. The same is true when the user changed their username. In both
// cases there is no need to migrate local data
if (options.beforeSignin.accountId === account.id) {
return hoodie.store.connect()
}
return hoodie.store.reset()
.then(function () {
function migrate (doc) {
doc.createdBy = account.id
delete doc._rev
return doc
}
return hoodie.store.add(options.beforeSignin.docs.map(migrate))
})
.then(function () {
return hoodie.store.connect()
})
})
hoodie.account.hook.before('signout', 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
})
})
hoodie.account.hook.after('signout', function (options) {
return hoodie.store.reset()
})
hoodie.account.on('unauthenticate', hoodie.store.disconnect)
hoodie.account.on('reauthenticate', hoodie.store.connect)
// handle connection status changes
hoodie.connectionStatus.on('disconnect', function () {
hoodie.account.get('session')
.then(function (session) {
if (session) {
hoodie.store.disconnect()
}
})
})
hoodie.connectionStatus.on('reconnect', function () {
hoodie.account.get('session')
.then(function (session) {
if (session) {
hoodie.store.connect()
}
})
})
hoodie.account.get('session')
.then(function (session) {
// signed out
if (!session) {
return
}
// signed in, but session was invalid
if (session.invalid) {
return
}
// hoodie.connectionStatus.ok is false if there is a connection issue
if (hoodie.connectionStatus.ok === false) {
return
}
hoodie.store.connect()
})
}