-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.tsx
93 lines (82 loc) · 2.23 KB
/
index.tsx
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
export interface PostMessage {
cmd: string;
data: any;
}
interface ListenerHash {
[key: string]: Function;
}
interface WorkerQueryDocumentSnapshot {
id: string;
data: () => any;
exists: boolean;
metadata: { fromCache: boolean; hasPendingWrites: boolean };
}
interface WorkerQuerySnapshot {
docs: WorkerQueryDocumentSnapshot[];
size: number;
empty: boolean;
}
export class FireWorker {
worker: Worker;
listeners: ListenerHash = {};
constructor() {
this.worker = new Worker('./worker.js');
this.worker.addEventListener('message', event => {
let data = event.data.response.data;
if(event.data.response.type === 'QuerySnapshot') {
data.docs = data.docs.map(d => {
const _data = d.data;
d.data = () => _data
return d;
});
}
this.listeners[event.data.name](data);
});
}
initializeApp(opts: any) {
this.worker.postMessage({ cmd: 'initializeApp', data: opts });
return new FireWorkerApp(this);
}
postMessage(message: PostMessage) {
this.worker.postMessage(message);
}
registerListener(namespace: string, callback: any) {
this.listeners[namespace] = callback;
}
}
export class FireWorkerApp {
constructor(private worker: FireWorker) { }
firestore() {
return new FireWorkerFirestore(this.worker);
}
}
export class FireWorkerFirestore {
constructor(private worker: FireWorker) { }
collection(path: string) {
return new FireWorkerFirestoreCol(this.worker, path);
}
}
export class FireWorkerFirestoreCol {
namespace: string;
snapshotNamespace: string;
pathNamespace: string;
constructor(private worker: FireWorker, private path: string) {
this.namespace = `firestore.col`;
this.snapshotNamespace = `${this.namespace}.onSnapshot`;
this.pathNamespace = `${this.namespace}.${path}`;
}
onSnapshot(next: (snap: WorkerQuerySnapshot) => void) {
this.worker.postMessage({
cmd: this.snapshotNamespace,
data: { path: this.path }
});
this.worker.registerListener(`${this.pathNamespace}.onSnapshot`, next);
}
add(data: any) {
this.worker.postMessage({
cmd: `${this.namespace}.add`,
data: { path: this.path, data },
});
}
}
export const firebase = new FireWorker();