express-generator-typescript 2.7.8 → 2.7.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.
Files changed (42) hide show
  1. package/lib/project-files/README.md +65 -0
  2. package/lib/project-files/config/.env.development +15 -0
  3. package/lib/project-files/config/.env.production +15 -0
  4. package/lib/project-files/config/.env.test +14 -0
  5. package/lib/project-files/config.ts +22 -0
  6. package/lib/project-files/eslint.config.ts +100 -0
  7. package/lib/project-files/gitignore +6 -0
  8. package/lib/project-files/package.json +56 -0
  9. package/lib/project-files/scripts/build.ts +28 -0
  10. package/lib/project-files/scripts/common/utils.ts +93 -0
  11. package/lib/project-files/src/common/constants/ENV.ts +19 -0
  12. package/lib/project-files/src/common/constants/HTTP_STATUS_CODES.ts +81 -0
  13. package/lib/project-files/src/common/constants/PATHS.ts +15 -0
  14. package/lib/project-files/src/common/constants/index.ts +11 -0
  15. package/lib/project-files/src/common/util/misc.ts +11 -0
  16. package/lib/project-files/src/common/util/route-errors.ts +38 -0
  17. package/lib/project-files/src/common/util/validators.ts +14 -0
  18. package/lib/project-files/src/index.ts +27 -0
  19. package/lib/project-files/src/models/User.ts +68 -0
  20. package/lib/project-files/src/models/common/types.ts +5 -0
  21. package/lib/project-files/src/public/stylesheets/users.css +48 -0
  22. package/lib/project-files/src/repos/MockOrm.ts +63 -0
  23. package/lib/project-files/src/repos/UserRepo.ts +134 -0
  24. package/lib/project-files/src/repos/database.json +1 -0
  25. package/lib/project-files/src/repos/database.test.json +1 -0
  26. package/lib/project-files/src/routes/UserRoutes.ts +69 -0
  27. package/lib/project-files/src/routes/common/types/index.ts +10 -0
  28. package/lib/project-files/src/routes/common/util/index.ts +16 -0
  29. package/lib/project-files/src/routes/index.ts +31 -0
  30. package/lib/project-files/src/server.ts +86 -0
  31. package/lib/project-files/src/services/UserService.ts +70 -0
  32. package/lib/project-files/src/views/users.html +132 -0
  33. package/lib/project-files/tests/aux/setup.ts +26 -0
  34. package/lib/project-files/tests/common/types.ts +16 -0
  35. package/lib/project-files/tests/common/utils.ts +55 -0
  36. package/lib/project-files/tests/users.test.ts +133 -0
  37. package/lib/project-files/tsconfig.json +35 -0
  38. package/lib/project-files/tsconfig.prod.json +30 -0
  39. package/lib/project-files/vitest.config.mts +18 -0
  40. package/package.json +1 -1
  41. package/README-git +0 -78
  42. package/express-typescript.png +0 -0
