-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathfauxgrenache.js
More file actions
148 lines (119 loc) · 2.86 KB
/
fauxgrenache.js
File metadata and controls
148 lines (119 loc) · 2.86 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
'use strict'
const http = require('http')
const Link = require('grenache-nodejs-link')
const { getGrapeApiUrl } = require('./utils')
const getRawBody = require('raw-body')
const async = require('async')
class FauxGrenache {
constructor (stubs, grapes, opts = {}) {
this.stubs = stubs
this.grapes = grapes
this.port = opts.port || 1557
this.link = opts.link || null
}
getLink () {
if (this.link) {
return this.link
}
const url = getGrapeApiUrl(this.grapes)
this.link = new Link({
grape: url
})
return this.link
}
start (cb = () => {}) {
return new Promise((resolve, reject) => {
this.link = this.getLink()
async.waterfall([
(next) => {
this.link.start()
next()
},
(next) => {
this.listen(this.port, next)
},
(next) => {
this.announce(this.stubs, next)
}
], (err) => {
if (err) {
reject(err)
cb(err)
return
}
resolve()
cb(null)
})
})
}
stop (cb = () => {}) {
return new Promise((resolve, reject) => {
async.waterfall([
(next) => {
this.stopAnnounces(this.stubs)
next()
},
(next) => {
this.link.stop()
next()
},
(next) => {
this.server.close(next)
}
], (err) => {
if (err) {
reject(err)
cb(err)
return
}
resolve()
cb(null)
})
})
}
listen (port, cb) {
const stubs = this.stubs
// its just tests, so lets use some async/await
this.server = http.createServer(async (req, res) => {
const buf = await getRawBody(req)
const parsed = JSON.parse(buf.toString())
const [id, service, data] = parsed
if (!stubs[service]) {
throw new Error('ERR_TEST_MISSING_STUB')
}
if (!stubs[service][data.action]) {
throw new Error('ERR_TEST_MISSING_STUB_ACTION')
}
function reply (err, data) {
if (err) {
res.end(
`["${id}","ERR_API_BASE: ${err.message}",null]`
)
return
}
const d = JSON.stringify([id, null, data])
res.end(d)
}
data.args.push(reply)
const args = [{}, ...data.args]
stubs[service][data.action].apply(stubs[service], args)
}).listen(port, cb)
}
stopAnnounces (stubs) {
Object.keys(stubs).map((el) => {
this.link.stopAnnouncing(el, this.port)
})
}
announce (stubs, cb) {
const tasks = Object.keys(stubs).map((el) => {
return (cb) => {
this.link.startAnnouncing(el, this.port, cb)
}
})
async.parallel(tasks, cb)
}
}
function fauxGrenache (stubs, grapes, opts) {
return new FauxGrenache(stubs, grapes, opts)
}
module.exports = fauxGrenache