forked from rdb/svelte-meteor-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
use-session.js
44 lines (37 loc) · 992 Bytes
/
use-session.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
/**
* This function wraps a Meteor Session variable as a Svelte store.
*/
import { Session } from "meteor/session";
import { EJSON } from "meteor/ejson";
let nextId = 1;
const parse = serialized =>
(serialized !== undefined && serialized !== 'undefined')
? EJSON.parse(serialized)
: undefined;
export default function useSession(key, defaultValue) {
if (arguments.length > 1) {
Session.setDefault(key, defaultValue);
}
return {
subscribe(set) {
Session._ensureKey(key);
const dep = Session.keyDeps[key];
if (Object.prototype.hasOwnProperty.call(Session.keys, key)) {
set(parse(Session.keys[key]));
}
const id = `svelte-session-${nextId++}`;
dep._dependentsById[id] = {
_id: id,
invalidate: () => {
set(parse(Session.keys[key]));
},
};
return () => {
delete dep._dependentsById[id];
};
},
set(value) {
Session.set(key, value);
},
};
};