Skip to content

Commit 63ecaa4

Browse files
author
Dom Harrington
committed
Add very basic case for requests sending to metrics server
1 parent ef0a4cb commit 63ecaa4

File tree

4 files changed

+70
-7
lines changed

4 files changed

+70
-7
lines changed

index.js

+24
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,32 @@
1+
const request = require('r2');
2+
const config = require('config');
3+
14
module.exports = (apiKey, group) => {
25
if (!apiKey) throw new Error('You must provide your ReadMe API key');
36
if (!group) throw new Error('You must provide a grouping function');
47

8+
const encoded = Buffer.from(`${apiKey}:`).toString('base64');
9+
510
return (req, res, next) => {
11+
function send() {
12+
request.post(`${config.host}/request`, {
13+
headers: { authorization: `Basic ${encoded}` },
14+
json: { group: group(req) },
15+
});
16+
cleanup();
17+
}
18+
19+
function cleanup() {
20+
res.removeListener('finish', send);
21+
res.removeListener('error', cleanup);
22+
res.removeListener('close', cleanup);
23+
}
24+
25+
// Add response listeners
26+
res.once('finish', send);
27+
res.once('error', cleanup);
28+
res.once('close', cleanup);
29+
630
return next();
731
};
832
};

package-lock.json

+33
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
"version": "0.0.0",
55
"dependencies": {
66
"config": "file:config",
7-
"configly": "^4.1.0"
7+
"configly": "^4.1.0",
8+
"r2": "^2.0.1"
89
},
910
"scripts": {
1011
"lint": "eslint -f unix .",

test/index.test.js

+11-6
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ const apiKey = 'OUW3RlI4gUCwWGpO10srIo2ufdWmMhMH';
1111

1212
describe('@readme/metrics', () => {
1313
before(() => {
14-
nock.disableNetConnect()
14+
nock.disableNetConnect();
1515
nock.enableNetConnect('127.0.0.1');
1616
});
1717
after(() => nock.cleanAll());
@@ -28,11 +28,13 @@ describe('@readme/metrics', () => {
2828
}, 'You must provide a grouping function');
2929
});
3030

31-
it('should send a request to the metrics server', () => {
31+
it('should send a request to the metrics server', function test(done) {
32+
this.timeout(5000);
33+
3234
const group = '5afa21b97011c63320226ef3';
3335

3436
const mock = nock(config.host)
35-
.post('/request', (body) => {
37+
.post('/request', body => {
3638
assert.equal(body.group, group);
3739
return true;
3840
})
@@ -45,9 +47,12 @@ describe('@readme/metrics', () => {
4547
return next();
4648
});
4749
app.use(middleware(apiKey, req => req.user.group));
50+
app.get('/test', (req, res) => res.sendStatus(200));
4851

49-
return request(app)
50-
.get('/test')
51-
.then(() => mock.done());
52+
request(app).get('/test').expect(200).end((err) => {
53+
if (err) return done(err);
54+
mock.done()
55+
return done();
56+
});
5257
});
5358
});

0 commit comments

Comments
 (0)