/
index.js
87 lines (69 loc) · 1.81 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
var carrier = require('carrier')
var mongodb = require('mongodb')
var morgan = require('morgan')
var stream = require('stream')
var MongoClient = mongodb.MongoClient
var PassThroughStream = stream.PassThrough
module.exports = mongoMorgan
function mongoMorgan(mongodbUrl, format, options) {
var args = Array.prototype.slice.call(arguments);
if (args.length === 0) {
throw new Error('mongodbUrl can not be empty.')
} else if (args.length > 0 && typeof mongodbUrl !== 'string') {
throw new Error('mongodbUrl can not be object, it should be string.')
}
// check format and object
if (typeof format === 'object') {
options = format
format = undefined
}
options = options || {}
var buffer = []
var collection = options.collection || 'request'
// create stream for morgan to write to
var stream = new PassThroughStream()
// create stream to read from
var lineStream = carrier.carry(stream)
lineStream.on('line', onLine)
// create mongo client
var mongoCollection = null
MongoClient.connect(mongodbUrl, onConnect)
// mixin options
options.stream = stream
function onConnect(error, mongoDb) {
if (error) {
throw error
}
mongoDb.collection(collection, {
w: 0
}, function(error, collection) {
mongoCollection = collection
while (buffer.length !== 0) {
var entry = buffer.shift()
mongoCollection.insert(entry)
}
})
}
function onLine(line) {
var entry = {
time: Date.now(),
request: line
}
buffer.push(entry)
if (!mongoCollection) {
return
}
while (buffer.length !== 0) {
entry = buffer.shift()
mongoCollection.insert(entry)
}
}
args = []
if (format) {
args.push(format)
}
if (options) {
args.push(options)
}
return morgan.apply(null, args)
}