mockapi-msi 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.dockerignore ADDED
@@ -0,0 +1,24 @@
1
+ **/.classpath
2
+ **/.dockerignore
3
+ **/.env
4
+ **/.git
5
+ **/.gitignore
6
+ **/.project
7
+ **/.settings
8
+ **/.toolstarget
9
+ **/.vs
10
+ **/.vscode
11
+ **/*.*proj.user
12
+ **/*.dbmdl
13
+ **/*.jfm
14
+ **/azds.yaml
15
+ **/charts
16
+ **/docker-compose*
17
+ **/compose*
18
+ **/Dockerfile*
19
+ **/node_modules
20
+ **/npm-debug.log
21
+ **/obj
22
+ **/secrets.dev.yaml
23
+ **/values.dev.yaml
24
+ README.md
@@ -0,0 +1,47 @@
1
+
2
+ # basic Mock API configuration
3
+ port: 8001
4
+ enableCors: true
5
+ #externalModulesPath: "../apiHandlers/"
6
+
7
+ # dummy example configurations
8
+ # PATH must point to a existing CSV file
9
+ # 3 native readers are supported: text | csv | folder
10
+ data:
11
+ myRows:
12
+ path: "./testdata/data.csv"
13
+ reader: csv
14
+ properties:
15
+ - json
16
+ - seq
17
+ - 0
18
+ #options
19
+ #json || text
20
+ #seq || rand
21
+ #-1 = return every record on every request
22
+ #0...n starting index (always reset to 0 when reach EOR)
23
+
24
+ # custom http response handlers section
25
+ #customHandlers:
26
+ # "custom":
27
+ # "myCustomHandler"
28
+
29
+ # Mock API available endpoints, return types and
30
+ # general configuration
31
+ # verb: any | get | post | delete | ...
32
+ # data: refers to previously configured data and readers
33
+ # responseStatus: 200 | 404 | 500 | ...
34
+ # responseContentType: any MIME available type
35
+ # handler: refers to any previously configured custom handler
36
+ endpoints:
37
+ "/data":
38
+ verb: get
39
+ data: myRows
40
+ responseStatus: 200
41
+ responseContentType: "application/json"
42
+
43
+ log: verbose
44
+ #debug
45
+ #error
46
+ #verbose
47
+ #none
package/Dockerfile ADDED
@@ -0,0 +1,8 @@
1
+ FROM node:12.18-alpine
2
+ ENV NODE_ENV=production
3
+ WORKDIR /usr/src/app
4
+ COPY ["package.json", "package-lock.json*", "npm-shrinkwrap.json*", "./"]
5
+ RUN npm install --production --silent && mv node_modules ../
6
+ COPY . .
7
+ EXPOSE 8001
8
+ CMD ["node", "main.js"]
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,95 @@
1
+ # Dynamic mocking descriptive API (MockAPI)
2
+
3
+ MockAPI help you buiding your app when requires connecting to a not yet built external API.
4
+
5
+ MockAPI let you create fake responses with pre defined and dynamic data for defined endpoints.
6
+
7
+ MockAPI also is intended to help you when, during testing phase, you cannot afford complex and expensive products (And you do not need them) that requires bulky configuration steps or depends directly on third party providers that you cannot control.
8
+
9
+ ## Configuration file
10
+
11
+ MockAPI can be used as it is. Without any additional coding activity. Just configure your endpoints and run ```main.js``` file.
12
+
13
+ ### Configuring MockAPI
14
+
15
+ Edit ```.mockapi-config``` to add your own endpoints, responses, parsers and data. Use standard YAML notation for this file.
16
+
17
+ #### Main entry points
18
+
19
+ **port** - Specify the HTTP port to be used by MockAPI to expose the defined endpoints.
20
+
21
+ **enableCors** - Enable/Disable CORS for MockAPI.
22
+
23
+ **externalModulesPath** - Optional configuration. Allows to specify a different path where the user custom handlers are located.
24
+
25
+ **data** -
26
+ Holds and describe the available data for all endpoints and responses.
27
+
28
+ **endpoints** - Describe all available endpoints, its verbs and responses.
29
+
30
+ **log** - Define MockAPI log level.
31
+
32
+ **customHandlers** - Import a custom HTTP data handler. Use these custom handlers to manipulate the output of your responses for a particular endpoint.
33
+
34
+ Within ```data``` entry, it is possible to define how the data must be handled. There are three built-in readers that comes with MockAPI.
35
+
36
+ **csv** - Reads the defined data as CSV.
37
+
38
+ **text** - Considers the data source as plain text.
39
+
40
+ **folder** - Reads the files from the folder matching the incoming request name.
41
+
42
+ #### Data definition
43
+
44
+ ```yaml
45
+ myRows:
46
+ path: "./testdata/data.csv"
47
+ reader: csv
48
+ properties:
49
+ - json
50
+ - seq
51
+ - 0
52
+ ```
53
+ The previous example defines a data source called ```myRows```, which will read the data from the defined ```path```, using the ```csv``` handler, parsing each row as ```json```, reading the values in a ```sequential``` order, starting from record ```0```.
54
+
55
+ #### Endpoint definition
56
+
57
+ ```yaml
58
+ "/users":
59
+ verb: get
60
+ data: myRows
61
+ responseStatus: 200
62
+ responseContentType: "application/json"
63
+ ```
64
+ From the previous code snippet, we are defining an endpoint ```[MockAPI URL]:[PORT]/users```, which will accept ```get``` requests, answering always with ```200``` status code, using data from ```myRows``` data definition in ```JSON``` format.
65
+
66
+ #### Custom handlers
67
+
68
+ A custom handler let you manipulate the data as your will. First, define the handler as follows:
69
+
70
+ ```yaml
71
+ customHandlers:
72
+ "custom":
73
+ "myCustomHandler"
74
+ ```
75
+ The previous code defines a custom handler called ```custom``` and will use the script code called ```myCustomHandler```. The custom code must be placed inside of ```scripts``` folder and coded in JavaScript with NodeJS support.
76
+
77
+ Your custom script must implement the following export format:
78
+
79
+ ```javascript
80
+ module.exports = {
81
+ process: [Your function entry point]
82
+ };
83
+ ```
84
+
85
+ #### Setting up the log level
86
+
87
+ MockAPI logs information into the execution console. There are different levels of logs that can be used.
88
+
89
+ ```yaml
90
+ log: verbose
91
+ #debug <- Useful for custom handlers
92
+ #error <- Only exposes internal errors
93
+ #verbose <- Logs debug, information and errors
94
+ #none <- Turn off the logs
95
+ ```
@@ -0,0 +1,9 @@
1
+ const action = function (requestInformation, data) {
2
+ console.log(data);
3
+ console.log(requestInformation);
4
+ return JSON.stringify("Hello from custom module");
5
+ };
6
+
7
+ module.exports = {
8
+ process: action
9
+ };
@@ -0,0 +1,14 @@
1
+ version: '3.4'
2
+
3
+ services:
4
+ mockapi:
5
+ image: mockapi
6
+ build:
7
+ context: .
8
+ dockerfile: ./Dockerfile
9
+ environment:
10
+ NODE_ENV: development
11
+ ports:
12
+ - 3000:3000
13
+ - 9229:9229
14
+ command: ["node", "--inspect=0.0.0.0:9229", "main.js"]
@@ -0,0 +1,12 @@
1
+ version: '3.4'
2
+
3
+ services:
4
+ mockapi:
5
+ image: mockapi
6
+ build:
7
+ context: .
8
+ dockerfile: ./Dockerfile
9
+ environment:
10
+ NODE_ENV: production
11
+ ports:
12
+ - 3001:8001
package/main.js ADDED
@@ -0,0 +1,108 @@
1
+ const http = require('http');
2
+ const LOG = require('./modules/log');
3
+ const YAML = require('yaml');
4
+ const constants = require('./modules/constants');
5
+ const readers = require('./modules/readers');
6
+ const parser = require('./modules/urlParser');
7
+ const handlerInjector = require('./modules/configurationParser');
8
+ const ModuleProxy = require('./modules/moduleProxy')
9
+
10
+ const rootPath = __dirname;
11
+ const configFile = readers.text_reader(`${rootPath}/${constants.CONFIG_FILE_NAME}`);
12
+ const parsedConfiguration = YAML.parse(configFile());
13
+
14
+ if (parsedConfiguration.port === undefined) throw new Error("port property is required");
15
+
16
+ const port = parsedConfiguration.port;
17
+ const enableCors = parsedConfiguration.enableCors;
18
+ const endpointList = parsedConfiguration.endpoints;
19
+ const logLevel = parsedConfiguration.log || constants.LOG_LEVELS.ALL;
20
+ const log = new LOG(logLevel);
21
+ const moduleProxy = new ModuleProxy(parsedConfiguration.externalModulesPath || constants.EXTERNAL_MODULES_PATH, log);
22
+
23
+ if (parsedConfiguration.customHandlers !== undefined) {
24
+ moduleProxy.load(parsedConfiguration.customHandlers);
25
+ }
26
+
27
+ let data = parsedConfiguration.data || { };
28
+ handlerInjector.loadHandlersFromConfiguration(data);
29
+
30
+ log.message(``);
31
+ log.message(`Mock API configuration:`);
32
+ log.message(` PORT: ${constants.COLOR.fgGreen}${port}${constants.COLOR.reset}`);
33
+ log.message(` CORS enabled: ${enableCors ? constants.COLOR.fgGreen : constants.COLOR.fgRed}${enableCors}${constants.COLOR.reset}`);
34
+ log.message(``);
35
+
36
+ log.message(`> Mock API attempting to use port: ${constants.COLOR.fgRed}${port}${constants.COLOR.reset}`)
37
+
38
+ http.createServer((request, response) => {
39
+ let bodyPayload = [];
40
+
41
+ request.on('data', (chunk) => {
42
+ bodyPayload.push(chunk);
43
+ }).on('end', () => {
44
+ bodyPayload = Buffer.concat(bodyPayload).toString();
45
+
46
+ const urlInformation = parser.parse(request.url);
47
+
48
+ log.info(`Requesting: ${urlInformation.base} - Verb: ${request.method}`);
49
+
50
+ if (bodyPayload !== '') {
51
+ log.info(`Incoming body: ${bodyPayload}`);
52
+ }
53
+
54
+ let actionFound = false;
55
+ let responseBody = null;
56
+ let responseStatus = null;
57
+ let contentType = null;
58
+
59
+ for (const endpointUrl in endpointList) {
60
+ if (Object.hasOwnProperty.call(endpointList, endpointUrl)) {
61
+ const endpoint = endpointList[endpointUrl];
62
+ const requestMethod = request.method.toLowerCase();
63
+
64
+ if (endpointUrl === urlInformation.base && (endpoint.verb === "any" || endpoint.verb.toLowerCase() === requestMethod)) {
65
+
66
+ if (endpoint.data !== undefined && data[endpoint.data] === undefined) {
67
+ log.error("No matching data variable for this request");
68
+ break;
69
+ }
70
+
71
+ actionFound = true;
72
+ contentType = endpoint.responseContentType;
73
+
74
+ try {
75
+ const processData = endpoint.data === undefined ? "" : data[endpoint.data].dataHandler(urlInformation);
76
+
77
+ responseBody = endpoint.handler !== undefined ?
78
+ moduleProxy.execute(endpoint.handler, { method: requestMethod, url: endpointUrl, body: bodyPayload }, processData) :
79
+ processData;
80
+
81
+ responseStatus = endpoint.responseStatus;
82
+ } catch(ex) {
83
+ log.error(`${ex.message}`);
84
+
85
+ responseStatus = ex.httpStatusCode;
86
+ responseBody = ex.message;
87
+ }
88
+
89
+ break;
90
+ }
91
+ }
92
+ }
93
+
94
+ response.statusCode = responseStatus ||
95
+ (!actionFound ?
96
+ constants.HTTP_STATUS_CODES.NOT_FOUND :
97
+ constants.HTTP_STATUS_CODES.OK);
98
+
99
+ response.setHeader('Content-Type', contentType || constants.DEFAULT_CONTENT_TYPE);
100
+
101
+ enableCors && response.setHeader('Access-Control-Allow-Origin', '*');
102
+
103
+ response.end(responseBody);
104
+ });
105
+ }).listen(port);
106
+
107
+ log.message(`> Mock API listening on port: ${constants.COLOR.fgGreen}${port}${constants.COLOR.reset}`)
108
+ log.message(``);
@@ -0,0 +1,31 @@
1
+ function HttpException(httpStatusCode, message) {
2
+ var instance = new Error(message);
3
+
4
+ instance.name = 'HttpException';
5
+ instance.httpStatusCode = httpStatusCode;
6
+
7
+ Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
8
+
9
+ if (Error.captureStackTrace) {
10
+ Error.captureStackTrace(instance, HttpException);
11
+ }
12
+
13
+ return instance;
14
+ }
15
+
16
+ HttpException.prototype = Object.create(Error.prototype, {
17
+ constructor: {
18
+ value: Error,
19
+ enumerable: false,
20
+ writable: true,
21
+ configurable: true
22
+ }
23
+ });
24
+
25
+ if (Object.setPrototypeOf){
26
+ Object.setPrototypeOf(HttpException, Error);
27
+ } else {
28
+ HttpException.__proto__ = Error;
29
+ }
30
+
31
+ module.exports = HttpException;
@@ -0,0 +1,44 @@
1
+ const readers = require("./readers");
2
+
3
+ const parseProperties = function (properties) {
4
+ let property = {
5
+ startIndex: 0,
6
+ format: "json",
7
+ direction: "rand"
8
+ };
9
+
10
+ if (properties === undefined) return property;
11
+
12
+ const props = properties;
13
+
14
+ if (props.length < 3) throw new Error("Invalid properties");
15
+ if (isNaN(props[2])) throw new Error("Index must be a number");
16
+
17
+ property.startIndex = parseFloat(props[2]);
18
+ property.format = props[0];
19
+ property.direction = props[1];
20
+
21
+ return property;
22
+ }
23
+
24
+ const injectHandlers = function (data) {
25
+
26
+ for (const variable in data) {
27
+ if (Object.hasOwnProperty.call(data, variable)) {
28
+ const node = data[variable];
29
+
30
+ if (node.path === undefined) throw new Error("Node requires a path");
31
+ if (node.reader === undefined) throw new Error("Node requires a reader");
32
+ if (readers[node.reader + "_reader"] === undefined) throw new Error("Selected reader cannot be found");
33
+
34
+ const properties = parseProperties(node.properties);
35
+
36
+ const nodeHandler = readers[node.reader + "_reader"];
37
+ node.dataHandler = nodeHandler(node.path, properties);
38
+ }
39
+ }
40
+ };
41
+
42
+ module.exports = {
43
+ loadHandlersFromConfiguration: injectHandlers
44
+ }
@@ -0,0 +1,96 @@
1
+ module.exports = {
2
+ BASE_URL: "http://localhost",
3
+ CONFIG_FILE_NAME: ".mockapi-config",
4
+ LOG_LEVELS: {
5
+ DEBUG: "debug",
6
+ ERROR: "error",
7
+ VERBOSE: "verbose",
8
+ NONE: "none"
9
+ },
10
+ EXTERNAL_MODULES_PATH: "../apiHandlers/",
11
+ DEFAULT_CONTENT_TYPE: "text/plain",
12
+ HTTP_STATUS_CODES: {
13
+ CONTINUE :100,
14
+ SWITCHING_PROTOCOLS :101,
15
+ PROCESSING :102,
16
+ OK :200,
17
+ CREATED :201,
18
+ ACCEPTED :202,
19
+ NON_AUTHORITATIVE_INFORMATION :203,
20
+ NO_CONTENT :204,
21
+ RESET_CONTENT :205,
22
+ PARTIAL_CONTENT :206,
23
+ MULTI_STATUS :207,
24
+ MULTIPLE_CHOICES :300,
25
+ MOVED_PERMANENTLY :301,
26
+ MOVED_TEMPORARILY :302,
27
+ SEE_OTHER :303,
28
+ NOT_MODIFIED :304,
29
+ USE_PROXY :305,
30
+ TEMPORARY_REDIRECT :307,
31
+ PERMANENT_REDIRECT :308,
32
+ BAD_REQUEST :400,
33
+ UNAUTHORIZED :401,
34
+ PAYMENT_REQUIRED :402,
35
+ FORBIDDEN :403,
36
+ NOT_FOUND :404,
37
+ METHOD_NOT_ALLOWED :405,
38
+ NOT_ACCEPTABLE :406,
39
+ PROXY_AUTHENTICATION_REQUIRED :407,
40
+ REQUEST_TIMEOUT :408,
41
+ CONFLICT :409,
42
+ GONE :410,
43
+ LENGTH_REQUIRED :411,
44
+ PRECONDITION_FAILED :412,
45
+ REQUEST_TOO_LONG :413,
46
+ REQUEST_URI_TOO_LONG :414,
47
+ UNSUPPORTED_MEDIA_TYPE :415,
48
+ REQUESTED_RANGE_NOT_SATISFIABLE :416,
49
+ EXPECTATION_FAILED :417,
50
+ IM_A_TEAPOT :418,
51
+ INSUFFICIENT_SPACE_ON_RESOURCE :419,
52
+ METHOD_FAILURE :420,
53
+ UNPROCESSABLE_ENTITY :422,
54
+ LOCKED :423,
55
+ FAILED_DEPENDENCY :424,
56
+ PRECONDITION_REQUIRED :428,
57
+ TOO_MANY_REQUESTS :429,
58
+ REQUEST_HEADER_FIELDS_TOO_LARGE :431,
59
+ UNAVAILABLE_FOR_LEGAL_REASONS :451,
60
+ INTERNAL_SERVER_ERROR :500,
61
+ NOT_IMPLEMENTED :501,
62
+ BAD_GATEWAY :502,
63
+ SERVICE_UNAVAILABLE :503,
64
+ GATEWAY_TIMEOUT :504,
65
+ HTTP_VERSION_NOT_SUPPORTED :505,
66
+ INSUFFICIENT_STORAGE :507,
67
+ NETWORK_AUTHENTICATION_REQUIRED :511
68
+ },
69
+ COLOR: {
70
+ reset: '\x1b[0m',
71
+ bright: '\x1b[1m',
72
+ dim: '\x1b[2m',
73
+ underscore: '\x1b[4m',
74
+ blink: '\x1b[5m',
75
+ reverse: '\x1b[7m',
76
+ hidden: '\x1b[8m',
77
+
78
+ fgBlack: '\x1b[30m',
79
+ fgRed: '\x1b[31m',
80
+ fgGreen: '\x1b[32m',
81
+ fgYellow: '\x1b[33m',
82
+ fgBlue: '\x1b[34m',
83
+ fgMagenta: '\x1b[35m',
84
+ fgCyan: '\x1b[36m',
85
+ fgWhite: '\x1b[37m',
86
+
87
+ bgBlack: '\x1b[40m',
88
+ bgRed: '\x1b[41m',
89
+ bgGreen: '\x1b[42m',
90
+ bgYellow: '\x1b[43m',
91
+ bgBlue: '\x1b[44m',
92
+ bgMagenta: '\x1b[45m',
93
+ bgCyan: '\x1b[46m',
94
+ bgWhite: '\x1b[47m'
95
+ }
96
+ };
package/modules/csv.js ADDED
@@ -0,0 +1,78 @@
1
+ let CSV = function (content, properties) {
2
+ this._content = content;
3
+ this._properties = properties;
4
+ this._currentIndex = properties.startIndex;
5
+ this._data = this._readData();
6
+ this._formattedData = [];
7
+
8
+ this["_" + properties.format]();
9
+ };
10
+
11
+ CSV.prototype._readData = function () {
12
+ let data = [];
13
+ const lines = this._content.split("\r\n");
14
+
15
+ for (let index = 0; index < lines.length; index++) {
16
+ const line = lines[index];
17
+ const extractedLine = line.match(/(?:,|\n|^)("(?:(?:"")*[^"]*)*"|[^",\n]*|(?:\n|$))/gm);
18
+
19
+ let parsedLine = [];
20
+
21
+ for (let i = 0; i < extractedLine.length; i++) {
22
+ const item = extractedLine[i];
23
+ parsedLine.push(item);
24
+ }
25
+
26
+ data.push(parsedLine);
27
+ }
28
+
29
+ return data;
30
+ };
31
+
32
+ CSV.prototype._json = function () {
33
+ if (this._data.length === 0) return;
34
+
35
+ const propertyNames = this._data[0];
36
+
37
+ for (let i = 1; i < this._data.length; i++) {
38
+ const record = this._data[i];
39
+ let obj = { };
40
+
41
+ for (let j = 0; j < record.length; j++) {
42
+ const data = record[j];
43
+ obj[propertyNames[j]] = data;
44
+ }
45
+
46
+ this._formattedData.push(obj);
47
+ }
48
+ };
49
+
50
+ CSV.prototype._text = function () {
51
+ this._formattedData = this._data.slice(1);
52
+ };
53
+
54
+ CSV.prototype._seq = function() {
55
+ if (this._currentIndex >= this._formattedData.length || this._currentIndex < 0) this._currentIndex = 0;
56
+
57
+ const record = this._formattedData[this._currentIndex];
58
+ this._currentIndex++;
59
+
60
+ return record;
61
+ };
62
+
63
+ CSV.prototype._rand = function() {
64
+ this._currentIndex = parseInt((Math.random() * this._formattedData.length - 1) + 1);
65
+ const record = this._formattedData[this._currentIndex];
66
+
67
+ return record;
68
+ };
69
+
70
+ CSV.prototype.read = function () {
71
+ if (this._currentIndex === -1) {
72
+ return JSON.stringify(this._formattedData);
73
+ }
74
+
75
+ return JSON.stringify(this["_" + this._properties.direction]());
76
+ };
77
+
78
+ module.exports = CSV;
package/modules/log.js ADDED
@@ -0,0 +1,39 @@
1
+ const constants = require("./constants");
2
+
3
+ const Log = function(logLevel) {
4
+ this._logLevel = logLevel || "verbose";
5
+ };
6
+
7
+ Log.prototype._write = function (message) {
8
+ const date = (new Date()).toString();
9
+
10
+ console.log(`${date} ${message}`);
11
+ };
12
+
13
+ Log.prototype.debug = function (message) {
14
+ if (this._logLevel === constants.LOG_LEVELS.DEBUG || this._logLevel === constants.LOG_LEVELS.VERBOSE) {
15
+ this._write(`${constants.COLOR.fgYellow}[DEBUG]${constants.COLOR.reset} - ${message}`);
16
+ }
17
+ };
18
+
19
+ Log.prototype.error = function (message) {
20
+ if (this._logLevel === constants.LOG_LEVELS.ERROR || this._logLevel === constants.LOG_LEVELS.VERBOSE) {
21
+ this._write(`${constants.COLOR.fgRed}[ERROR]${constants.COLOR.reset} - ${message}`);
22
+ }
23
+ };
24
+
25
+ Log.prototype.info = function (message) {
26
+ if (this._logLevel === constants.LOG_LEVELS.VERBOSE) {
27
+ this._write(`${constants.COLOR.fgYellow}[INFO]${constants.COLOR.reset} - ${message}`);
28
+ }
29
+ };
30
+
31
+ Log.prototype.detail = function (message) {
32
+ if (this._logLevel === constants.LOG_LEVELS.VERBOSE) {
33
+ this._write(`${message}`);
34
+ }
35
+ };
36
+
37
+ Log.prototype.message = (message) => console.log(message);
38
+
39
+ module.exports = Log;
@@ -0,0 +1,55 @@
1
+ const constants = require("./constants");
2
+ const HttpException = require('./HttpException');
3
+
4
+ class Proxy {
5
+
6
+ _externalModuleList = {};
7
+
8
+ constructor(externalModulePath, logger) {
9
+ this._externalModuleList = {};
10
+ this._logger = logger;
11
+ this._externalModulePath = externalModulePath;
12
+ }
13
+
14
+ async load(modules) {
15
+ for (const moduleName in modules) {
16
+ if (Object.hasOwnProperty.call(modules, moduleName)) {
17
+ const moduleFileName = modules[moduleName];
18
+
19
+ try {
20
+ const modulePath = `${this._externalModulePath}${moduleFileName}.js`;
21
+
22
+ this._logger.info(`Attempting to load module ${moduleName} from ${modulePath}`);
23
+
24
+ const module = await import(modulePath);
25
+
26
+ this._externalModuleList[moduleName] = module;
27
+
28
+ this._logger.info(`Module '${moduleName}' was loaded`);
29
+ } catch (error) {
30
+ this._logger.error(`Module '${moduleName}' failed during loading ${error}`);
31
+ }
32
+ }
33
+ }
34
+ }
35
+
36
+ execute(name, requestInformation, data) {
37
+ for (const moduleName in this._externalModuleList) {
38
+ if (Object.hasOwnProperty.call(this._externalModuleList, moduleName) && moduleName === name) {
39
+ const module = this._externalModuleList[moduleName];
40
+
41
+ try {
42
+ return module.process(requestInformation, data);
43
+ } catch (error) {
44
+ throw new HttpException(constants.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR, `Module ${moduleName} failed. ${error}`);
45
+ }
46
+
47
+ }
48
+ }
49
+
50
+ throw new HttpException(constants.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR, `Module ${moduleName} doesn't exists`);
51
+ }
52
+
53
+ }
54
+
55
+ module.exports = Proxy;
@@ -0,0 +1,38 @@
1
+ const fs = require('fs');
2
+ const constants = require("./constants");
3
+ const CSV = require('./csv');
4
+ const HttpException = require('./HttpException');
5
+
6
+ const text_reader = (file) => {
7
+ return () => {
8
+ if (!fs.existsSync(file)) {
9
+ throw new HttpException(constants.HTTP_STATUS_CODES.NOT_FOUND, `File ${file} doesn't exists`);
10
+ }
11
+
12
+ return fs.readFileSync(file, 'utf8');
13
+ };
14
+ };
15
+
16
+ const folder_reader = (folder) => {
17
+ return (urlInformation) => {
18
+
19
+ if (!urlInformation.hasFile) {
20
+ throw new HttpException(constants.HTTP_STATUS_CODES.NOT_ACCEPTABLE, "File not provided");
21
+ }
22
+
23
+ return text_reader(folder + urlInformation.file)()
24
+ };
25
+ };
26
+
27
+ const csv_reader = function (file, parameters) {
28
+ const csvContent = text_reader(file, parameters)();
29
+ const csvReader = new CSV(csvContent, parameters);
30
+
31
+ return csvReader.read.bind(csvReader);
32
+ };
33
+
34
+ module.exports = {
35
+ text_reader: text_reader,
36
+ folder_reader: folder_reader,
37
+ csv_reader: csv_reader
38
+ };
@@ -0,0 +1,23 @@
1
+ const constants = require("./constants");
2
+
3
+ const parser = (url) => {
4
+
5
+ const parsedUrl = new URL(url, constants.BASE_URL);
6
+ const urlSections = parsedUrl.pathname.split("/").filter((e) => e !== "");
7
+
8
+ const baseUrl = "/" + urlSections.filter((e) => e.indexOf(".") < 0).join("/");
9
+ const file = urlSections.filter((e) => e.indexOf(".") >= 0);
10
+ const hasFile = file.length > 0;
11
+
12
+ return {
13
+ base: baseUrl,
14
+ file: hasFile ? file[0] : "",
15
+ hasFile: hasFile,
16
+ search: parsedUrl.searchParamss
17
+ };
18
+
19
+ };
20
+
21
+ module.exports = {
22
+ parse: parser
23
+ };
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "mockapi-msi",
3
+ "version": "1.0.0",
4
+ "description": "Mock API is a lightweight configurable HTTP API for testing and prototyping.",
5
+ "main": "main.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "author": "Matias Iacono",
10
+ "license": "ISC",
11
+ "bin": {
12
+ "mockapi": "main.js"
13
+ },
14
+ "dependencies": {
15
+ "yaml": "2.0.0-5"
16
+ }
17
+ }
@@ -0,0 +1,6 @@
1
+ id,name,money
2
+ 1,"test 1",100
3
+ 2,"test 2",100
4
+ 3,"test 3",100
5
+ 4,"test, 4",100
6
+ 5,"test 5",100