forked from urish/firebase-server
/
index.js
93 lines (78 loc) · 2.18 KB
/
index.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
/*
* firebase-server 0.1.0
* License: MIT.
* Copyright (C) 2013, 2014, Uri Shaked.
*/
'use strict';
var WebSocketServer = require('ws').Server;
var mockfirebase = require('mockfirebase');
var loggingEnabled = false;
function _log(message) {
if (loggingEnabled) {
console.log('[firebase-server] ' + message);
}
}
function FirebaseServer(port, name, data) {
this.name = name || 'mock.firebase.server';
this.mockFb = new mockfirebase.MockFirebase('https://' + this.name + '/', data);
this._wss = new WebSocketServer({
port: port
});
this._wss.on('connection', this.handleConnection.bind(this));
_log('Listening for connections on port ' + port);
}
FirebaseServer.prototype = {
handleConnection: function (ws) {
_log('New connection from ' + ws._socket.remoteAddress + ':' + ws._socket.remotePort);
function send(message) {
var payload = JSON.stringify(message);
_log('Sending message: ' + payload);
try {
ws.send(payload);
} catch (e) {
_log('Send failed: ' + e);
}
}
ws.on('message', function (data) {
_log('Client message: ' + data);
if (data === 0) {
return;
}
var parsed = JSON.parse(data);
if (parsed.t === 'd') {
var path = parsed.d.b.p.substr(1);
var requestId = parsed.d.r;
var fbRef = path ? this.mockFb.child(path) : this.mockFb;
if (parsed.d.a === 'l' || parsed.d.a === 'q') {
_log('Client listen ' + path);
// listen
send({d: {r: requestId, b: {s: 'ok', d: ''}}, t: 'd'});
fbRef.on('value', function (snap) {
if (snap.val()) {
send({d: {a: 'd', b: {p: path, d: snap.val(), t: null}}, t: 'd'});
}
});
}
if (parsed.d.a === 'p') {
_log('Client update ' + path);
fbRef.set(parsed.d.b.d, function () {
// TODO check for failure
send({d: {r: requestId, b: {s: 'ok', d: ''}}, t: 'd'});
});
}
this.mockFb.flush();
}
}.bind(this));
send({d: { t: 'h', d: {ts: new Date().getTime(), v: '5', h: this.name, s: ''}}, t: 'c' });
},
getData: function() {
return this.mockFb.getData();
},
close: function() {
this._wss.close();
}
};
FirebaseServer.enableLogging = function (value) {
loggingEnabled = value;
};
module.exports = FirebaseServer;