UNPKG

2.77 kBJavaScriptView Raw
1const request = require('request-promise-native');
2const {httpVerbs, requestRegex, replacementRegex} = require('./shared');
3const RequestList = require('./requestList');
4const RequestCache = require('./requestCache');
5
6class Request {
7 constructor(req) {
8 let config = {};
9 this.originalRequest = req;
10
11 Object.keys(req).forEach(k => config[k.toUpperCase()] = req[k]);
12
13 let { REQUEST, ALIAS, PAYLOAD, HOST, PARAMS, HEADERS, DOCUMENTATION } = config;
14 let { verb, endpoint } = this.parseRequest(REQUEST);
15
16 this.VERB = verb;
17 this.ENDPOINT = HOST + endpoint;
18
19 this.HEADERS = HEADERS;
20 this.PAYLOAD = PAYLOAD;
21 this.PARAMS = PARAMS;
22
23 this.ALIAS = ALIAS;
24 this.DOCUMENTATION = DOCUMENTATION;
25
26 if (typeof this.ALIAS === 'undefined') {
27 console.info(`${REQUEST} is missing an alias.`);
28 }
29
30 this.DEPENDENCIES = this.findDependencies(req);
31 }
32
33 parseRequest(request) {
34 let parts = request.match(requestRegex);
35
36 return {
37 verb: parts[1],
38 endpoint: parts[2]
39 };
40 }
41
42 findDependencies(request, set = new Set()) {
43 if (typeof request === 'object') {
44 let keys = Object.keys(request).filter(key => key !== 'ALIAS');
45
46 keys.forEach(key => {
47 set = this.findDependencies(request[key], set);
48 });
49 } else if (typeof request === 'string') {
50 let matches = request.match(replacementRegex) || [];
51 let deps = matches.map(m => m.split('.')[0].substring(1));
52
53 return new Set([...set, ...deps]);
54 }
55
56 return set;
57 }
58
59 async exec(modifiers = [], requestList) {
60 let dependencies = Array.from(this.DEPENDENCIES);
61
62 let cache = await requestList.fetchDependencies(dependencies);
63
64 let settings = {
65 endpoint: cache.parse(this.ENDPOINT),
66 method: this.VERB,
67 headers: cache.parse(this.HEADERS),
68 query: cache.parse(this.PARAMS),
69 payload: cache.parse(this.PAYLOAD)
70 };
71
72 modifiers.forEach(mod => {
73 if (typeof mod.preRequest !== 'undefined') {
74 mod.preRequest(settings, this.originalRequest);
75 }
76 });
77
78 try {
79 let response = await request({
80 url: settings.endpoint,
81 method: settings.method,
82 headers: settings.headers,
83 qs: settings.query,
84 body: settings.payload,
85
86 json: true,
87 simple: false,
88 resolveWithFullResponse: true
89 });
90
91 let results = {
92 request: {
93 headers: response.request.headers,
94 body: response.request.body,
95 endpoint: response.request.uri.href
96 },
97 response: {
98 status: response.statusCode,
99 headers: response.headers,
100 body: response.body
101 },
102 body: response.body
103 };
104
105 cache.add(`$${this.ALIAS}`, results);
106
107 return results;
108 } catch({ error }) {
109 throw new Error(error);
110 }
111 }
112}
113
114module.exports = Request;