typescript-mock-server 1.11.4 → 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
package/README.md CHANGED
@@ -4,10 +4,37 @@ This makes it easier to maintain your mocks because you can load your own models
4
4
  have to update your mock, otherwise you will receive compile errors.
5
5
 
6
6
  # Quickstart
7
- The easiest way to check out this stub/mock server is by installing it as a (dev)dependency and then
8
- add a script to you scripts section: `npm run --prefix node_modules/typescript-mock-server start -- --path=$INIT_CWD/tms-models`.
9
- Your models should export a data const (or a function receiving `req` and `res`) and your file should be named as `^(get|post){1}(-\d)?.ts$`.
10
- Changes are being picked up automatically, so no need for a restart. When you add files, you have to restart.
7
+ The easiest way to use this tool is by installing it globally:
8
+
9
+ ```bash
10
+ npm install -g typescript-mock-server
11
+ ```
12
+
13
+ Then you can run it from anywhere using:
14
+
15
+ ```bash
16
+ typescript-mock-server --path=./tms-models
17
+ ```
18
+
19
+ Alternatively, you can install it as a (dev)dependency:
20
+
21
+ ```bash
22
+ npm install --save-dev typescript-mock-server
23
+ ```
24
+
25
+ And add a script to your `package.json`:
26
+
27
+ ```json
28
+ "scripts": {
29
+ "mock": "typescript-mock-server --path=tms-models"
30
+ }
31
+ ```
32
+
33
+ Or run it directly using `npx`:
34
+
35
+ ```bash
36
+ npx typescript-mock-server --path=tms-models
37
+ ```
11
38
 
12
39
  Check out the [working example project](https://github.com/GuyT07/typescript-mock-server-examle) and [the source](https://github.com/GuyT07/typescript-mock-server/tree/main/tms-models/users).
13
40
 
@@ -99,6 +126,7 @@ Following dependencies are being used:
99
126
 
100
127
 
101
128
  ## Release notes (will be moved to GitHub in the future)
129
+ - v1.11.5 - Ensured binary has executable permissions and updated README with better Quickstart instructions.
102
130
  - v1.11.4 - Fixed "models not found" error when running as a dependency by removing incorrect path mapping for compiled models and relying on ts-node for raw TypeScript files.
103
131
  - v1.11.3 - Fixed module resolution when used as a dependency by explicitly adding ts-node as a dependency and improving its configuration at runtime.
104
132
  - v1.11.1 - Added binary support to the package, allowing it to be executed as a command-line tool when installed as a dependency.
@@ -178,16 +178,6 @@ class TypescriptMockServerImpl {
178
178
  const endpoint = this.convertFileNameToEndpoint(dirPath, dirent, httpVerb);
179
179
  let modulePath = `${dirPath}/${dirent.name}`;
180
180
  this.registeredEndpoints.push({ httpVerb, endpoint });
181
- if (__filename.endsWith('.js') && modulePath.endsWith('.ts')) {
182
- const distPath = path_1.default.join(process.cwd(), 'dist');
183
- const potentialJsPath = modulePath
184
- .replace(process.cwd(), distPath)
185
- .replace(/\.ts$/, '.js');
186
- const fs = require('fs');
187
- if (fs.existsSync(potentialJsPath)) {
188
- modulePath = potentialJsPath;
189
- }
190
- }
191
181
  yield TypescriptMockServerImpl.loadModule(modulePath)
192
182
  .then(model => this.addEndpoint(endpoint, httpVerb, model))
193
183
  .catch(error => this.log.error(error));
@@ -77,6 +77,18 @@ class TypescriptMockServerImpl {
77
77
  }
78
78
  static loadModule(moduleName) {
79
79
  return __awaiter(this, void 0, void 0, function* () {
80
+ if (moduleName.endsWith('.ts')) {
81
+ require('ts-node').register({
82
+ transpileOnly: true,
83
+ skipProject: true,
84
+ compilerOptions: {
85
+ module: 'commonjs',
86
+ allowJs: true,
87
+ esModuleInterop: true,
88
+ resolveJsonModule: true
89
+ }
90
+ });
91
+ }
80
92
  return yield Promise.resolve(`${moduleName}`).then(s => __importStar(require(s)));
81
93
  });
82
94
  }
@@ -167,15 +179,6 @@ class TypescriptMockServerImpl {
167
179
  const endpoint = this.convertFileNameToEndpoint(dirPath, dirent, httpVerb);
168
180
  let modulePath = `${dirPath}/${dirent.name}`;
169
181
  this.registeredEndpoints.push({ httpVerb, endpoint });
170
- if (__filename.endsWith('.js')) {
171
- const distPath = path_1.default.join(process.cwd(), 'dist');
172
- if (modulePath.startsWith(process.cwd()) && !modulePath.startsWith(distPath)) {
173
- modulePath = modulePath.replace(process.cwd(), distPath);
174
- }
175
- if (modulePath.endsWith('.ts')) {
176
- modulePath = modulePath.replace(/\.ts$/, '.js');
177
- }
178
- }
179
182
  yield TypescriptMockServerImpl.loadModule(modulePath)
180
183
  .then(model => this.addEndpoint(endpoint, httpVerb, model))
181
184
  .catch(error => this.log.error(error));
package/dist/src/index.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "typescript-mock-server",
3
- "version": "1.11.4",
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": {
7
7
  "typescript-mock-server": "dist/src/index.js"
8
8
  },
9
9
  "scripts": {
10
+ "prepare": "npm run build",
10
11
  "test": "jest",
11
- "build": "tsc --outDir dist && sed -i '' '1s|.*|#!/usr/bin/env node|' dist/src/index.js",
12
+ "build": "tsc --outDir dist && sed -i '' '1s|.*|#!/usr/bin/env node|' dist/src/index.js && chmod +x dist/src/index.js",
12
13
  "example": "npm run build && node dist/src/index.js --path=tms-models --port=5200 --cors=http://localhost:5200",
13
14
  "start": "npm run build && node dist/src/index.js",
14
15
  "update-deps": "npm update",
@@ -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 });
package/tsconfig.json CHANGED
@@ -1,5 +1,7 @@
1
1
  {
2
2
  "compilerOptions": {
3
+ "rootDir": ".",
4
+
3
5
  "target": "es6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
4
6
 
5
7
  "module": "commonjs", /* Specify what module code is generated. */