typescript-mock-server 0.0.8 → 0.0.11

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
@@ -5,25 +5,26 @@ 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$`.
11
- Changes are being picked up automatically, so no need for a restart.
8
+ add a script to you scripts section: `npm run --prefix node_modules/typescript-mock-server start -- --path=/tms-models`.
9
+ Your models should export a data const 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.
12
11
 
13
- 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).
12
+ 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).
14
13
 
15
14
  # Options
16
- `--port=x`: Port number the server runs on
17
- `--path=x`: Path to your models
15
+ - `--port=x`: Port number the server runs on
16
+ - `--path=x`: Path to your models
18
17
 
19
- ## Adding GET mocks/stubs
18
+ ## Register mocks/stubs
20
19
  Examples talk, so lets start with an example.
21
20
 
22
- Your requirement is to have the following endpoints `/users`, `/users/1` and `/users/profile/1`
21
+ Your requirement is to have the following GET endpoints `/users`, `/users/1` and `/users/profile/1`
23
22
 
24
23
  Create a root folder that contains your models, like `models`. Then add a folder `users` and within the newly created folder
25
- create a new folder `profile`. Add following files `get.ts` and `get-1.ts` in the `users` directory, `get-1.ts` in the `profile` dir. You should
26
- have the following structure:
24
+ create a new folder `profile`. Add following files `get.ts` and `get-1.ts` in the `users` directory, `get-1.ts` in the `profile` dir.
25
+ To register another HTTP verb, you replace `get` with your verb ('get', 'post', 'put', 'delete', 'patch', 'options' and 'head' are currently supported).
26
+
27
+ You should have the following structure:
27
28
 
28
29
  ```
29
30
  --models
@@ -70,7 +71,23 @@ Following dependencies are being used:
70
71
 
71
72
  ## Roadmap
72
73
  - [x] Support other server port
