typescript-mock-server 1.11.5 → 1.11.6

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.
File without changes
File without changes
@@ -0,0 +1 @@
1
+ []
@@ -0,0 +1 @@
1
+ 3.0
File without changes
@@ -80,6 +80,7 @@ class TypescriptMockServerImpl {
80
80
  if (moduleName.endsWith('.ts')) {
81
81
  require('ts-node').register({
82
82
  transpileOnly: true,
83
+ skipProject: true,
83
84
  compilerOptions: {
84
85
  module: 'commonjs',
85
86
  allowJs: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typescript-mock-server",
3
- "version": "1.11.5",
3
+ "version": "1.11.6",
4
4
  "description": "Simple mock server that can be used in front end development. Instead of creating json files you can just publish TypeScript objects as json",
5
5
  "main": "dist/src/index.js",
6
6
  "bin": {
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Command = void 0;
4
+ var Command;
5
+ (function (Command) {
6
+ Command["PATH"] = "path";
7
+ Command["PORT"] = "port";
8
+ Command["CORS"] = "cors";
9
+ })(Command || (exports.Command = Command = {}));
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommandLineImpl = void 0;
4
+ const logger_impl_1 = require("./logger-impl");
5
+ class CommandLineImpl {
6
+ constructor() {
7
+ this.arguments = new Map();
8
+ this.log = new logger_impl_1.LoggerImpl();
9
+ this.parseCommandLineArguments();
10
+ }
11
+ getCommands() {
12
+ return this.arguments;
13
+ }
14
+ getCommand(command) {
15
+ return this.arguments.get(command);
16
+ }
17
+ parseCommandLineArguments() {
18
+ process.argv.slice(2).map((element) => {
19
+ const matches = element.match('--([a-zA-Z0-9]+)=(.*)');
20
+ if (matches) {
21
+ const value = matches[2].replace(/^['"]/, '').replace(/['"]$/, '');
22
+ this.arguments.set(matches[1], value);
23
+ }
24
+ });
25
+ this.log.debug(`Passed arguments ${[...this.arguments.keys()].join(',')}`);
26
+ }
27
+ }
28
+ exports.CommandLineImpl = CommandLineImpl;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LoggerImpl = void 0;
4
+ const tslog_1 = require("tslog");
5
+ class LoggerImpl {
6
+ constructor() {
7
+ this.log = new tslog_1.Logger({ ignoreStackLevels: 4, displayFunctionName: false });
8
+ }
9
+ static getArgumentsToPass(args) {
10
+ return LoggerImpl.getNumberOfArguments(args) === 1 ? args[0] : args;
11
+ }
12
+ static getNumberOfArguments(args) {
13
+ return args.length;
14
+ }
15
+ debug(...args) {
16
+ this.log.debug(LoggerImpl.getArgumentsToPass(args));
17
+ }
18
+ error(...args) {
19
+ this.log.error(LoggerImpl.getArgumentsToPass(args));
20
+ }
21
+ trace(...args) {
22
+ this.log.trace(LoggerImpl.getArgumentsToPass(args));
23
+ }
24
+ warn(...args) {
25
+ this.log.warn(LoggerImpl.getArgumentsToPass(args));
26
+ }
27
+ info(...args) {
28
+ this.log.info(LoggerImpl.getArgumentsToPass(args));
29
+ }
30
+ }
31
+ exports.LoggerImpl = LoggerImpl;
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
45
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
46
+ var m = o[Symbol.asyncIterator], i;
47
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
48
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
49
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
50
+ };
51
+ var __importDefault = (this && this.__importDefault) || function (mod) {
52
+ return (mod && mod.__esModule) ? mod : { "default": mod };
53
+ };
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ exports.TypescriptMockServerImpl = void 0;
56
+ const express_1 = __importDefault(require("express"));
57
+ const cors_1 = __importDefault(require("cors"));
58
+ const command_line_impl_1 = require("./command-line-impl");
59
+ const command_line_1 = require("../command-line");
60
+ const promises_1 = require("fs/promises");
61
+ const logger_impl_1 = require("./logger-impl");
62
+ const path_1 = __importDefault(require("path"));
63
+ class TypescriptMockServerImpl {
64
+ constructor(config) {
65
+ this.log = new logger_impl_1.LoggerImpl();
66
+ this.commandLine = new command_line_impl_1.CommandLineImpl();
67
+ this.registeredEndpoints = [];
68
+ if (config && 'use' in config) {
69
+ this.app = config;
70
+ this.basePath = this.getPath();
71
+ }
72
+ else {
73
+ const serverConfig = config;
74
+ this.app = (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.app) || (0, express_1.default)();
75
+ this.basePath = this.getPath(serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.path);
76
+ }
77
+ }
78
+ static loadModule(moduleName) {
79
+ return __awaiter(this, void 0, void 0, function* () {
80
+ if (moduleName.endsWith('.ts')) {
81
+ require('ts-node').register({
82
+ transpileOnly: true,
83
+ compilerOptions: {
84
+ module: 'commonjs',
85
+ allowJs: true,
86
+ esModuleInterop: true,
87
+ resolveJsonModule: true
88
+ }
89
+ });
90
+ }
91
+ return yield Promise.resolve(`${moduleName}`).then(s => __importStar(require(s)));
92
+ });
93
+ }
94
+ start() {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ this.log.info(`basePath: ${this.basePath}`);
97
+ const port = this.commandLine.getCommand(command_line_1.Command.PORT) || 3000;
98
+ const corsSetting = {
99
+ origin: this.commandLine.getCommand(command_line_1.Command.CORS) || '*'
100
+ };
101
+ this.app.use((0, cors_1.default)(corsSetting));
102
+ // add started endpoint
103
+ this.addEndpoint('state', 'get', { data: { status: 'started' } });
104
+ yield this.readRoutes(this.basePath).catch(error => this.log.error(error));
105
+ this.app.listen(port, () => {
106
+ this.log.info(`App is listening on port ${port}!`);
107
+ });
108
+ this.log.info(`Started mock server on port ${port}`);
109
+ });
110
+ }
111
+ readRoutes(dirPath) {
112
+ return __awaiter(this, void 0, void 0, function* () {
113
+ var _a, e_1, _b, _c;
114
+ const dir = yield (0, promises_1.opendir)(dirPath);
115
+ try {
116
+ for (var _d = true, dir_1 = __asyncValues(dir), dir_1_1; dir_1_1 = yield dir_1.next(), _a = dir_1_1.done, !_a; _d = true) {
117
+ _c = dir_1_1.value;
118
+ _d = false;
119
+ const dirent = _c;
120
+ if (dirent.isDirectory()) {
121
+ yield this.readRoutes(`${dirPath}/${dirent.name}`);
122
+ }
123
+ else {
124
+ yield this.handleFile(dirPath, dirent);
125
+ }
126
+ }
127
+ }
128
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
129
+ finally {
130
+ try {
131
+ if (!_d && !_a && (_b = dir_1.return)) yield _b.call(dir_1);
132
+ }
133
+ finally { if (e_1) throw e_1.error; }
134
+ }
135
+ const port = this.commandLine.getCommand(command_line_1.Command.PORT) || 3000;
136
+ this.registeredEndpoints.forEach(endpoint => this.log.info(`${endpoint.httpVerb.toUpperCase()} http://localhost:${port}${endpoint.endpoint}`));
137
+ this.registeredEndpoints = [];
138
+ });
139
+ }
140
+ handleFile(dirPath, dirent) {
141
+ return __awaiter(this, void 0, void 0, function* () {
142
+ const httpVerb = (dirent.name.indexOf('-') > -1 ? dirent.name.split('-')[0] : dirent.name.split('.')[0]);
143
+ yield this.handleRequest(dirPath, dirent, httpVerb);
144
+ });
145
+ }
146
+ addEndpoint(endpoint, httpVerb, model) {
147
+ const route = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
148
+ this.app[httpVerb](route, (req, res) => {
149
+ var _a, _b;
150
+ let responseData = model.data;
151
+ let statusCode = (_a = model === null || model === void 0 ? void 0 : model.config) === null || _a === void 0 ? void 0 : _a.statusCode;
152
+ let delay = (_b = model === null || model === void 0 ? void 0 : model.config) === null || _b === void 0 ? void 0 : _b.delay;
153
+ if (typeof model.data === 'function') {
154
+ responseData = model.data(req, res);
155
+ }
156
+ if (statusCode) {
157
+ res.statusCode = statusCode;
158
+ }
159
+ if (delay) {
160
+ setTimeout(() => res.send(responseData), this.getDelayValue(delay));
161
+ }
162
+ else {
163
+ return res.send(responseData);
164
+ }
165
+ });
166
+ }
167
+ getDelayValue(delay) {
168
+ if (typeof delay === 'number') {
169
+ return delay;
170
+ }
171
+ else if (delay.min && delay.max) {
172
+ return Math.floor(delay.min + Math.random() * delay.max);
173
+ }
174
+ return 0;
175
+ }
176
+ handleRequest(dirPath, dirent, httpVerb) {
177
+ return __awaiter(this, void 0, void 0, function* () {
178
+ const endpoint = this.convertFileNameToEndpoint(dirPath, dirent, httpVerb);
179
+ let modulePath = `${dirPath}/${dirent.name}`;
180
+ this.registeredEndpoints.push({ httpVerb, endpoint });
181
+ yield TypescriptMockServerImpl.loadModule(modulePath)
182
+ .then(model => this.addEndpoint(endpoint, httpVerb, model))
183
+ .catch(error => this.log.error(error));
184
+ });
185
+ }
186
+ convertFileNameToEndpoint(dirPath, dirent, httpVerb) {
187
+ const endpoint = `${dirPath.replace(this.basePath, '')}/${dirent.name}`
188
+ .replace('.ts', '')
189
+ .replace(`${httpVerb}-`, '')
190
+ .replace(httpVerb, '');
191
+ if (endpoint.endsWith('/')) {
192
+ return endpoint.substring(0, endpoint.length - 1);
193
+ }
194
+ return endpoint;
195
+ }
196
+ getPath(defaultPath = 'tms-models') {
197
+ let definedPath = defaultPath;
198
+ if (!this.commandLine.getCommands().has(command_line_1.Command.PATH)) {
199
+ this.log.warn(`Path parameter not set, fallback to default ${defaultPath}`);
200
+ }
201
+ else {
202
+ definedPath = this.commandLine.getCommand(command_line_1.Command.PATH);
203
+ }
204
+ if (path_1.default.isAbsolute(definedPath)) {
205
+ return definedPath;
206
+ }
207
+ return path_1.default.join(process.cwd(), definedPath);
208
+ }
209
+ }
210
+ exports.TypescriptMockServerImpl = TypescriptMockServerImpl;
@@ -35,6 +35,7 @@ export class TypescriptMockServerImpl implements TypescriptMockServer{
35
35
  if (moduleName.endsWith('.ts')) {
36
36
  require('ts-node').register({
37
37
  transpileOnly: true,
38
+ skipProject: true,
38
39
  compilerOptions: {
39
40
  module: 'commonjs',
40
41
  allowJs: true,
package/src/index.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const typescript_mock_server_impl_1 = require("./impl/typescript-mock-server-impl");
5
+ const server = new typescript_mock_server_impl_1.TypescriptMockServerImpl();
6
+ server.start().then(() => console.log('Server started')).catch(console.error);
package/src/logger.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });