forked from mongodb-js/mongodb-schema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (59 loc) · 1.91 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
var stream = require('./stream');
var es = require('event-stream');
// var debug = require('debug')('mongodb-schema:wrapper');
/**
* Convenience shortcut for parsing schemas. Accepts an array, stream or
* MongoDB cursor object to parse documents from.
*
* @param {Cursor|Array|Stream} docs An array, a cursor, or a stream
*
* @param {Object} options options (optional)
* @param {Boolean} options.semanticTypes enable semantic type detection (default: false)
* @param {Boolean} options.storeValues enable storing of values (default: true)
*
* @param {Function} callback Callback which will be passed `(err, schema)`
* @return {Promise} You can await promise, or use callback if provided.
*/
module.exports = function(docs, options, callback) {
const promise = new Promise((resolve, reject) => {
// shift parameters if no options are specified
if (typeof options === 'undefined' || (typeof options === 'function' && typeof callback === 'undefined')) {
callback = options;
options = {};
}
var src;
// MongoDB Cursors
if (docs.stream && typeof docs.stream === 'function') {
src = docs.stream();
// Streams
} else if (docs.pipe && typeof docs.pipe === 'function') {
src = docs;
// Arrays
} else if (Array.isArray(docs)) {
src = es.readArray(docs);
} else {
reject(new Error(
'Unknown input type for `docs`. Must be an array, ' +
'stream or MongoDB Cursor.'
));
return;
}
var result;
src
.pipe(stream(options))
.on('data', function(data) {
result = data;
})
.on('error', function(err) {
reject(err);
})
.on('end', function() {
resolve(result);
});
});
if (callback && typeof callback === 'function') {
promise.then(callback.bind(null, null), callback);
}
return promise;
};
module.exports.stream = stream;