|
| 1 | +const fs = require('fs'); |
| 2 | +const util = require('./util'); |
| 3 | +const http = require('http'); |
| 4 | +const https = require('https'); |
| 5 | +const querystring = require('querystring'); |
| 6 | + |
| 7 | +class Client { |
| 8 | + constructor(routes) { |
| 9 | + if(!routes) { |
| 10 | + throw new Error("Routes config is required"); |
| 11 | + } |
| 12 | + if(typeof routes == 'string') { |
| 13 | + try { |
| 14 | + routes = JSON.parse(routes); |
| 15 | + } |
| 16 | + catch(e) { |
| 17 | + throw new Error("Error parsing config file", e); |
| 18 | + } |
| 19 | + } |
| 20 | + this.routes = routes; |
| 21 | + this.setupRoutes(); |
| 22 | + } |
| 23 | + |
| 24 | + setupRoutes() { |
| 25 | + let routes = this.routes; |
| 26 | + this.generateApi(routes.api); |
| 27 | + } |
| 28 | + |
| 29 | + generateApi(routes, histRoutes = "") { |
| 30 | + let self = this; |
| 31 | + let parts = histRoutes.split('/'); |
| 32 | + // Nested API, we need up update self to point last object |
| 33 | + if(parts.length > 1) { |
| 34 | + |
| 35 | + for(let i = 1; i < parts.length; i++) { |
| 36 | + self = self[util.toCamelCase(parts[i])]; |
| 37 | + } |
| 38 | + } |
| 39 | + Object.keys(routes).forEach((key) => { |
| 40 | + // Key name will become the intermediate method |
| 41 | + // for all the endpoints |
| 42 | + let sub = routes[key]; |
| 43 | + let curRoute = histRoutes + '/' + key; |
| 44 | + let cur = util.toCamelCase(key); |
| 45 | + if(sub.url) { |
| 46 | + // Consider end of recursion when url is present in sub |
| 47 | + self[cur] = (obj) => { |
| 48 | + return new Promise((resolve, reject) => { |
| 49 | + try { |
| 50 | + let body = this.validateParams(obj, sub.params); |
| 51 | + let options = { |
| 52 | + host: this.routes.defines.constants.host, |
| 53 | + port: this.routes.defines.constants.port, |
| 54 | + path: sub.url, |
| 55 | + method: sub.method, |
| 56 | + headers: { |
| 57 | + 'content-type': sub.contentType || 'application/json' |
| 58 | + } |
| 59 | + }; |
| 60 | + |
| 61 | + // Sets the query parameters on get request |
| 62 | + if(options.method === 'GET') { |
| 63 | + options.path += '?' + querystring.stringify(body); |
| 64 | + } |
| 65 | + |
| 66 | + // User https if api is hosted on https |
| 67 | + let transport = (options.port === 443) ? https: http; |
| 68 | + |
| 69 | + let req = transport.request(options, (res) => { |
| 70 | + res.setEncoding("utf8"); |
| 71 | + let data = ""; |
| 72 | + res.on("data", function(chunk) { |
| 73 | + data += chunk; |
| 74 | + }); |
| 75 | + res.on("error", function(err) { |
| 76 | + console.log('Error occured in http request', err); |
| 77 | + }); |
| 78 | + res.on("end", function() { |
| 79 | + console.log('Request ended'); |
| 80 | + if (res.statusCode >= 400 && res.statusCode < 600 || res.statusCode < 10) { |
| 81 | + reject(new Error(data)); |
| 82 | + } else { |
| 83 | + if(res.headers['content-type'].indexOf('application/json') !== -1) { |
| 84 | + try { |
| 85 | + res.data = JSON.parse(data); |
| 86 | + } |
| 87 | + catch(e) { |
| 88 | + reject(e); |
| 89 | + } |
| 90 | + } |
| 91 | + else |
| 92 | + res.data = data; |
| 93 | + resolve(res); |
| 94 | + } |
| 95 | + }); |
| 96 | + }); |
| 97 | + let hasBody ='get|delete|head'.indexOf(sub.method.toLowerCase()) === -1; |
| 98 | + if(hasBody) { |
| 99 | + console.log('writing to request, ', JSON.stringify(body)); |
| 100 | + req.write(JSON.stringify(body)); |
| 101 | + } |
| 102 | + req.end(); |
| 103 | + } |
| 104 | + catch(e){ |
| 105 | + reject(e); |
| 106 | + } |
| 107 | + }); |
| 108 | + }; |
| 109 | + } |
| 110 | + else { |
| 111 | + // Dig deeper (recursion) |
| 112 | + if(cur.length) |
| 113 | + self[cur] = {}; |
| 114 | + this.generateApi(routes[key], curRoute); |
| 115 | + } |
| 116 | + |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + validateParams(obj, paramsList) { |
| 121 | + // Validates provided parameters with that of |
| 122 | + // required parameters for request |
| 123 | + let params = Object.keys(paramsList); |
| 124 | + |
| 125 | + for( let parameter of params) { |
| 126 | + let def = this.routes.defines.params[parameter]; |
| 127 | + let val = obj[parameter]; |
| 128 | + if(val) { |
| 129 | + if(typeof val != def.type.toLowerCase()) |
| 130 | + throw new Error(parameter + " value incompatible"); |
| 131 | + } |
| 132 | + else if(def.required) { |
| 133 | + throw new Error(parameter + " is required"); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + return obj; |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +module.exports = (config) => { |
| 142 | + return new Client(config); |
| 143 | +}; |
0 commit comments