-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinvoke
142 lines (117 loc) · 4.72 KB
/
invoke
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
#!/usr/bin/env node
const webServiceInterface = require('@sirensolutions/web-service-interface');
const sinon = require('sinon');
const minimist = require('minimist');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function main() {
const invocationParameters = parseArguments();
await compileTypescript();
const [Service, config] = await getRegistrationInfo(invocationParameters.service);
validateProvidedConfig(config, invocationParameters);
const service = new Service(invocationParameters.config);
validateInputs(service.inputSchema, invocationParameters.inputs);
const results = await service.invoke(invocationParameters.inputs);
validateResultStructure(service.outputConfiguration, results);
console.log(JSON.stringify(results, null, 2));
info(`\nActa Publica documents were fetched`)
}
function parseArguments() {
const args = minimist(process.argv.slice(2));
if (args['-h'] || args['--help'] || args._.length === 0) {
help();
process.exit();
}
if (args._.length !== 1) {
throw new Error('There should only be one positional argument (i.e. the web service to invoke)');
}
const invocationParameters = {
service: args._[0],
inputs: {},
config: {}
};
for (const [arg, value] of Object.entries(args)) {
if (arg.startsWith('input:')) {
invocationParameters.inputs[arg.replace(/^input:/, '')] = value;
} else if (arg.startsWith('config:')) {
invocationParameters.config[arg.replace(/^config:/, '')] = value;
} else if (!['_', 'debug'].includes(arg)) {
throw new Error(`Unexpected argument: --${arg}`);
}
}
return invocationParameters;
}
function help() {
warn('Usage: npm run invoker <service> --input:<input1> <value> --config:<config1> <value>\n');
warn(' Example: npm run invoker ActaPublica --input:query 123456-7890\n');
}
async function compileTypescript() {
try {
await exec('npx gulp compile');
} catch (err) {
err.message = 'Could not compile Typescript:\n\n' + err.stdout + err.stderr;
throw err
}
}
function getRegistrationInfo(serviceName) {
return new Promise((resolve, reject) => {
sinon.stub(webServiceInterface, 'registerServices')
.callsFake((group, serviceClasses, config) => {
const ServiceClass = serviceClasses.find(Service => new Service().name === serviceName);
if (ServiceClass) {
resolve([ServiceClass, config]);
} else {
reject(new Error(`Web service '${serviceName}' not registered. Choose one of [${serviceClasses.map(Service => new Service().name)}]`));
}
});
require('./dist/src');
});
}
function validateProvidedConfig(config, invocationParameters) {
const validation = webServiceInterface.Joi.object(config).validate(invocationParameters.config);
if (validation.error) {
throw new Error(`You must provide a --config:${validation.error.details[0].path} argument`);
}
}
function validateInputs(inputSchema, inputs) {
const errors = [];
Object.entries(inputs).forEach(([param, value]) => {
if (!inputSchema[param]) {
errors.push(`Parameter provided, but is not expected: --input:${param}`);
} else if (inputSchema[param].type === 'text' && typeof value === 'boolean') {
errors.push(`A value must be provided: --input:${param} value`);
} else if (inputSchema[param].type === 'boolean' && typeof value !== 'boolean') {
errors.push(`Must not have value (i.e. must be boolean): --input:${param}`);
} else if (inputSchema[param].type === 'date' && !moment(value).isValid) {
errors.push(`Must be a valid date: --input:${param}`);
}
});
Object.entries(inputSchema)
.filter(([param, paramInfo]) => paramInfo.required && !inputs[param])
.forEach(([param]) => errors.push(`Parameter required, but not provided: --input:${param}`));
if (errors.length) {
throw new Error(`Inputs are invalid:\n ${errors.join('\n ')}`);
}
}
function validateResultStructure(outputConfiguration, results) {
if (!Object.keys(outputConfiguration) === Object.keys(results)) {
throw new Error(`Expected the following keys in the response:\n ${Object.keys(outputConfiguration)}\nBut got:\n ${Object.keys(results)}`);
}
}
function info(string) {
// Using warn so text is output to stderr (stdout reserved for result info)
console.warn(`\x1b[32m${string}\x1b[0m`);
}
function error(string) {
console.error(`\x1b[31m${string}\x1b[0m`);
}
function warn(string) {
console.warn(`\x1b[33m${string}\x1b[0m`);
}
main()
.catch(err => {
if (err instanceof webServiceInterface.WebServiceError) {
err.message = `${err.message}:\n${JSON.stringify(err.data, null, 2)}`;
}
error(process.argv.includes('--debug') ? `${err.stack}\n` : `Error: ${err.message}\n`);
});