This repository has been archived by the owner on Feb 8, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
130 lines (102 loc) · 2.49 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
var stream = require('stream')
, schema = require('./dustmap-upload-schema.json')
, JaySchema = new (require('jayschema'))()
;
module.exports = Payload;
/**
* Constructor & Inheritance
*/
function Payload(opts) {
if (!(this instanceof Payload)) {
return new Payload(opts);
}
stream.Duplex.call(this, opts);
this._ = {
raw : ''
, doc : undefined
, readable : false
};
this.on('finish', parse);
// give it a kick whenever the source is readable
// read(0) will not consume any bytes
this.on('parsed', this.read.bind(this, 0));
return this;
}
Payload.prototype = Object.create( stream.Duplex.prototype, {
constructor: { value: Payload }
});
/**
* Writable Stream implementation
*/
Payload.prototype._write = function(chunk, enc, cb) {
appendRaw.call(this, chunk, enc);
cb();
};
/**
* Readable Stream implementation
*/
Payload.prototype._read = function(size) {
if (! this._.readable) {
return this.push('');
} else {
this.push( JSON.stringify(this._.doc) );
return this.push(null);
}
};
/**
* Public Methods
*/
Payload.prototype.endUpload = function() {
this.addUpload.apply(this, arguments);
return checkDoc.call(this);
};
Payload.prototype.addUpload = function(node, ts, m, replace) {
if (arguments.length < 3)
return;
if (this._.doc === undefined)
this._.doc = {};
var D = this._.doc;
if (! D.hasOwnProperty(node))
D[node] = {};
if (! D[node].hasOwnProperty(ts) || replace)
D[node][ts] = [];
( Array.isArray(m) ? m : [m] ).forEach(function(x){
D[node][ts].push(x);
});
};
/**
* Private Methods and Helper
*/
function parse() {
try {
this._.doc = JSON.parse( this._.raw );
} catch (err) {
return this.emit('error', err);
}
return checkDoc.call(this);
}
function checkDoc() {
/*
* JSON Schema validation
*/
var errors = JaySchema.validate(this._.doc, schema);
if (errors.length)
return this.emit('error', errors);
/*
* More validation checks ... ?
*/
// TODO ...
this._.readable = true;
this.emit('parsed', this._.doc);
return this;
}
function appendRaw(chunk, enc) {
var isBuffer = Buffer.isBuffer(chunk);
if (isBuffer) {
this._.raw += chunk.toString();
} else {
throw new Error(
util.format('got string "%s" and encoding "%s" ... what should i do?', chunk, enc)
);
}
}