1 | const Request = require('./request');
|
2 | const RequestCache = require('./requestCache');
|
3 | const httpVerbs = require('./shared').httpVerbs;
|
4 | const requireg = require('requireg');
|
5 |
|
6 | class RequestList {
|
7 | constructor(doc = {}, config = {}) {
|
8 | this.config = config;
|
9 |
|
10 | this.modifiers = this.loadPlugins();
|
11 | this.list = this.loadRequests(doc);
|
12 | this.cache = new RequestCache();
|
13 | }
|
14 |
|
15 | async execByAlias(alias) {
|
16 | let request = this.list.find(r => r.ALIAS === alias);
|
17 |
|
18 | if (typeof request === 'undefined') {
|
19 | return Promise.reject(`${alias} not found among the requests.`);
|
20 | }
|
21 |
|
22 | try {
|
23 | let response = await request.exec(this.modifiers, this);
|
24 |
|
25 | this.modifiers.forEach(mod => {
|
26 | if (typeof mod.postResponse !== 'undefined') {
|
27 | mod.postResponse(response);
|
28 | }
|
29 | });
|
30 |
|
31 | return response;
|
32 | } catch (reason) {
|
33 | throw new Error(
|
34 | `Request: ${request.VERB} ${request.ENDPOINT} FAILED. \n${reason}`
|
35 | );
|
36 | }
|
37 | }
|
38 |
|
39 | async fetchDependencies(dependencies) {
|
40 | dependencies = dependencies.map(d => this.execByAlias(d));
|
41 | await Promise.all(dependencies);
|
42 |
|
43 | return this.cache;
|
44 | }
|
45 |
|
46 | loadRequests(doc) {
|
47 | let requests = Object.keys(doc).filter(key => {
|
48 | let verb = key.split(' ')[0].toUpperCase();
|
49 | return httpVerbs.indexOf(verb) > -1;
|
50 | });
|
51 |
|
52 | return requests.map(request => {
|
53 | let type = typeof doc[request];
|
54 |
|
55 | if (type === 'string') {
|
56 | doc[request] = {
|
57 | ALIAS: doc[request]
|
58 | };
|
59 | }
|
60 |
|
61 | doc[request] = doc[request] || {};
|
62 |
|
63 | doc[request].HOST = this.config.HOST;
|
64 | doc[request].request = request;
|
65 |
|
66 | return new Request(doc[request]);
|
67 | });
|
68 | }
|
69 |
|
70 | loadPlugins() {
|
71 | if (typeof this.config.PLUGINS === 'undefined') {
|
72 | return;
|
73 | }
|
74 |
|
75 | return this.config.PLUGINS.map(plugin => {
|
76 | let name = plugin;
|
77 | let settings = null;
|
78 |
|
79 | if (typeof plugin === 'object') {
|
80 | name = Object.keys(plugin)[0];
|
81 | settings = plugin[name];
|
82 | }
|
83 |
|
84 | return new (requireg(name))(settings);
|
85 | });
|
86 | }
|
87 | }
|
88 |
|
89 | module.exports = RequestList;
|