-
-
Notifications
You must be signed in to change notification settings - Fork 328
/
Copy pathform-preserve.js
80 lines (69 loc) · 2 KB
/
form-preserve.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
/* global Package */
import { EJSON } from 'meteor/ejson'
/**
* Internal helper object to preserve form inputs across Hot Code Push
* and across "pages" navigation if the option is enabled.
*/
export class FormPreserve {
/**
* @constructor
* @param {String} migrationName
*/
constructor (migrationName) {
const self = this
if (typeof migrationName !== 'string') {
throw Error('You must define an unique migration name of type String')
}
self.registeredForms = {}
self.retrievedDocuments = {}
if (Package.reload) {
const Reload = Package.reload.Reload
self.retrievedDocuments = Reload._migrationData(migrationName) || '{}'
// Currently migration does not seem to support proper storage
// of Date type. It comes back as a string, so we need to store
// EJSON instead.
if (typeof self.retrievedDocuments === 'string') {
self.retrievedDocuments = EJSON.parse(self.retrievedDocuments)
}
Reload._onMigrate(migrationName, function () {
const doc = self._retrieveRegisteredDocuments()
return [true, EJSON.stringify(doc)]
})
}
}
getDocument (formId) {
const self = this
if (!(formId in self.retrievedDocuments)) {
return false
}
return self.retrievedDocuments[formId]
}
clearDocument (formId) {
delete this.retrievedDocuments[formId]
}
registerForm (formId, retrieveFunc) {
this.registeredForms[formId] = retrieveFunc
}
formIsRegistered (formId) {
return !!this.registeredForms[formId]
}
unregisterForm (formId) {
delete this.registeredForms[formId]
delete this.retrievedDocuments[formId]
}
unregisterAllForms () {
const self = this
self.registeredForms = {}
self.retrievedDocuments = {}
}
_retrieveRegisteredDocuments () {
const self = this
const res = {}
Object
.entries(self.registeredForms)
.forEach(function ([formId, retrieveFunc]) {
res[formId] = retrieveFunc()
})
return res
}
}