-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·92 lines (78 loc) · 2.34 KB
/
Copy pathindex.js
File metadata and controls
executable file
·92 lines (78 loc) · 2.34 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
#!/usr/bin/env node
const fs = require('fs');
const process = require('process');
const request = require('request');
const Ajv = require('ajv');
const async = require('async');
const chalk = require('chalk');
const protagonist = require('protagonist');
const _ = require('lodash');
const { retrieve, getHost } = require('./specs.js');
const argv = require('optimist').
usage('Usage: $0 -s [schema_file] [-d [data_file]] [-h [host]]').
demand(['s']).argv;
// read blueprint api spec
const specFile = fs.readFileSync(argv.s, {encoding: 'utf8'});
const specJson = protagonist.parseSync(specFile);
// retrieve http specs
const specs = retrieve(specJson.content);
// only generate http specs
if (!argv.d) {
console.log(specs);
return
}
var host = argv.h || getHost(specJson.content);
// parse data
const dataFile = fs.readFileSync(argv.d, {encoding: 'utf8'});
const reqData = JSON.parse(dataFile);
const ajv = new Ajv();
// test requests
async.eachSeries(reqData, (r, cb) => {
const spec = _.find(specs, s => s.url === r.url &&
s.method === r.method);
if (!spec) {
console.log(chalk.yellow(`[SKIP] ${r.title} ==> SPEC NOT FOUND`));
return cb();
}
// interpolate path param
var path = _.reduce(r.params, (p, v, k) => p.replace(`{${k}}`, v),
spec.url).replace(/{|}/g, '');
var query = '';
// interpolate query params
var paths = path.split('?');
if (paths.length > 1) {
path = paths[0];
query = _.chain(paths[1]).split(',').
map(q => [q, _.get(r.params, q)]).
filter(x => !!x[1]).
map(x => `${x[0]}=${encodeURIComponent(x[1])}`).
join('&').
value();
}
var url = `${host}${path}${query?'?'+query:''}`;
request({
method: spec.method,
url: url,
headers: r.headers,
body: r.body ? JSON.stringify(r.body): undefined
}, (err, res, body) => {
console.log(chalk.gray(`${spec.method} ${url}`));
// check status code
if (_.get(res, 'statusCode') !== 200) {
return cb(`non 200 response status:${body}`);
}
if (spec.schema) {
var valid = ajv.validate(spec.schema, JSON.parse(body))
if (!valid) {
return cb(ajv.errors);
}
}
console.log(chalk.green(' ===> OK'));
cb();
});
}, err => {
if (err) {
console.log(chalk.red('Failed: ', JSON.stringify(err)));
process.exit(1);
}
});