forked from pinojs/pino-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pino-mongodb.js
executable file
·76 lines (62 loc) · 1.86 KB
/
pino-mongodb.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
#!/usr/bin/env node
'use strict'
const carrier = require('carrier')
const program = require('commander')
const MongoClient = require('mongodb').MongoClient
const parseMongoUrl = require('muri')
const log = require('./lib/log')
const pkg = require('./package.json')
const makeInsert = require('./lib/makeInsert')
const transport = require('./lib/pino-transport')
module.exports = transport
if (require.main === module) {
// used as cli
cli()
}
function cli () {
program
.version(pkg.version)
.description(pkg.description)
.arguments('[mongo-url]')
.option('-c, --collection <name>', 'database collection', transport.defaultOption.collection)
.option('-o, --stdout', 'output inserted documents into stdout', false)
.option('-e, --errors', 'output insertion errors into stderr', false)
.parse(process.argv)
const cliOptions = program.opts()
const mongoUrl = (program.args[0] || transport.defaultOption.uri)
function handleConnection (e, mClient) {
if (e) {
throw e
}
const dbName = parseMongoUrl(mongoUrl).db
const db = mClient.db(dbName)
const emitter = carrier.carry(process.stdin)
const collection = db.collection(cliOptions.collection)
const insert = makeInsert(cliOptions.errors, cliOptions.stdout)
let insertCounter = 0
const insertCallback = function () {
insertCounter--
if (process.stdin.destroyed && insertCounter === 0) {
mClient.close(process.exit)
}
}
emitter.on('line', (line) => {
insertCounter++
insert(collection, log(line), insertCallback)
})
process.stdin.on('close', () => {
if (insertCounter === 0) {
mClient.close(process.exit)
}
})
process.once('SIGINT', () => {
mClient.close(process.exit)
})
}
const options = {}
MongoClient.connect(
mongoUrl,
options,
handleConnection
)
}