73
- - [ ] Improve paths/way to start
74
- - [ ] Support different headers
75
- - [ ] Support all HTTP methods
74
+ - [x] Improve paths/way to start
75
+ - [ ] Support different headers/configurations (delays, status codes, ...)
76
+ - [x] Support most used HTTP methods
77
+ - [ ] Add tests
78
+ - [ ] Refactor, split up in separate classes (first check if people actually want to use the tool)
79
+ - [ ] Setup CI/CD (+code quality + coverage tooling)
80
+ - [ ] Setup website
81
+ - [ ] Create a JVM compatible version
82
+ - [ ] Create interface to force implementation of required properties and make it more stable
83
+ - [ ] Improve error handling (missing properties etc.)
84
+ - [ ] Create an optional persistent state
85
+
86
+
87
+ ## Release notes (will be moved to GitHub in the future)
88
+ - v0.0.11 - Add items to roadmap, bug fixes
89
+ - v0.0.10 - Support multiple http verbs
90
+
91
+ ## Bug fix contributors
92
+ - Path fix, from now on current working directory is used. Credits to [Spoodyman](https://github.com/spoodyman)
76
93
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typescript-mock-server",
3
- "version": "0.0.8",
3
+ "version": "0.0.11",
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",
@@ -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.ts CHANGED
@@ -3,8 +3,7 @@
3
3
  import express, { Express } from 'express';
4
4
  import * as fs from 'fs';
5
5
 
6
- const baseDirPath = process.cwd();
7
- console.log(baseDirPath);
6
+ type HttpVerb = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
8
7
 
9
8
  const argv: { [key: string]: string } = (() => {
10
9
  const args = {};
@@ -19,70 +18,71 @@ const argv: { [key: string]: string } = (() => {
19
18
  return args;
20
19
  })();
21
20
 
22
- console.log(argv);
21
+ console.log(`Passed arguments %o`, argv);
23
22
 
24
23
  // Create a new express app instance
25
24
  const app: Express = express();
26
25
 
27
- const {path, port} = argv;
26
+ const { path, port } = argv;
28
27
 
29
- // @ts-ignore
30
- const basePath = `${baseDirPath}/${path}`;
28
+ const basePath = `${process.cwd()}/${path}`;
29
+
30
+ interface RegisteredEndpoint {
31
+ httpVerb: string;
32
+ endpoint: string;
33
+ }
34
+
35
+ const registeredEndpoints: RegisteredEndpoint[] = [];
31
36
 
32
37
  console.log('basePath:' + basePath);
33
38
 
34
- async function print(path: string) {
35
- console.log(path);
39
+ async function readRoutes(path: string) {
36
40
  const dir = await fs.promises.opendir(path);
37
41
  for await (const dirent of dir) {
38
42
  if (dirent.isDirectory()) {
39
- await print(`${path}/${dirent.name}`);
43
+ await readRoutes(`${path}/${dirent.name}`);
40
44
  } else {
41
45
  handleFile(path, dirent);
42
46
  }
43
47
  }
48
+ registeredEndpoints.forEach(endpoint => console.log(`${endpoint.httpVerb.toUpperCase()} http://localhost:${port}${endpoint.endpoint}`))
44
49
  }
45
50
 
46
- print(basePath).catch(console.error);
47
-
48
- async function loadModule(moduleName: string) {
49
- return await import(moduleName);
50
- }
51
+ readRoutes(basePath).catch(console.error);
51
52
 
52
53
  app.listen(port || 3000, function() {
53
54
  console.log(`App is listening on port ${port || 3000}!`);
54
55
  });
55
56
 
57
+ async function loadModule(moduleName: string) {
58
+ return await import(moduleName);
59
+ }
60
+
56
61
  function handleFile(path: string, dirent: fs.Dirent) {
57
- console.log('File name: ' + dirent.name);
58
- if (dirent.name.startsWith('get')) {
59
- handleGetRequest(path, dirent);
60
- }
62
+ const httpVerb = (dirent.name.indexOf('-') > -1 ? dirent.name.split('-')[0] : dirent.name.split('.')[0]) as HttpVerb;
63
+ handleRequest(path, dirent, httpVerb);
61
64
  }
62
65
 
63
- function addEndpoint(endpoint: string, model: any) {
64
- app.get(endpoint, function(req, res) {
65
- res.send(model.data);
66
- });
66
+ function addEndpoint(endpoint: string, httpVerb: HttpVerb, model: any) {
67
+ app[httpVerb](endpoint, (req, res) => res.send(model.data));
67
68
  }
68
69
 
69
- function handleGetRequest(path: string, dirent: fs.Dirent) {
70
- console.log('Adding GET request');
71
- const endpoint = convertFileNameToEndpoint(path, dirent);
72
- console.log('Endpoint: ' + endpoint);
70
+ function handleRequest(path: string, dirent: fs.Dirent, httpVerb: HttpVerb) {
71
+ const endpoint = convertFileNameToEndpoint(path, dirent, httpVerb);
73
72
  const modulePath = `${path}/${dirent.name}`;
74
- console.log('Resolve module: ' + modulePath);
73
+ registeredEndpoints.push({httpVerb, endpoint});
75
74
  loadModule(modulePath)
76
- .then(model => addEndpoint(endpoint, model))
75
+ .then(model => addEndpoint(endpoint, httpVerb, model))
77
76
  .catch(err => console.error(err));
78
77
  }
79
78
 
80
- function convertFileNameToEndpoint(path: string, dirent: fs.Dirent): string {
81
- let endpoint = `${path.replace(basePath, '')}/${dirent.name}`;
82
- endpoint = endpoint.replace('.ts', '');
83
- endpoint = endpoint.replace('get', '');
84
- if (endpoint !== '') {
85
- endpoint = endpoint.replace('-', '');
79
+ function convertFileNameToEndpoint(path: string, dirent: fs.Dirent, httpVerb: HttpVerb): string {
80
+ const endpoint = `${path.replace(basePath, '')}/${dirent.name}`
81
+ .replace('.ts', '')
82
+ .replace(httpVerb, '')
83
+ .replace('-', '');
84
+ if (endpoint.endsWith('/')) {
85
+ return endpoint.substring(0, endpoint.length - 1);
86
86
  }
87
87
  return endpoint;
88
88
  }
@@ -0,0 +1,11 @@
1
+ interface User {
2
+ id: number;
3
+ firstName: string;
4
+ lastName: string;
5
+ }
6
+
7
+ export const data: User = {
8
+ id: 1,
9
+ firstName: 'Guy deleted',
10
+ lastName: 'Theuws deleted'
11
+ };
@@ -0,0 +1 @@
1
+ export const data = null;
@@ -0,0 +1 @@
1
+ export const data = null;
@@ -0,0 +1,11 @@
1
+ interface User {
2
+ id: number;
3
+ firstName: string;
4
+ lastName: string;
5
+ }
6
+
7
+ export const data: User = {
8
+ id: 1,
9
+ firstName: 'Guy patch',
10
+ lastName: 'Theuws patch'
11
+ };
@@ -0,0 +1,11 @@
1
+ interface User {
2
+ id: number;
3
+ firstName: string;
4
+ lastName: string;
5
+ }
6
+
7
+ export const data: User = {
8
+ id: new Date().getMilliseconds(),
9
+ firstName: 'Guy created',
10
+ lastName: 'Theuws created'
11
+ };
@@ -0,0 +1,11 @@
1
+ interface User {
2
+ id: number;
3
+ firstName: string;
4
+ lastName: string;
5
+ }
6
+
7
+ export const data: User = {
8
+ id: 1,
9
+ firstName: 'Guy updated',
10
+ lastName: 'Theuws updated'
11
+ };
@@ -1,8 +0,0 @@
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
- };
@@ -1,16 +0,0 @@
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
- }];
@@ -1,12 +0,0 @@
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
- };