-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathbase.js
113 lines (96 loc) · 2.57 KB
/
base.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
103
104
105
106
107
108
109
110
111
112
113
/**
* @flow
*/
import Log from '../utils/log'
import {NativeModules, NativeEventEmitter, AsyncStorage} from 'react-native';
const FirestackModule = NativeModules.Firestack;
const FirestackModuleEvt = new NativeEventEmitter(FirestackModule);
import promisify from '../utils/promisify'
let logs = {};
export class Base {
constructor(firestack, options={}) {
this.firestack = firestack;
this.eventHandlers = {};
// Extend custom options with default options
this.options = Object.assign({}, firestack.options, options);
}
// Logger
get log() {
if (!logs[this.namespace]) {
const debug = this.firestack._debug;
logs[this.namespace] = new Log(this.namespace, debug);
}
return logs[this.namespace];
}
_addConstantExports(constants) {
Object.keys(constants).forEach(name => {
FirestackModule[name] = constants[name];
});
}
_addToFirestackInstance(...methods) {
methods.forEach(name => {
this.firestack[name] = this[name].bind(this);
})
}
/**
* app instance
**/
get app() {
return this.firestack.app;
}
whenReady(fn) {
return this.firestack.configurePromise.then(fn);
}
get namespace() {
return 'firestack:base';
}
// Event handlers
// proxy to firestack instance
_on(name, cb, nativeModule) {
return new Promise((resolve) => {
// if (!this.eventHandlers[name]) {
// this.eventHandlers[name] = {};
// }
if (!nativeModule) {
nativeModule = FirestackModuleEvt;
}
const sub = nativeModule.addListener(name, cb);
this.eventHandlers[name] = sub;
resolve(sub);
})
}
_off(name) {
return new Promise((resolve, reject) => {
if (this.eventHandlers[name]) {
const subscription = this.eventHandlers[name];
subscription.remove(); // Remove subscription
delete this.eventHandlers[name];
resolve(subscription)
}
});
}
}
export class ReferenceBase extends Base {
constructor(firestack, path) {
super(firestack);
this.path = Array.isArray(path) ?
path :
(typeof path == 'string' ?
[path] : []);
// sanitize path, just in case
this.path = this.path
.filter(str => str !== "" );
}
get key() {
const path = this.path;
return path.length === 0 ? '/' : path[path.length - 1];
}
pathToString() {
let path = this.path;
let pathStr = (path.length > 0 ? path.join('/') : '/');
if (pathStr[0] != '/') {
pathStr = `/${pathStr}`
}
return pathStr;
}
}