@@ -0,0 +1,132 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <!-- Head -->
5
+ <head>
6
+ <meta charset="UTF-8">
7
+ <title>Users</title>
8
+ <link rel="stylesheet" type="text/css" href="/stylesheets/users.css" />
9
+
10
+ <!-- Handlebars -->
11
+ <script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.8/handlebars.min.js"></script>
12
+
13
+ <!-- Bootstrap -->
14
+ <link
15
+ href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
16
+ rel="stylesheet"
17
+ integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
18
+ crossorigin="anonymous"
19
+ />
20
+ <script
21
+ src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
22
+ integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
23
+ crossorigin="anonymous"
24
+ ></script>
25
+ </head>
26
+
27
+ <!-- Body -->
28
+ <body>
29
+
30
+ <!-- Add Users -->
31
+ <div class="users-column add-user-col">
32
+ <div class="column-header">
33
+ Add User:
34
+ </div>
35
+ <div>
36
+ <input
37
+ id="name-input"
38
+ type="text"
39
+ class="form-control"
40
+ placeholder="Name"
41
+ />
42
+ </div>
43
+ <div>
44
+ <input
45
+ id="email-input"
46
+ type="email"
47
+ class="form-control"
48
+ placeholder="Email"
49
+ />
50
+ </div>
51
+ <div>
52
+ <button
53
+ id="add-user-btn"
54
+ class="btn btn-success"
55
+ >
56
+ Add
57
+ </button>
58
+ </div>
59
+ </div>
60
+
61
+ <!-- Display Users -->
62
+ <div class="users-column">
63
+ <div class="column-header">
64
+ Users:
65
+ </div>
66
+
67
+ <div id="all-users-anchor"></div>
68
+ <script
69
+ id="all-users-template"
70
+ type="text/x-handlebars-template"
71
+ >
72
+ {{#each users}}
73
+ <div class="user-display-ele">
74
+ <div class="normal-view">
75
+ <div><b>Name:</b> {{name}}</div>
76
+ <div><b>Email:</b> {{email}}</div>
77
+ <div><b>Created:</b> {{createdFormatted}}</div>
78
+ <button
79
+ type="button"
80
+ class="btn btn-primary edit-user-btn"
81
+ data-user-id="{{id}}"
82
+ >
83
+ Edit
84
+ </button>
85
+ <button
86
+ class="btn btn-danger delete-user-btn"
87
+ data-user-id="{{id}}"
88
+ >
89
+ Delete
90
+ </button>
91
+ </div>
92
+
93
+ <div class="edit-view">
94
+ <div>
95
+ Name:&nbsp;
96
+ <input
97
+ type="text"
98
+ class="form-control name-edit-input"
99
+ value="{{name}}"
100
+ />
101
+ </div>
102
+ <div class="email-edit">
103
+ Email:&nbsp;
104
+ <input
105
+ type="email"
106
+ class="form-control email-edit-input"
107
+ value="{{email}}"
108
+ />
109
+ </div>
110
+ <button
111
+ class="btn btn-primary submit-edit-btn"
112
+ data-user-id="{{id}}"
113
+ data-user-created="{{created}}"
114
+ >
115
+ Submit
116
+ </button>
117
+ <button
118
+ class="btn btn-secondary cancel-edit-btn"
119
+ data-user-id="{{id}}"
120
+ >
121
+ Cancel
122
+ </button>
123
+ </div>
124
+ </div>
125
+ {{/each}}
126
+ </script>
127
+ </div>
128
+ </body>
129
+
130
+ <script src="scripts/http.js"></script>
131
+ <script src="scripts/users.js"></script>
132
+ </html>
@@ -0,0 +1,26 @@
1
+
2
+ import { beforeAll } from 'vitest';
3
+ import supertest, { Test } from 'supertest';
4
+ import TestAgent from 'supertest/lib/agent';
5
+
6
+ import app from '@src/server';
7
+ import MockOrm from '@src/repos/MockOrm';
8
+
9
+
10
+ /******************************************************************************
11
+ Run
12
+ ******************************************************************************/
13
+
14
+ let agent: TestAgent<Test>;
15
+
16
+ beforeAll(async () => {
17
+ agent = supertest.agent(app);
18
+ await MockOrm.cleanDb();
19
+ });
20
+
21
+
22
+ /******************************************************************************
23
+ Export
24
+ ******************************************************************************/
25
+
26
+ export { agent };
@@ -0,0 +1,16 @@
1
+ import { Response } from 'supertest';
2
+
3
+
4
+ /******************************************************************************
5
+ Types
6
+ ******************************************************************************/
7
+
8
+ // Use generics to add properties to 'body'
9
+ export type TRes<T = object> = Omit<Response, 'body'> & {
10
+ body: T & { error?: string | IErrorObject },
11
+ };
12
+
13
+ interface IErrorObject {
14
+ message: string;
15
+ [key: string]: unknown;
16
+ }
@@ -0,0 +1,55 @@
1
+ import { IParseObjectError, parseJson } from 'jet-validators/utils';
2
+ import { isString } from 'jet-validators';
3
+ import { IUser } from '@src/models/User';
4
+
5
+ /******************************************************************************
6
+ Types
7
+ ******************************************************************************/
8
+
9
+ type TUserArray = IUser[] | readonly IUser[];
10
+
11
+ interface IValidationError {
12
+ message: string;
13
+ errors: IParseObjectError[];
14
+ }
15
+
16
+ /******************************************************************************
17
+ Functions
18
+ ******************************************************************************/
19
+
20
+ /**
21
+ * JSON parse a validation error.
22
+ */
23
+ export function parseValidationError(arg: unknown): IValidationError {
24
+ if (!isString(arg)) {
25
+ throw new Error('Not a string');
26
+ }
27
+ return parseJson<IValidationError>(arg);
28
+ }
29
+
30
+ /**
31
+ * Compare to user arrays. Order does not matter and this assumes the email
32
+ * field is unique
33
+ */
34
+ export function compareUserArrays(a: TUserArray, b: TUserArray): boolean {
35
+ if (a.length !== b.length) return false;
36
+ const aSorted = sortByEmail(a);
37
+ const bSorted = sortByEmail(b);
38
+ for (let i = 0; i < aSorted.length; i++) {
39
+ const a = aSorted[i],
40
+ b = bSorted[i];
41
+ if (a.email !== b.email || a.name !== b.name) {
42
+ return false;
43
+ }
44
+ }
45
+ return true;
46
+ }
47
+
48
+ /**
49
+ * Sort user array by email.
50
+ */
51
+ function sortByEmail(arr: TUserArray): IUser[] {
52
+ return [...arr].sort((x, y) => {
53
+ return x.email.localeCompare(y.email);
54
+ });
55
+ }
@@ -0,0 +1,133 @@
1
+ import UserRepo from '@src/repos/UserRepo';
2
+ import User, { IUser } from '@src/models/User';
3
+ import { USER_NOT_FOUND_ERR } from '@src/services/UserService';
4
+
5
+ import HTTP_STATUS_CODES from '@src/common/constants/HTTP_STATUS_CODES';
6
+ import { ValidationError } from '@src/common/util/route-errors';
7
+ import { JET_PATHS as Paths } from '@src/common/constants/PATHS';
8
+
9
+ import { compareUserArrays, parseValidationError } from './common/utils';
10
+ import { agent } from './aux/setup';
11
+ import { TRes } from './common/types';
12
+
13
+ /******************************************************************************
14
+ Constants
15
+ ******************************************************************************/
16
+
17
+ // Dummy users for GET req
18
+ const DB_USERS = [
19
+ User.new({ name: 'Sean Maxwell', email: 'sean.maxwell@gmail.com' }),
20
+ User.new({ name: 'John Smith', email: 'john.smith@gmail.com' }),
21
+ User.new({ name: 'Gordan Freeman', email: 'gordan.freeman@gmail.com' }),
22
+ ] as const;
23
+
24
+ /******************************************************************************
25
+ Tests
26
+ IMPORTANT: Following TypeScript best practices, we test all scenarios that
27
+ can be triggered by a user under normal circumstances. Not all theoretically
28
+ scenarios (i.e. a failed database connection).
29
+ ******************************************************************************/
30
+
31
+ describe('UserRouter', () => {
32
+
33
+ let dbUsers: IUser[] = [];
34
+
35
+ // Run before all tests
36
+ beforeEach(async () => {
37
+ await UserRepo.deleteAllUsers();
38
+ dbUsers = await UserRepo.insertMult(DB_USERS);
39
+ });
40
+
41
+ // Get all users
42
+ describe(`"GET:${Paths.Users.Get}"`, () => {
43
+
44
+ // Success
45
+ it('should return a JSON object with all the users and a status code ' +
46
+ `of "${HTTP_STATUS_CODES.Ok}" if the request was successful.`, async () => {
47
+ const res: TRes<{ users: IUser[]}> = await agent.get(Paths.Users.Get);
48
+ expect(res.status).toBe(HTTP_STATUS_CODES.Ok);
49
+ expect(compareUserArrays(res.body.users, DB_USERS)).toBeTruthy();
50
+ });
51
+ });
52
+
53
+ // Test add user
54
+ describe(`"POST:${Paths.Users.Add}"`, () => {
55
+
56
+ // Test add user success
57
+ it(`should return a status code of "${HTTP_STATUS_CODES.Created}" if ` +
58
+ 'the request was successful.', async () => {
59
+ const user = User.new({ name: 'a', email: 'a@a.com' }),
60
+ res = await agent.post(Paths.Users.Add).send({ user });
61
+ expect(res.status).toBe(HTTP_STATUS_CODES.Created);
62
+ });
63
+
64
+ // Missing param
65
+ it('should return a JSON object with an error message of and a status ' +
66
+ `code of "${HTTP_STATUS_CODES.BadRequest}" if the user param was ` +
67
+ 'missing.', async () => {
68
+ const res: TRes = await agent.post(Paths.Users.Add).send({ user: null });
69
+ expect(res.status).toBe(HTTP_STATUS_CODES.BadRequest);
70
+ const errorObj = parseValidationError(res.body.error);
71
+ expect(errorObj.message).toBe(ValidationError.MESSAGE);
72
+ expect(errorObj.errors[0].prop).toBe('user');
73
+ });
74
+ });
75
+
76
+ // Update users
77
+ describe(`"PUT:${Paths.Users.Update}"`, () => {
78
+
79
+ // Success
80
+ it(`should return a status code of "${HTTP_STATUS_CODES.Ok}" if the ` +
81
+ 'request was successful.', async () => {
82
+ const user = DB_USERS[0];
83
+ user.name = 'Bill';
84
+ const res = await agent.put(Paths.Users.Update).send({ user });
85
+ expect(res.status).toBe(HTTP_STATUS_CODES.Ok);
86
+ });
87
+
88
+ // Id is the wrong data type
89
+ it('should return a JSON object with an error message and a status code ' +
90
+ `of "${HTTP_STATUS_CODES.BadRequest}" if the user param was missing`,
91
+ async () => {
92
+ const user = User.new();
93
+ user.id = ('5' as unknown as number);
94
+ const res: TRes = await agent.put(Paths.Users.Update).send({ user });
95
+ expect(res.status).toBe(HTTP_STATUS_CODES.BadRequest);
96
+ const errorObj = parseValidationError(res.body.error);
97
+ expect(errorObj.message).toBe(ValidationError.MESSAGE);
98
+ expect(errorObj.errors[0].prop).toBe('user');
99
+ expect(errorObj.errors[0].children?.[0].prop).toBe('id');
100
+ });
101
+
102
+ // User not found
103
+ it('should return a JSON object with the error message of ' +
104
+ `"${USER_NOT_FOUND_ERR}" and a status code of ` +
105
+ `"${HTTP_STATUS_CODES.NotFound}" if the id was not found.`, async () => {
106
+ const user = User.new({ id: 4, name: 'a', email: 'a@a.com' }),
107
+ res: TRes = await agent.put(Paths.Users.Update).send({ user });
108
+ expect(res.status).toBe(HTTP_STATUS_CODES.NotFound);
109
+ expect(res.body.error).toBe(USER_NOT_FOUND_ERR);
110
+ });
111
+ });
112
+
113
+ // Delete User
114
+ describe(`"DELETE:${Paths.Users.Delete()}"`, () => {
115
+
116
+ // Success
117
+ it(`should return a status code of "${HTTP_STATUS_CODES.Ok}" if the ` +
118
+ 'request was successful.', async () => {
119
+ const id = dbUsers[0].id,
120
+ res = await agent.delete(Paths.Users.Delete(id));
121
+ expect(res.status).toBe(HTTP_STATUS_CODES.Ok);
122
+ });
123
+
124
+ // User not found
125
+ it('should return a JSON object with the error message of ' +
126
+ `"${USER_NOT_FOUND_ERR}" and a status code of ` +
127
+ `"${HTTP_STATUS_CODES.NotFound}" if the id was not found.`, async () => {
128
+ const res: TRes = await agent.delete(Paths.Users.Delete(-1));
129
+ expect(res.status).toBe(HTTP_STATUS_CODES.NotFound);
130
+ expect(res.body.error).toBe(USER_NOT_FOUND_ERR);
131
+ });
132
+ });
133
+ });
@@ -0,0 +1,35 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "CommonJS",
5
+ "lib": ["ES2020"],
6
+ "strict": true,
7
+ "baseUrl": "./",
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true,
10
+ "forceConsistentCasingInFileNames": true,
11
+ "paths": {
12
+ "@src/*": ["src/*"]
13
+ },
14
+ "useUnknownInCatchVariables": false,
15
+ "types": ["vitest/globals"],
16
+ },
17
+ "ts-node": {
18
+ "swc": true,
19
+ "require": [
20
+ "tsconfig-paths/register",
21
+ "./config.ts"
22
+ ],
23
+ },
24
+ "include": [
25
+ "src/**/*.ts",
26
+ "tests/**/*.ts",
27
+ "config.ts",
28
+ "scripts",
29
+ "eslint.config.ts",
30
+ "vitest.config.mts"
31
+ ],
32
+ "exclude": [
33
+ "src/public/*"
34
+ ]
35
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "CommonJS",
5
+ "lib": ["ES2020"],
6
+ "strict": true,
7
+ "baseUrl": "./",
8
+ "outDir": "temp",
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "forceConsistentCasingInFileNames": true,
12
+ "paths": {
13
+ "@src/*": ["src/*"]
14
+ },
15
+ "useUnknownInCatchVariables": false,
16
+ "sourceMap": false,
17
+ "removeComments": true
18
+ },
19
+ "include": [
20
+ "src/**/*.ts",
21
+ "config.ts"
22
+ ],
23
+ "exclude": [
24
+ "tests",
25
+ "src/public/",
26
+ "scripts",
27
+ "eslint.config.ts",
28
+ "vitest.config.js"
29
+ ]
30
+ }
@@ -0,0 +1,18 @@
1
+ import { defineConfig } from 'vitest/config';
2
+ import path from 'path';
3
+
4
+ const config = defineConfig({
5
+ test: {
6
+ globals: true,
7
+ environment: 'node',
8
+ setupFiles: ['config.ts', './tests/aux/setup.ts'],
9
+ isolate: true,
10
+ },
11
+ resolve: {
12
+ alias: {
13
+ '@src': path.resolve(__dirname, './src'),
14
+ },
15
+ },
16
+ });
17
+
18
+ export default config;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-generator-typescript",
3
- "version": "2.7.8",
3
+ "version": "2.7.9",
4
4
  "description": "Generate new Express applications similar to express-generate which but sets it up to use TypeScript instead",
