typescript-mock-server 0.0.9 → 0.0.10

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
@@ -9,20 +9,22 @@ add a script to you scripts section: `npm run --prefix node_modules/typescript-m
9
9
  Your models should export a data const and your file should be named as `^(get|post){1}(-\d)?.ts$`.
10
10
  Changes are being picked up automatically, so no need for a restart.
11
11
 
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).
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).
13
13
 
14
14
  # Options
15
15
  - `--port=x`: Port number the server runs on
16
16
  - `--path=x`: Path to your models
17
17
 
18
- ## Adding GET mocks/stubs
18
+ ## Register mocks/stubs
19
19
  Examples talk, so lets start with an example.
20
20
 
21
- 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`
22
22
 
23
23
  Create a root folder that contains your models, like `models`. Then add a folder `users` and within the newly created folder
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. You should
25
- 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:
26
28
 
27
29
  ```
28
30
  --models
@@ -70,6 +72,11 @@ Following dependencies are being used:
70
72
  ## Roadmap
71
73
  - [x] Support other server port
72
74
  - [x] Improve paths/way to start
73
- - [ ] Support different headers
74
- - [ ] Support all HTTP methods
75
+ - [ ] Support different headers/configurations (delays, status codes, ...)
76
+ - [x] Support all 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
75
82
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typescript-mock-server",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
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",
package/src/index.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  import express, { Express } from 'express';
4
4
  import * as fs from 'fs';
5
5
 
6
+ type HttpVerb = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
7
+
6
8
  const argv: { [key: string]: string } = (() => {
7
9
  const args = {};
8
10
  process.argv.slice(2).map((element) => {
@@ -16,69 +18,71 @@ const argv: { [key: string]: string } = (() => {
16
18
  return args;
17
19
  })();
18
20
 
19
- console.log(argv);
21
+ console.log(`Passed arguments %o`, argv);
20
22
 
21
23
  // Create a new express app instance
22
24
  const app: Express = express();
23
25
 
24
- const {path, port} = argv;
26
+ const { path, port } = argv;
25
27
 
26
28
  const basePath = `${path}`;
27
29
 
30
+ interface RegisteredEndpoint {
31
+ httpVerb: string;
32
+ endpoint: string;
33
+ }
34
+
35
+ const registeredEndpoints: RegisteredEndpoint[] = [];
36
+
28
37
  console.log('basePath:' + basePath);
29
38
 
30
- async function print(path: string) {
31
- console.log(path);
39
+ async function readRoutes(path: string) {
32
40
  const dir = await fs.promises.opendir(path);
33
41
  for await (const dirent of dir) {
34
42
  if (dirent.isDirectory()) {
35
- await print(`${path}/${dirent.name}`);
43
+ await readRoutes(`${path}/${dirent.name}`);
36
44
  } else {
37
45
  handleFile(path, dirent);
38
46
  }
39
47
  }
48
+ registeredEndpoints.forEach(endpoint => console.log(`${endpoint.httpVerb.toUpperCase()} http://localhost:${port}${endpoint.endpoint}`))
40
49
  }
41
50
 
42
- print(basePath).catch(console.error);
43
-
44
- async function loadModule(moduleName: string) {
45
- return await import(moduleName);
46
- }
51
+ readRoutes(basePath).catch(console.error);
47
52
 
48
53
  app.listen(port || 3000, function() {
49
54
  console.log(`App is listening on port ${port || 3000}!`);
50
55
  });
51
56
 
57
+ async function loadModule(moduleName: string) {
58
+ return await import(moduleName);
59
+ }
60
+
52
61
  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
- }
62
+ const httpVerb = (dirent.name.indexOf('-') > -1 ? dirent.name.split('-')[0] : dirent.name.split('.')[0]) as HttpVerb;
63
+ handleRequest(path, dirent, httpVerb);
57
64
  }
58
65
 
59
- function addEndpoint(endpoint: string, model: any) {
60
- app.get(endpoint, function(req, res) {
61
- res.send(model.data);
62
- });
66
+ function addEndpoint(endpoint: string, httpVerb: HttpVerb, model: any) {
67
+ app[httpVerb](endpoint, (req, res) => res.send(model.data));
63
68
  }
64
69
 
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);
70
+ function handleRequest(path: string, dirent: fs.Dirent, httpVerb: HttpVerb) {
71
+ const endpoint = convertFileNameToEndpoint(path, dirent, httpVerb);
69
72
  const modulePath = `${path}/${dirent.name}`;
70
- console.log('Resolve module: ' + modulePath);
73
+ registeredEndpoints.push({httpVerb, endpoint});
71
74
  loadModule(modulePath)
72
- .then(model => addEndpoint(endpoint, model))
75
+ .then(model => addEndpoint(endpoint, httpVerb, model))
73
76
  .catch(err => console.error(err));
74
77
  }
75
78
 
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('-', '');
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);
82
86
  }
83
87
  return endpoint;
84
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
- };