├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── custom.md │ └── feature_request.md └── dependabot.yml ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── biome.json ├── docker-compose.yml ├── migrate.ts ├── migrations └── 1679248134387-test.ts ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── stylesheets │ └── style.css └── views │ ├── error.pug │ ├── index.pug │ └── layout.pug ├── src ├── app.ts ├── bin │ └── www.ts ├── clients │ ├── MigrationClient.ts │ └── MongooseClient.ts ├── constants │ └── events.ts ├── handlers │ └── UserHandler.ts ├── interfaces │ └── IUser.ts ├── models │ ├── User.ts │ └── index.ts ├── options │ └── mongoose.ts └── routes │ ├── index.ts │ └── users.ts ├── tests └── mongose.test.ts ├── tsconfig.json └── vite.config.mts /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 16 | 1. Go to '...' 17 | 2. Click on '....' 18 | 3. Scroll down to '....' 19 | 4. See error 20 | 21 | **Expected behavior** 22 | A clear and concise description of what you expected to happen. 23 | 24 | **Screenshots** 25 | If applicable, add screenshots to help explain your problem. 26 | 27 | **Desktop (please complete the following information):** 28 | 29 | - OS: [e.g. iOS] 30 | - Browser [e.g. chrome, safari] 31 | - Version [e.g. 22] 32 | 33 | **Smartphone (please complete the following information):** 34 | 35 | - Device: [e.g. iPhone6] 36 | - OS: [e.g. iOS8.1] 37 | - Browser [e.g. stock browser, safari] 38 | - Version [e.g. 22] 39 | 40 | **Additional context** 41 | Add any other context about the problem here. 42 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | day: "monday" 13 | ignore: 14 | - dependency-name: "sort-keys" 15 | commit-message: 16 | prefix: "Update dependencies" 17 | pull-request-branch-name: 18 | separator: "-" 19 | groups: 20 | all-dependencies: 21 | patterns: 22 | - "*" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OS X 2 | .DS_Store* 3 | Icon? 4 | ._* 5 | 6 | # Windows 7 | Thumbs.db 8 | ehthumbs.db 9 | Desktop.ini 10 | 11 | # Linux 12 | .directory 13 | *~ 14 | 15 | # npm 16 | node_modules 17 | *.log 18 | *.gz 19 | 20 | # Directories 21 | coverage 22 | dist 23 | reports 24 | 25 | # Benchmarking 26 | benchmarks/graphs 27 | 28 | # Env vars 29 | .env 30 | globalConfig.json -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "streetsidesoftware.code-spell-checker", 4 | "mikestead.dotenv", 5 | "biomejs.biome", 6 | "eamodio.gitlens", 7 | "vitest.explorer", 8 | "DavidAnson.vscode-markdownlint" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Attach to local", 9 | "port": 9229, 10 | "request": "attach", 11 | "skipFiles": ["/**"], 12 | "type": "node" 13 | }, 14 | { 15 | "name": "Compile and debug", 16 | "type": "node", 17 | "request": "launch", 18 | "preLaunchTask": "npm: build", 19 | "program": "${workspaceFolder}/src/bin/www.ts", 20 | "outFiles": ["${workspaceFolder}/dist/**/*.js"], 21 | "resolveSourceMapLocations": ["${workspaceFolder}/dist/**/*.js.map"], 22 | "env": { 23 | // To debug mongo queries add mquery 24 | "DEBUG": "http,express", 25 | "NODE_ENV": "development" 26 | }, 27 | "console": "integratedTerminal", 28 | "internalConsoleOptions": "neverOpen" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "explorer.fileNesting.enabled": true, 3 | "explorer.fileNesting.patterns": { 4 | "tsconfig.json": "tsconfig.*.json, env.d.ts", 5 | "package.json": "package-lock.json, .gitignore", 6 | "README.md": "CHANGELOG.md, CODE_OF_CONDUCT.md, CONTRIBUTING.md", 7 | "docker-compose.yml": "Dockerfile" 8 | }, 9 | "editor.tabSize": 2, 10 | "editor.insertSpaces": true, 11 | "editor.defaultFormatter": "biomejs.biome", 12 | "editor.codeActionsOnSave": { 13 | "quickfix.biome": "explicit", 14 | "source.organizeImports.biome": "explicit" 15 | }, 16 | "cSpell.words": [ 17 | "autosync", 18 | "biomejs", 19 | "ilovepixelart", 20 | "lcov", 21 | "linebreak", 22 | "parens", 23 | "singleline", 24 | "sonarjs" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "npm", 6 | "script": "build", 7 | "group": "build", 8 | "problemMatcher": [], 9 | "label": "npm: build", 10 | "detail": "tsc" 11 | } 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 4 | 5 | ## Our Standards 6 | 7 | Examples of behavior that contributes to creating a positive environment include: 8 | 9 | * Using welcoming and inclusive language 10 | * Being respectful of differing viewpoints and experiences 11 | * Gracefully accepting constructive criticism 12 | * Focusing on what is best for the community 13 | * Showing empathy towards other community members 14 | 15 | Examples of unacceptable behavior by participants include: 16 | 17 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 18 | * Trolling, insulting/derogatory comments, and personal or political attacks 19 | * Public or private harassment 20 | * Publishing others’ private information, such as a physical or electronic address, without explicit permission 21 | * Other conduct which could reasonably be considered inappropriate in a professional setting 22 | 23 | ## Our Responsibilities 24 | 25 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 26 | 27 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 28 | 29 | ## Scope 30 | 31 | This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 32 | 33 | ## Enforcement 34 | 35 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership. 36 | 37 | ## Attribution 38 | 39 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at 40 | 41 | For answers to common questions about this code of conduct, see 42 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | 1. Start an issue. We will discuss the best approach 4 | 2. Make a pull request. I'll review it and comment until we are both confident about it 5 | 3. I'll merge your PR and bump the version of the package 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:20-alpine 2 | 3 | WORKDIR /app 4 | COPY package.json package-lock.json ./ 5 | RUN npm install 6 | COPY . . 7 | 8 | EXPOSE 3000 9 | ENV PORT 3000 10 | 11 | RUN npm run build 12 | 13 | CMD ["npm", "start"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2025 ilovepixelart 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Express.js + Mongoose + TypeScript 5 + tsx 2 | 3 | * [express 5](https://expressjs.com/) - fast, unopinionated, minimalist web framework for node 4 | * [mongoose](https://mongoosejs.com/) - mongodb object modeling 5 | * [ts-migrate-mongoose](https://github.com/ilovepixelart/ts-migrate-mongoose) - mongoose migration framework 6 | * [ts-patch-mongoose](https://github.com/ilovepixelart/ts-migrate-mongoose) - mongoose patch history & events 7 | * [ts-cache-mongoose](https://github.com/ilovepixelart/ts-cache-mongoose) - mongoose cache (in-memory, redis) 8 | * [typescript 5](https://www.typescriptlang.org/) 9 | * [tsx](https://tsx.is/) - for typescript transpilation 10 | * [biome](https://biomejs.dev/) - one toolchain for your web project 11 | * [vitest](https://vitest.dev/) - vitest with mongodb-memory-server for testing 12 | 13 | Commands: 14 | 15 | ```bash 16 | npm i 17 | 18 | npm run dev # developer mode 19 | 20 | npm run build # build using tsx 21 | npm run start # production mode 22 | 23 | npm run biome # lint & format check 24 | npm run biome:fix # lint & format auto fix 25 | 26 | npm run test # to run all tests 27 | npm run test:open # to run coverage & open istanbul in the browser 28 | ``` 29 | 30 | You can run it using docker: 31 | 32 | ```bash 33 | docker compose build 34 | docker compose up 35 | ``` 36 | -------------------------------------------------------------------------------- /biome.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://biomejs.dev/schemas/2.2.0/schema.json", 3 | "vcs": { "enabled": false, "clientKind": "git", "useIgnoreFile": false }, 4 | "files": { 5 | "ignoreUnknown": false, 6 | "includes": ["src/**/*.ts", "tests/**/*.ts"] 7 | }, 8 | "formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2 }, 9 | "assist": { 10 | "actions": { 11 | "source": { 12 | "organizeImports": { 13 | "level": "on", 14 | "options": { 15 | "groups": [ 16 | "vitest", 17 | ":BLANK_LINE:", 18 | { "type": false }, 19 | ":BLANK_LINE:" 20 | ] 21 | } 22 | } 23 | } 24 | } 25 | }, 26 | "linter": { 27 | "enabled": true, 28 | "rules": { 29 | "recommended": true, 30 | "correctness": { 31 | "noUnusedVariables": "off" 32 | } 33 | } 34 | }, 35 | "javascript": { 36 | "formatter": { 37 | "trailingCommas": "all", 38 | "quoteStyle": "single", 39 | "semicolons": "asNeeded", 40 | "lineWidth": 320 41 | }, 42 | "globals": ["Atomics", "SharedArrayBuffer"] 43 | }, 44 | "json": { 45 | "formatter": { 46 | "trailingCommas": "none" 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | database: 5 | image: mongo 6 | container_name: database 7 | restart: always 8 | ports: 9 | - "27017:27017" 10 | 11 | server: 12 | container_name: server 13 | build: . 14 | ports: 15 | - "3000:3000" 16 | depends_on: 17 | - database 18 | environment: 19 | - MONGO_URI=mongodb://database:27017 20 | - MIGRATE_MONGO_URI=mongodb://database:27017 -------------------------------------------------------------------------------- /migrate.ts: -------------------------------------------------------------------------------- 1 | // Configuration file example for ts-migrate-mongoose: 2 | // You can also use .env instead of a config file 3 | 4 | export default { 5 | uri: process.env.MIGRATE_MONGO_URI ?? 'mongodb://localhost:27017/express', 6 | // "collection": "migrations", 7 | // "migrationsPath": "./migrations", 8 | // "templatePath": "./migrations/template.ts", 9 | // "autosync": false 10 | } 11 | -------------------------------------------------------------------------------- /migrations/1679248134387-test.ts: -------------------------------------------------------------------------------- 1 | import getModels from '../src/models' 2 | 3 | export async function up() { 4 | console.log('Migration - up') 5 | const { User } = await getModels() 6 | 7 | // Write migration here 8 | await User.findOneAndUpdate({ name: 'John Doe' }, { name: 'John Doe', role: 'admin' }, { upsert: true, new: true }) 9 | } 10 | 11 | export async function down() { 12 | console.log('Migration - down') 13 | const { User } = await getModels() 14 | // Write migration here 15 | await User.deleteMany({ role: 'admin' }) 16 | } 17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ts-express-tsx", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "start": "node ./dist/bin/www.js", 7 | "build": "tsc", 8 | "dev": "tsx watch src/bin/www.ts", 9 | "biome": "npx @biomejs/biome check", 10 | "biome:fix": "npx @biomejs/biome check --write .", 11 | "test": "vitest run --coverage", 12 | "test:open": "npm test && open-cli coverage/lcov-report/index.html" 13 | }, 14 | "dependencies": { 15 | "@biomejs/biome": "2.2.6", 16 | "cookie-parser": "1.4.7", 17 | "debug": "4.4.3", 18 | "dotenv": "17.2.3", 19 | "express": "5.1.0", 20 | "http-errors": "2.0.0", 21 | "mongoose": "8.19.1", 22 | "morgan": "1.10.1", 23 | "pug": "3.0.3", 24 | "ts-cache-mongoose": "1.7.5", 25 | "ts-migrate-mongoose": "4.1.0", 26 | "ts-patch-mongoose": "2.9.2" 27 | }, 28 | "devDependencies": { 29 | "@types/cookie-parser": "1.4.9", 30 | "@types/debug": "4.1.12", 31 | "@types/express": "5.0.3", 32 | "@types/http-errors": "2.0.5", 33 | "@types/morgan": "1.9.10", 34 | "@types/node": "24.8.1", 35 | "@vitest/coverage-v8": "3.2.4", 36 | "mongodb-memory-server": "10.2.3", 37 | "open-cli": "8.0.0", 38 | "tsx": "4.20.6", 39 | "typescript": "5.9.3", 40 | "vitest": "3.2.4" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ilovepixelart/ts-express-tsx/291cda520355d128996318663467622cb40a0787/public/favicon.ico -------------------------------------------------------------------------------- /public/stylesheets/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 50px; 3 | font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; 4 | } 5 | 6 | a { 7 | color: #00b7ff; 8 | } 9 | -------------------------------------------------------------------------------- /public/views/error.pug: -------------------------------------------------------------------------------- 1 | extends layout 2 | 3 | block content 4 | h1= message 5 | h2= error.status 6 | pre #{error.stack} 7 | -------------------------------------------------------------------------------- /public/views/index.pug: -------------------------------------------------------------------------------- 1 | extends layout 2 | 3 | block content 4 | h1= title 5 | p Welcome to #{title} 6 | -------------------------------------------------------------------------------- /public/views/layout.pug: -------------------------------------------------------------------------------- 1 | doctype html 2 | html 3 | head 4 | title= title 5 | link(rel='stylesheet', href='/stylesheets/style.css') 6 | body 7 | block content 8 | -------------------------------------------------------------------------------- /src/app.ts: -------------------------------------------------------------------------------- 1 | import path from 'node:path' 2 | import cookieParser from 'cookie-parser' 3 | import express from 'express' 4 | import createError from 'http-errors' 5 | import logger from 'morgan' 6 | import indexRouter from './routes/index' 7 | import usersRouter from './routes/users' 8 | 9 | import type { NextFunction, Request, Response } from 'express' 10 | import type { HttpError } from 'http-errors' 11 | 12 | const app = express() 13 | 14 | // view engine setup 15 | app.set('views', path.join(__dirname, '../public/views')) 16 | app.set('view engine', 'pug') 17 | 18 | app.use(logger('dev')) 19 | app.use(express.json()) 20 | app.use(express.urlencoded({ extended: false })) 21 | app.use(cookieParser()) 22 | app.use(express.static(path.join(__dirname, '../public'))) 23 | 24 | app.use('/', indexRouter) 25 | app.use('/users', usersRouter) 26 | 27 | // catch 404 and forward to error handler 28 | app.use((_req: Request, _res: Response, next: NextFunction) => { 29 | next(createError(404)) 30 | }) 31 | 32 | // error handler 33 | app.use((error: HttpError, req: Request, res: Response) => { 34 | // set locals, only providing error in development 35 | res.locals.message = error.message 36 | res.locals.error = req.app.get('env') === 'development' ? error : {} 37 | 38 | // render the error page 39 | res.status(error.status || 500) 40 | res.render('error') 41 | }) 42 | 43 | export default app 44 | -------------------------------------------------------------------------------- /src/bin/www.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Module dependencies. 3 | */ 4 | 5 | import dotenv from 'dotenv' 6 | 7 | dotenv.config() 8 | 9 | import http from 'node:http' 10 | import debug from 'debug' 11 | import app from '../app' 12 | import MigrationClient from '../clients/MigrationClient' 13 | import MongooseClient from '../clients/MongooseClient' 14 | 15 | import type { Server } from 'node:http' 16 | import type { HttpError } from 'http-errors' 17 | 18 | import '../handlers/UserHandler' 19 | 20 | const log = debug('ts-express-tsx:server') 21 | 22 | /** 23 | * Normalize a port into a number, string, or false. 24 | */ 25 | 26 | const normalizePort = (val: string): boolean | number | string => { 27 | const port = Number.parseInt(val, 10) 28 | if (Number.isNaN(port)) return val // named pipe 29 | if (port >= 0) return port // port number 30 | return false 31 | } 32 | 33 | const port = normalizePort(process.env.PORT ?? '3000') 34 | 35 | /** 36 | * Event listener for HTTP server "error" event. 37 | */ 38 | 39 | const onError = (error: HttpError): void => { 40 | if (error.syscall !== 'listen') { 41 | throw error 42 | } 43 | 44 | const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port.toString()}` 45 | 46 | // handle specific listen errors with friendly messages 47 | if (error.code === 'EACCES') { 48 | console.error(`${bind} requires elevated privileges`) 49 | process.exit(1) 50 | } else if (error.code === 'EADDRINUSE') { 51 | console.error(`${bind} is already in use`) 52 | process.exit(1) 53 | } else { 54 | throw error 55 | } 56 | } 57 | 58 | /** 59 | * Event listener for HTTP server "listening" event. 60 | */ 61 | 62 | const onListening = (server: Server): void => { 63 | let bind = 'unknown' 64 | const addr = server.address() 65 | if (typeof addr === 'string') { 66 | bind = `pipe ${addr}` 67 | } else if (addr) { 68 | bind = `port ${addr.port.toString()}` 69 | } 70 | 71 | log(`Listening on ${bind}`) 72 | } 73 | 74 | const start = async (): Promise => { 75 | await MongooseClient.connect() 76 | await MigrationClient.connect() 77 | 78 | /** 79 | * Get port from environment and store in Express. 80 | */ 81 | 82 | app.set('port', port) 83 | 84 | /** 85 | * Create HTTP server. 86 | */ 87 | 88 | const server = http.createServer(app) 89 | 90 | /** 91 | * Listen on provided port, on all network interfaces. 92 | */ 93 | 94 | server.listen(port) 95 | server.on('error', (error: HttpError) => { 96 | onError(error) 97 | }) 98 | server.on('listening', () => { 99 | onListening(server) 100 | }) 101 | } 102 | 103 | start().catch((error: unknown) => { 104 | log(error) 105 | process.exit(1) 106 | }) 107 | -------------------------------------------------------------------------------- /src/clients/MigrationClient.ts: -------------------------------------------------------------------------------- 1 | import { Migrator } from 'ts-migrate-mongoose' 2 | 3 | export default { 4 | connect: async (): Promise => { 5 | const migrator = await Migrator.connect({ 6 | uri: process.env.MONGO_URI ?? 'mongodb://localhost:27017/express', 7 | autosync: true, 8 | }) 9 | 10 | console.info('Running migrations...') 11 | 12 | await migrator 13 | .run('down', 'test') 14 | .then((migrations) => { 15 | for (const migration of migrations) { 16 | console.info('down:', migration.filename) 17 | } 18 | }) 19 | .catch((error: unknown) => { 20 | console.error(error) 21 | }) 22 | 23 | await migrator.prune() 24 | 25 | await migrator 26 | .run('up') 27 | .then((migrations) => { 28 | for (const migration of migrations) { 29 | console.info('up:', migration.filename) 30 | } 31 | }) 32 | .catch((error: unknown) => { 33 | console.error(error) 34 | }) 35 | 36 | await migrator.close() 37 | }, 38 | } 39 | -------------------------------------------------------------------------------- /src/clients/MongooseClient.ts: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose' 2 | import cache from 'ts-cache-mongoose' 3 | import optionsMongoose from '../options/mongoose' 4 | 5 | import type { Mongoose, MongooseError } from 'mongoose' 6 | 7 | // Run project, open localhost:3000/users to see the cache in action, by refreshing the page 8 | cache.init(mongoose, { 9 | engine: 'memory', 10 | // This is for demo purposes, you should not use this in production 11 | debug: true, 12 | }) 13 | 14 | // In case you using mongoose 6 15 | // https://mongoosejs.com/docs/guide.html#strictQuery 16 | mongoose.set('strictQuery', false) 17 | 18 | mongoose.connection.on('error', (error: MongooseError) => { 19 | console.error(error.message) 20 | }) 21 | 22 | mongoose.connection.on('connecting', () => { 23 | console.info('Connecting to MongoDB...') 24 | }) 25 | 26 | mongoose.connection.on('connected', () => { 27 | console.info('Connected to MongoDB') 28 | }) 29 | 30 | mongoose.connection.on('disconnected', () => { 31 | console.info('Disconnected from MongoDB') 32 | }) 33 | 34 | mongoose.connection.on('reconnect', () => { 35 | console.info('Reconnecting to MongoDB...') 36 | }) 37 | 38 | export default { 39 | connect: async (): Promise => { 40 | await mongoose.connect(process.env.MONGO_URI ?? 'mongodb://localhost:27017/express', optionsMongoose) 41 | return mongoose 42 | }, 43 | isConnected: (): boolean => Number(mongoose.connection.readyState) === 1, 44 | } 45 | -------------------------------------------------------------------------------- /src/constants/events.ts: -------------------------------------------------------------------------------- 1 | export const USER_CREATED = 'user-created' 2 | export const USER_UPDATED = 'user-updated' 3 | export const USER_DELETED = 'user-deleted' 4 | -------------------------------------------------------------------------------- /src/handlers/UserHandler.ts: -------------------------------------------------------------------------------- 1 | import { patchEventEmitter } from 'ts-patch-mongoose' 2 | import { USER_CREATED, USER_DELETED, USER_UPDATED } from '../constants/events' 3 | 4 | patchEventEmitter.on(USER_CREATED, ({ doc }) => { 5 | try { 6 | console.log('Event - user created', doc) 7 | // Do something with doc here 8 | } catch (error) { 9 | console.error(error) 10 | } 11 | }) 12 | 13 | patchEventEmitter.on(USER_UPDATED, ({ doc, oldDoc, patch }) => { 14 | try { 15 | console.log('Event - user updated', doc, oldDoc, patch) 16 | // Do something with doc, oldDoc and patch here 17 | } catch (error) { 18 | console.error(error) 19 | } 20 | }) 21 | 22 | patchEventEmitter.on(USER_DELETED, ({ oldDoc }) => { 23 | try { 24 | console.log('Event - user deleted', oldDoc) 25 | // Do something with doc here 26 | } catch (error) { 27 | console.error(error) 28 | } 29 | }) 30 | -------------------------------------------------------------------------------- /src/interfaces/IUser.ts: -------------------------------------------------------------------------------- 1 | interface IUser { 2 | name: string 3 | role: string 4 | createdAt?: Date 5 | updatedAt?: Date 6 | } 7 | 8 | export default IUser 9 | -------------------------------------------------------------------------------- /src/models/User.ts: -------------------------------------------------------------------------------- 1 | import { model, models, Schema } from 'mongoose' 2 | import { patchHistoryPlugin } from 'ts-patch-mongoose' 3 | import { USER_CREATED, USER_DELETED, USER_UPDATED } from '../constants/events' 4 | 5 | import type { Model } from 'mongoose' 6 | import type IUser from '../interfaces/IUser' 7 | 8 | const UserSchema = new Schema( 9 | { 10 | name: { 11 | type: String, 12 | required: true, 13 | index: true, 14 | }, 15 | role: { 16 | type: String, 17 | required: true, 18 | enum: ['admin', 'manager', 'user'], 19 | index: true, 20 | }, 21 | }, 22 | { timestamps: true }, 23 | ) 24 | 25 | UserSchema.plugin(patchHistoryPlugin, { 26 | eventCreated: USER_CREATED, 27 | eventUpdated: USER_UPDATED, 28 | eventDeleted: USER_DELETED, 29 | omit: ['__v', 'createdAt', 'updatedAt'], 30 | }) 31 | 32 | const User = (models.User as Model | undefined) ?? model('User', UserSchema) 33 | 34 | export default User 35 | -------------------------------------------------------------------------------- /src/models/index.ts: -------------------------------------------------------------------------------- 1 | import MongooseClient from '../clients/MongooseClient' 2 | import User from './User' 3 | 4 | import type { Model, Mongoose } from 'mongoose' 5 | import type IUser from '../interfaces/IUser' 6 | 7 | const getModels = async (): Promise<{ 8 | mongoose: Mongoose 9 | User: Model 10 | }> => { 11 | const mongoose = await MongooseClient.connect() 12 | 13 | return { 14 | mongoose, 15 | User, 16 | } 17 | } 18 | 19 | export default getModels 20 | -------------------------------------------------------------------------------- /src/options/mongoose.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | autoIndex: true, 3 | } 4 | -------------------------------------------------------------------------------- /src/routes/index.ts: -------------------------------------------------------------------------------- 1 | import { Router } from 'express' 2 | 3 | import type { Request, Response } from 'express' 4 | 5 | const router = Router() 6 | 7 | /* GET home page. */ 8 | router.get('/', (_req: Request, res: Response) => { 9 | res.render('index', { title: 'Express' }) 10 | }) 11 | 12 | export default router 13 | -------------------------------------------------------------------------------- /src/routes/users.ts: -------------------------------------------------------------------------------- 1 | import { Router } from 'express' 2 | import User from '../models/User' 3 | 4 | import type { Request, Response } from 'express' 5 | 6 | const router = Router() 7 | 8 | /* GET users listing. */ 9 | router.get('/', async (_req: Request, res: Response) => { 10 | const users = await User.find().select({ _id: 0, name: 1, role: 1 }).cache('1 minute').exec() 11 | res.json(users) 12 | }) 13 | 14 | export default router 15 | -------------------------------------------------------------------------------- /tests/mongose.test.ts: -------------------------------------------------------------------------------- 1 | import { afterAll, beforeAll, describe, expect, it } from 'vitest' 2 | 3 | import { MongoMemoryServer } from 'mongodb-memory-server' 4 | import mongoose from 'mongoose' 5 | 6 | describe('mongoose', async () => { 7 | const mongod = await MongoMemoryServer.create() 8 | 9 | beforeAll(async () => { 10 | const uri = mongod.getUri() 11 | await mongoose.connect(uri) 12 | }) 13 | 14 | afterAll(async () => { 15 | await mongoose.connection.dropDatabase() 16 | await mongoose.connection.close() 17 | await mongod.stop() 18 | }) 19 | 20 | it('should insert a doc into collection', async () => { 21 | const users = mongoose.connection.db?.collection('users') 22 | 23 | const mockUser = { name: 'John' } 24 | const user = await users?.insertOne(mockUser) 25 | 26 | const insertedUser = await users?.findOne({ _id: user?.insertedId }) 27 | expect(insertedUser).toEqual(mockUser) 28 | }) 29 | }) 30 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src"], 3 | "compilerOptions": { 4 | "target": "ES2021", 5 | "lib": ["ES2021"], 6 | "types": ["node"], 7 | "module": "CommonJS", 8 | "moduleResolution": "Node", 9 | "outDir": "dist", 10 | "strict": true, 11 | "allowSyntheticDefaultImports": true, 12 | "allowUnreachableCode": false, 13 | "allowUnusedLabels": false, 14 | "checkJs": true, 15 | "declaration": true, 16 | "declarationMap": true, 17 | "esModuleInterop": true, 18 | "exactOptionalPropertyTypes": true, 19 | "forceConsistentCasingInFileNames": true, 20 | "importHelpers": true, 21 | "isolatedModules": true, 22 | "noEmitOnError": true, 23 | "noFallthroughCasesInSwitch": true, 24 | "noImplicitOverride": true, 25 | "noImplicitReturns": true, 26 | "noUncheckedIndexedAccess": true, 27 | "noUnusedLocals": true, 28 | "noUnusedParameters": true, 29 | "removeComments": true, 30 | "skipLibCheck": true, 31 | "sourceMap": true 32 | }, 33 | } 34 | -------------------------------------------------------------------------------- /vite.config.mts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitest/config' 2 | 3 | export default defineConfig({ 4 | test: { 5 | include: ['tests/**/*.test.ts'], 6 | name: 'node', 7 | environment: 'node', 8 | coverage: { 9 | reporter: ['lcov'], 10 | }, 11 | }, 12 | }) 13 | --------------------------------------------------------------------------------