5
5
  "scripts": {
6
6
  "express-generator-typescript": "node bin/cli.js",
package/README-git DELETED
@@ -1,78 +0,0 @@
1
- <p align="center">
2
- <img alt="express-generator-typescript" src="https://github.com/seanpmaxwell/express-generator-typescript/raw/master/express-typescript.png" width="420">
3
- </p>
4
-
5
- <p align="center">
6
- <a href="https://www.npmjs.com/package/express-generator-typescript"><img src="https://img.shields.io/npm/v/express-generator-typescript.svg?style=for-the-badge&logo=npm" alt="NPM Version"></a>
7
- <a href="https://www.npmjs.com/package/express-generator-typescript"><img src="https://img.shields.io/npm/dm/express-generator-typescript.svg?style=for-the-badge" alt="NPM Downloads"></a>
8
- <a href="https://www.npmjs.com/package/express-generator-typescript"><img src="https://img.shields.io/npm/l/express-generator-typescript.svg?style=for-the-badge" alt="License"></a>
9
- </p>
10
-
11
- # express-generator-typescript
12
-
13
- Command line tool which generates production-ready express templates with TypeScript baked in. Spin up a web server in seconds that follows the [TypeScript best practices](https://github.com/seanpmaxwell/Typescript-Best-Practices/blob/main/README.md).
14
-
15
- ## Overview
16
-
17
- `express-generator-typescript` creates a new Express application similar to the classic `express-generator` package, but the generated project is fully wired for TypeScript. You get strict typing, linting, hot reloading, production builds, testing utilities, and sane defaults that focus on APIs (no view engine or opinionated ORM). Path aliases are preconfigured through `tsconfig-paths` and `_moduleAliases`, so referencing modules stays clean even as the app grows.
18
-
19
- ## Features
20
-
21
- - **TypeScript-first** – strict compiler settings, linting, and sensible tsconfig defaults ready to go.
22
- - **API-centric** – no view engine or extra dependencies; ideal for SPAs, mobile backends, or services.
23
- - **Productivity tooling** – includes nodemon, ts-node, hot reload scripts, Jest, ESLint, and production builds.
24
- - **Path aliases** – aliases configured in `tsconfig.json` and `preload.js` so you can import modules cleanly.
25
- - **Keeps dependencies lean** – no bundled ORM or UI layers; only the essentials for Express + TS development.
26
-
27
- ## Installation
28
-
29
- ```bash
30
- npx express-generator-typescript
31
- # or install globally
32
- npm install -g express-generator-typescript
33
- ```
34
-
35
- ## Quick Start
36
-
37
- ```bash
38
- # generate a project (defaults to express-gen-ts)
39
- npx express-generator-typescript my-api
40
-
41
- cd my-api
42
-
43
- # start developing at http://localhost:3000
44
- npm run dev
45
- ```
46
-
47
- Use `--use-yarn` if you prefer Yarn over npm. If you omit the project name, the generator creates `express-gen-ts`.
48
-
49
- ## CLI Options
50
-
51
- | Option | Description |
52
- | ----------------- | --------------------------------------------------------------------------- |
53
- | `project name` | Folder to create. Defaults to `express-gen-ts` if omitted. |
54
- | `--use-yarn` | Installs dependencies with Yarn instead of npm. |
55
-
56
- > The historical `--with-auth` switch was removed in v2.5+. For an auth-ready example see the [express-jsonwebtoken-demo](https://github.com/seanpmaxwell/express-jsonwebtoken-demo) project.
57
-
58
- ## Sample Project
59
-
60
- The generated code includes CRUD routes for illustrative `User` resources to demonstrate controllers, services, and routing patterns in Express + TypeScript. Replace these samples with your own modules after scaffolding.
61
-
62
- ## Available Scripts
63
-
64
- - `npm run dev` / `npm run dev:hot` – Run the server with live reload.
65
- - `npm run test` / `npm run test:hot` – Execute all Jest tests, optionally with watch mode.
66
- - `npm run test -- users.test.ts` – Target a single test file.
67
- - `npm run lint` – Run ESLint checks.
68
- - `npm run build` – Compile the project for production.
69
- - `npm start` – Serve the built project.
70
- - `npm run type-check` – Run the TypeScript compiler without emitting files.
71
-
72
- ## Debugging
73
-
74
- Development uses `nodemon` so the server restarts when files change. To enable the Node.js inspector, edit `nodemonConfig` in `package.json` (and `spec/nodemon.json` for tests) and change the `exec` value from `ts-node` to `node --inspect -r ts-node/register`.
75
-
76
- ## License
77
-
78
- [MIT](LICENSE)
Binary file