-
Notifications
You must be signed in to change notification settings - Fork 4
/
pits-and-relations.js
57 lines (48 loc) · 1.35 KB
/
pits-and-relations.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
var fs = require('fs');
var path = require('path');
var schemas = require('histograph-schemas');
var geojsonhint = require('geojsonhint');
var validator = require('is-my-json-valid');
var validators = {
pits: validator(schemas.pits),
relations: validator(schemas.relations)
};
function createWriteStream(type, config) {
return fs.createWriteStream(path.join(config.dataset, config.dataset + '.' + type + '.ndjson'), {
flags: config.truncate === false ? 'r+' : 'w',
encoding: 'utf8',
});
}
module.exports = function(config) {
var streams = {
pits: createWriteStream('pits', config),
relations: createWriteStream('relations', config)
};
this.emit = function(type, obj, callback) {
var jsonValid = validators[type](obj);
var valid = true;
var errors;
if (!jsonValid) {
errors = validators[type].errors;
valid = false;
} else if (type === 'pits' && obj.geometry) {
var geojsonErrors = geojsonhint.hint(obj.geometry);
if (geojsonErrors.length > 0) {
errors = geojsonErrors;
valid = false;
}
}
if (!valid) {
setImmediate(callback, errors);
} else {
streams[type].write(JSON.stringify(obj) + '\n', function() {
callback();
});
}
};
this.close = function() {
streams.pits.close();
streams.relations.close();
};
return this;
};