typescript-mock-server 0.0.6 → 0.0.9

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/README.md CHANGED
@@ -1,16 +1,19 @@
1
1
  # Typescript mock server
2
2
  Simple mock/stub server that can be used in front end development. Instead of creating json files you can just publish TypeScript objects as json.
3
3
  This makes it easier to maintain your mocks because you can load your own models. When you change your implementation you also
4
- have to update your mock, otherwise you will receive compile errors.
4
+ have to update your mock, otherwise you will receive compile errors.
5
5
 
6
6
  # Quickstart
7
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: `cd node_modules/typescript-mock-server && npm run start -- --path=../../path-to-your-model-directory`.
9
- Please note we are changing the directory and therefore, to set the path parameter, you need to go 2 levels up to be in your root.
10
- I am looking for a cleaner way of doing this. Your models should export a data const and your file should be named as `^(get|post){1}(-\d)?.ts$`.
8
+ add a script to you scripts section: `npm run --prefix node_modules/typescript-mock-server start -- --path=$(pwd)/tms-models`.
9
+ Your models should export a data const and your file should be named as `^(get|post){1}(-\d)?.ts$`.
11
10
  Changes are being picked up automatically, so no need for a restart.
12
11
 
13
- Check out [the examples](https://github.com/GuyT07/typescript-mock-server/tree/main/tms-models/users).
12
+ Check out the [working example project](https://github.com/GuyT07/typescript-mock-server-examle) and source [the examples](https://github.com/GuyT07/typescript-mock-server/tree/main/tms-models/users).
13
+
14
+ # Options
15
+ - `--port=x`: Port number the server runs on
16
+ - `--path=x`: Path to your models
14
17
 
15
18
  ## Adding GET mocks/stubs
16
19
  Examples talk, so lets start with an example.
@@ -65,8 +68,8 @@ Following dependencies are being used:
65
68
  - @types/node
66
69
 
67
70
  ## Roadmap
68
- - [ ] Support other server port
69
- - [ ] Improve paths/way to start
71
+ - [x] Support other server port
72
+ - [x] Improve paths/way to start
70
73
  - [ ] Support different headers
71
74
  - [ ] Support all HTTP methods
72
75
 
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "typescript-mock-server",
3
- "version": "0.0.6",
3
+ "version": "0.0.9",
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
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1",
7
- "example": "ts-node-dev src/index.ts --path=tms-models",
7
+ "example": "ts-node-dev src/index.ts --path=$(pwd)/tms-models --port=5000",
8
8
  "start": "ts-node-dev src/index.ts"
9
9
  },
10
10
  "repository": {
@@ -12,12 +12,15 @@
12
12
  "url": "git+https://github.com/GuyT07/typescript-mock-server.git"
13
13
  },
14
14
  "keywords": ["mock server", "testing", "stub", "typescript"],
15
- "author": "",
15
+ "author": "Guy Theuws",
16
16
  "license": "ISC",
17
17
  "bugs": {
18
18
  "url": "https://github.com/GuyT07/typescript-mock-server/issues"
19
19
  },
20
20
  "homepage": "https://github.com/GuyT07/typescript-mock-server#readme",
21
+ "funding": {
22
+ "url" : "https://genydev.nl"
23
+ },
21
24
  "devDependencies": {
22
25
  "prettier": "^2.6.2"
23
26
  },
package/src/index.js ADDED
@@ -0,0 +1,133 @@
1
+ #!./../node_modules/.bin/ts-node-dev
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || function (mod) {
20
+ if (mod && mod.__esModule) return mod;
21
+ var result = {};
22
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
+ __setModuleDefault(result, mod);
24
+ return result;
25
+ };
26
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
27
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
28
+ return new (P || (P = Promise))(function (resolve, reject) {
29
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
30
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
31
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
32
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
33
+ });
34
+ };
35
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
36
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
37
+ var m = o[Symbol.asyncIterator], i;
38
+ 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);
39
+ 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); }); }; }
40
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
41
+ };
42
+ var __importDefault = (this && this.__importDefault) || function (mod) {
43
+ return (mod && mod.__esModule) ? mod : { "default": mod };
44
+ };
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ const express_1 = __importDefault(require("express"));
47
+ const fs = __importStar(require("fs"));
48
+ const baseDirPath = process.cwd();
49
+ console.log(baseDirPath);
50
+ const argv = (() => {
51
+ const args = {};
52
+ process.argv.slice(2).map((element) => {
53
+ const matches = element.match('--([a-zA-Z0-9]+)=(.*)');
54
+ if (matches) {
55
+ // @ts-ignore
56
+ args[matches[1]] = matches[2]
57
+ .replace(/^['"]/, '').replace(/['"]$/, '');
58
+ }
59
+ });
60
+ return args;
61
+ })();
62
+ console.log(argv);
63
+ // Create a new express app instance
64
+ const app = (0, express_1.default)();
65
+ // @ts-ignore
66
+ const args = argv['path'];
67
+ // @ts-ignore
68
+ const basePath = `${baseDirPath}/${args}`;
69
+ console.log('basePath:' + basePath);
70
+ function print(path) {
71
+ var e_1, _a;
72
+ return __awaiter(this, void 0, void 0, function* () {
73
+ console.log(path);
74
+ const dir = yield fs.promises.opendir(path);
75
+ try {
76
+ for (var dir_1 = __asyncValues(dir), dir_1_1; dir_1_1 = yield dir_1.next(), !dir_1_1.done;) {
77
+ const dirent = dir_1_1.value;
78
+ if (dirent.isDirectory()) {
79
+ yield print(`${path}/${dirent.name}`);
80
+ }
81
+ else {
82
+ handleFile(path, dirent);
83
+ }
84
+ }
85
+ }
86
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
87
+ finally {
88
+ try {
89
+ if (dir_1_1 && !dir_1_1.done && (_a = dir_1.return)) yield _a.call(dir_1);
90
+ }
91
+ finally { if (e_1) throw e_1.error; }
92
+ }
93
+ });
94
+ }
95
+ print(basePath).catch(console.error);
96
+ function loadModule(moduleName) {
97
+ return __awaiter(this, void 0, void 0, function* () {
98
+ return yield Promise.resolve().then(() => __importStar(require(moduleName)));
99
+ });
100
+ }
101
+ app.listen(3000, function () {
102
+ console.log('App is listening on port 3000!');
103
+ });
104
+ function handleFile(path, dirent) {
105
+ console.log('File name: ' + dirent.name);
106
+ if (dirent.name.startsWith('get')) {
107
+ handleGetRequest(path, dirent);
108
+ }
109
+ }
110
+ function addEndpoint(endpoint, model) {
111
+ app.get(endpoint, function (req, res) {
112
+ res.send(model.data);
113
+ });
114
+ }
115
+ function handleGetRequest(path, dirent) {
116
+ console.log('Adding GET request');
117
+ const endpoint = convertFileNameToEndpoint(path, dirent);
118
+ console.log('Endpoint: ' + endpoint);
119
+ const modulePath = `${path}/${dirent.name}`;
120
+ console.log('Resolve module: ' + modulePath);
121
+ loadModule(modulePath)
122
+ .then(model => addEndpoint(endpoint, model))
123
+ .catch(err => console.error(err));
124
+ }
125
+ function convertFileNameToEndpoint(path, dirent) {
126
+ let endpoint = `${path.replace(basePath, '')}/${dirent.name}`;
127
+ endpoint = endpoint.replace('.ts', '');
128
+ endpoint = endpoint.replace('get', '');
129
+ if (endpoint !== '') {
130
+ endpoint = endpoint.replace('-', '');
131
+ }
132
+ return endpoint;
133
+ }
package/src/index.ts CHANGED
@@ -1,90 +1,84 @@
1
- #!./../node_modules/.bin/ts-node-dev
1
+ #!./node_modules/.bin/ts-node-dev
2
2
 
3
- import express from 'express';
4
- import { Express } from 'express';
3
+ import express, { Express } from 'express';
5
4
  import * as fs from 'fs';
6
5
 
7
- const baseDirPath = process.cwd()
8
- console.log(baseDirPath);
9
-
10
- const argv = (() => {
11
- const args = {};
12
- process.argv.slice(2).map((element) => {
13
- const matches = element.match('--([a-zA-Z0-9]+)=(.*)');
14
- if (matches) {
15
- // @ts-ignore
16
- args[matches[1]] = matches[2]
17
- .replace(/^['"]/, '').replace(/['"]$/, '');
18
- }
19
- });
20
- return args;
21
- })();
6
+ const argv: { [key: string]: string } = (() => {
7
+ const args = {};
8
+ process.argv.slice(2).map((element) => {
9
+ const matches = element.match('--([a-zA-Z0-9]+)=(.*)');
10
+ if (matches) {
11
+ // @ts-ignore
12
+ args[matches[1]] = matches[2]
13
+ .replace(/^['"]/, '').replace(/['"]$/, '');
14
+ }
15
+ });
16
+ return args;
17
+ })();
22
18
 
23
- console.log(argv);
19
+ console.log(argv);
24
20
 
25
21
  // Create a new express app instance
26
- const app: Express = express();
22
+ const app: Express = express();
27
23
 
28
- // @ts-ignore
29
- const args = argv['path'];
24
+ const {path, port} = argv;
30
25
 
31
- // @ts-ignore
32
- const basePath = `${baseDirPath}/${args}`;
26
+ const basePath = `${path}`;
33
27
 
34
- console.log('basePath:' + basePath);
28
+ console.log('basePath:' + basePath);
35
29
 
36
- async function print(path: string) {
37
- console.log(path);
38
- const dir = await fs.promises.opendir(path);
39
- for await (const dirent of dir) {
40
- if (dirent.isDirectory()) {
41
- await print(`${path}/${dirent.name}`);
42
- } else {
43
- handleFile(path, dirent);
44
- }
45
- }
30
+ async function print(path: string) {
31
+ console.log(path);
32
+ const dir = await fs.promises.opendir(path);
33
+ for await (const dirent of dir) {
34
+ if (dirent.isDirectory()) {
35
+ await print(`${path}/${dirent.name}`);
36
+ } else {
37
+ handleFile(path, dirent);
46
38
  }
39
+ }
40
+ }
47
41
 
48
- print(basePath).catch(console.error);
42
+ print(basePath).catch(console.error);
49
43
 
50
- async function loadModule(moduleName: string) {
51
- return await import(moduleName);
52
- }
44
+ async function loadModule(moduleName: string) {
45
+ return await import(moduleName);
46
+ }
53
47
 
54
- app.listen(3000, function() {
55
- console.log('App is listening on port 3000!');
56
- });
48
+ app.listen(port || 3000, function() {
49
+ console.log(`App is listening on port ${port || 3000}!`);
50
+ });
57
51
 
58
- function handleFile(path: string, dirent: fs.Dirent) {
59
- console.log('File name: ' + dirent.name);
60
- if (dirent.name.startsWith('get')) {
61
- handleGetRequest(path, dirent);
62
- }
63
- }
52
+ function handleFile(path: string, dirent: fs.Dirent) {
53
+ console.log('File name: ' + dirent.name);
54
+ if (dirent.name.startsWith('get')) {
55
+ handleGetRequest(path, dirent);
56
+ }
57
+ }
64
58
 
65
- function addEndpoint(endpoint: string, model: any) {
66
- app.get(endpoint, function(req, res) {
67
- res.send(model.data)
68
- });
69
- }
59
+ function addEndpoint(endpoint: string, model: any) {
60
+ app.get(endpoint, function(req, res) {
61
+ res.send(model.data);
62
+ });
63
+ }
70
64
 
71
- function handleGetRequest(path: string, dirent: fs.Dirent) {
72
- console.log('Adding GET request');
73
- const endpoint = convertFileNameToEndpoint(path, dirent);
74
- console.log('Endpoint: ' + endpoint);
75
- const modulePath = `${path}/${dirent.name}`;
76
- console.log('Resolve module: ' + modulePath);
77
- loadModule(modulePath)
78
- .then(model => addEndpoint(endpoint, model))
79
- .catch(err => console.error(err));
80
- }
65
+ function handleGetRequest(path: string, dirent: fs.Dirent) {
66
+ console.log('Adding GET request');
67
+ const endpoint = convertFileNameToEndpoint(path, dirent);
68
+ console.log('Endpoint: ' + endpoint);
69
+ const modulePath = `${path}/${dirent.name}`;
70
+ console.log('Resolve module: ' + modulePath);
71
+ loadModule(modulePath)
72
+ .then(model => addEndpoint(endpoint, model))
73
+ .catch(err => console.error(err));
74
+ }
81
75
 
82
- function convertFileNameToEndpoint(path: string, dirent: fs.Dirent): string {
83
- let endpoint = `${path.replace(basePath, '')}/${dirent.name}`;
84
- endpoint = endpoint.replace('.ts', '');
85
- endpoint = endpoint.replace('get', '');
86
- if (endpoint !== '') {
87
- endpoint = endpoint.replace('-', '');
88
- }
89
- return endpoint;
76
+ function convertFileNameToEndpoint(path: string, dirent: fs.Dirent): string {
77
+ let endpoint = `${path.replace(basePath, '')}/${dirent.name}`;
78
+ endpoint = endpoint.replace('.ts', '');
79
+ endpoint = endpoint.replace('get', '');
80
+ if (endpoint !== '') {
81
+ endpoint = endpoint.replace('-', '');
82
+ }
83
+ return endpoint;
90
84
  }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.data = void 0;
4
+ exports.data = {
5
+ id: 1,
6
+ firstName: 'Guy',
7
+ lastName: 'Theuws'
8
+ };
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.data = exports.newDate = void 0;
4
+ const newDate = () => new Date();
5
+ exports.newDate = newDate;
6
+ exports.data = [{
7
+ id: 1,
8
+ firstName: 'Guy',
9
+ lastName: 'Theuws',
10
+ creationDate: (0, exports.newDate)()
11
+ }, {
12
+ id: 2,
13
+ firstName: 'Generation Y',
14
+ lastName: 'Development',
15
+ creationDate: (0, exports.newDate)()
16
+ }];
@@ -5,7 +5,7 @@ export interface User {
5
5
  creationDate: Date;
6
6
  }
7
7
 
8
- const newDate = () => new Date();
8
+ export const newDate = () => new Date();
9
9
 
10
10
  export const data: User[] = [{
11
11
  id: 1,
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.data = void 0;
4
+ const get_1 = require("../get");
5
+ exports.data = {
6
+ id: 1, title: 'Hello profile', user: {
7
+ id: 1,
8
+ firstName: 'Guy',
9
+ lastName: 'Theuws',
10
+ creationDate: (0, get_1.newDate)()
11
+ }
12
+ };
@@ -1,4 +1,4 @@
1
- import { User } from '../get';
1
+ import { newDate, User } from '../get';
2
2
 
3
3
  interface Profile {
4
4
  id: number;
@@ -10,6 +10,7 @@ export const data: Profile = {
10
10
  id: 1, title: 'Hello profile', user: {
11
11
  id: 1,
12
12
  firstName: 'Guy',
13
- lastName: 'Theuws'
13
+ lastName: 'Theuws',
14
+ creationDate: newDate()
14
15
  }
15
16
  };
package/nodemon.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "watch": [
3
- "src",
4
- "tms-models"
5
- ],
6
- "ext": ".ts,.js",
7
- "ignore": [],
8
- "exec": "ts-node ./src/index.ts"
9
- }