├── .env.example ├── .gitattributes ├── .gitignore ├── .husky ├── commit-msg └── pre-commit ├── .vscode ├── extensions.json └── settings.json ├── LICENSE ├── README.md ├── docker-compose.yml ├── eslint.config.mjs ├── nest-cli.json ├── package.json ├── src ├── app │ ├── app.base.controller.ts │ ├── app.constant.ts │ └── app.module.ts ├── configs │ ├── app.ts │ ├── database.ts │ ├── index.ts │ ├── rmq.ts │ └── swagger.ts ├── db.ts ├── entities │ ├── base.entity.ts │ ├── system-log.entity.ts │ ├── terms-of-service-translation.entity.ts │ ├── terms-of-service.entity.ts │ ├── todo.entity.ts │ └── user.entity.ts ├── main.ts ├── modules │ ├── auth │ │ ├── auth.constant.ts │ │ ├── auth.module.ts │ │ ├── auth.public.controller.ts │ │ ├── auth.service.ts │ │ ├── dtos │ │ │ └── log-in.dto.ts │ │ ├── guards │ │ │ ├── jwt-admin.guard.ts │ │ │ ├── jwt-user.guard.ts │ │ │ └── secret.guard.ts │ │ ├── responses │ │ │ └── log-in.response.ts │ │ └── strategies │ │ │ ├── jwt.strategy.ts │ │ │ └── secret.strategy.ts │ ├── system-log │ │ ├── system-log.interface.ts │ │ ├── system-log.module.ts │ │ └── system-log.service.ts │ ├── terms-of-service │ │ ├── terms-of-service.interface.ts │ │ ├── terms-of-service.module.ts │ │ └── terms-of-service.service.ts │ ├── todo │ │ ├── todo.constant.ts │ │ ├── todo.interface.ts │ │ ├── todo.module.ts │ │ └── todo.service.ts │ └── user │ │ ├── user.constant.ts │ │ ├── user.interface.ts │ │ ├── user.module.ts │ │ ├── user.schedule.ts │ │ └── user.service.ts ├── platforms │ ├── admin │ │ ├── admin.module.ts │ │ ├── admin.protected.controller.ts │ │ ├── dtos │ │ │ ├── create-admin-user.dto.ts │ │ │ └── upsert-terms-of-service.dto.ts │ │ └── responses │ │ │ ├── formatted-user.response.ts │ │ │ └── upsert-terms-of-service.response.ts │ ├── app │ │ └── app.module.ts │ └── web │ │ ├── dtos │ │ ├── create-todo.dto.ts │ │ ├── register.dto.ts │ │ └── update-todo.dto.ts │ │ ├── responses │ │ ├── create-todo.response.ts │ │ ├── formatted-todo.response.ts │ │ ├── get-latest-terms-of-service.response.ts │ │ └── get-todo-details.response.ts │ │ ├── web.module.ts │ │ ├── web.protected.controller.ts │ │ └── web.public.controller.ts └── utils │ ├── decorator.ts │ ├── rmq.ts │ ├── swagger.ts │ └── time.ts ├── tsconfig.json └── yarn.lock /.env.example: -------------------------------------------------------------------------------- 1 | # App (src/configs/app.ts) 2 | APP_NAME=NestJS Demo 3 | APP_HOST=localhost 4 | APP_PORT=3000 5 | APP_SECRET=IamNotASecret 6 | APP_SWAGGER=true 7 | APP_JWT_SECRET=IamNotASecret 8 | APP_JWT_EXPIRES=604800 9 | # Database (src/configs/database.ts) 10 | TYPEORM_CONNECTION=mysql 11 | TYPEORM_HOST=localhost 12 | TYPEORM_PORT=3306 13 | TYPEORM_USERNAME=root 14 | TYPEORM_PASSWORD= 15 | TYPEORM_DATABASE=nestjs_demo 16 | TYPEORM_ENTITIES=dist/entities/*.js 17 | TYPEORM_MIGRATIONS=dist/migrations/*.js 18 | TYPEORM_MIGRATIONS_RUN=false 19 | TYPEORM_LOGGING=true 20 | TYPEORM_SYNCHRONIZE=true 21 | TYPEORM_DROP_SCHEMA=false 22 | # TypeORM CLI 23 | TYPEORM_ENTITIES_DIR=src/entities 24 | TYPEORM_MIGRATIONS_DIR=src/migrations 25 | # RabbitMQ (src/configs/rmq.ts) 26 | RMQ_ENABLE=true 27 | RMQ_URL=amqp://localhost:5672 28 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | eslint.config.mjs linguist-vendored 2 | Dockerfile linguist-vendored 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | dist 3 | node_modules 4 | # Logs 5 | logs 6 | *.log 7 | npm-debug.log* 8 | yarn-debug.log* 9 | yarn-error.log* 10 | lerna-debug.log* 11 | # OS 12 | .DS_Store 13 | # IDEs and editors 14 | /.idea 15 | .project 16 | .classpath 17 | .c9/ 18 | *.launch 19 | .settings/ 20 | *.sublime-workspace 21 | # IDE - VSCode 22 | .vscode/* 23 | !.vscode/settings.json 24 | !.vscode/tasks.json 25 | !.vscode/launch.json 26 | !.vscode/extensions.json 27 | # ENV 28 | .env 29 | # Docker 30 | volumes 31 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | yarn commitlint --edit $1 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | yarn lint 2 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "wmaurer.change-case", 4 | "mikestead.dotenv", 5 | "dbaeumer.vscode-eslint", 6 | "christian-kohler.path-intellisense", 7 | "esbenp.prettier-vscode", 8 | "roscop.activefileinstatusbar", 9 | "mizyind.darkpp-regular", 10 | "ms-azuretools.vscode-docker", 11 | "eamodio.gitlens", 12 | "dozerg.tsimportsorter", 13 | "wayou.vscode-todo-highlight", 14 | "dakara.transformer", 15 | "vscode-icons-team.vscode-icons" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "editor.insertSpaces": true, 4 | "editor.tabSize": 2, 5 | "editor.trimAutoWhitespace": true, 6 | "files.eol": "\n", 7 | "files.exclude": { 8 | ".git": true, 9 | ".husky": true, 10 | ".vscode": true, 11 | ".DS_Store": true, 12 | "node_modules": true 13 | }, 14 | "files.insertFinalNewline": true, 15 | "files.trimTrailingWhitespace": true, 16 | "vsicons.presets.nestjs": true 17 | } 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) miZyind 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 | # NestJS Demo 2 | 3 | [![Docker](https://img.shields.io/badge/docker-2496ed?style=for-the-badge&logo=docker&logoColor=fff)](https://www.docker.com) 4 | [![NodeJS](https://img.shields.io/node/v/nestjs-xion?style=for-the-badge&label=&color=339933&logo=node.js&logoColor=fff)](https://nodejs.org) 5 | [![Yarn](https://img.shields.io/badge/-=1.22.22-2c8ebb?style=for-the-badge&label=&logo=yarn&logoColor=fff)](https://classic.yarnpkg.com) 6 | [![MySQL](https://img.shields.io/badge/->=9-4479a1?style=for-the-badge&label=&logo=mysql&logoColor=fff)](https://www.mysql.com) 7 | [![NestJS](https://img.shields.io/github/package-json/dependency-version/mizyind/nestjs-demo/@nestjs/core?style=for-the-badge&label=&color=e0234e&logo=nestjs&logoColor=fff)](https://nestjs.com) 8 | [![TypeScript](https://img.shields.io/github/package-json/dependency-version/mizyind/nestjs-demo/dev/typescript?style=for-the-badge&label=&color=007acc&logo=typescript&logoColor=fff)](https://www.typescriptlang.org) 9 | [![Prettier](https://img.shields.io/npm/dependency-version/eslint-plugin-mizyind/prettier?style=for-the-badge&label=&color=f7b93e&logo=prettier&logoColor=000)](https://prettier.io) 10 | [![ESLint](https://img.shields.io/npm/dependency-version/eslint-plugin-mizyind/eslint?style=for-the-badge&label=&color=4b32c3&logo=eslint&logoColor=fff)](https://eslint.org) 11 | 12 | ## 🌌 Techniques 13 | 14 | - **[NestJS](https://nestjs.com)** - A progressive NodeJS framework for building efficient, reliable and scalable server-side applications. 15 | - **[@nestjs/cli](https://github.com/nestjs/nest-cli)** - CLI tool for Nest. 16 | - **[@nestjs/jwt](https://github.com/nestjs/jwt)** - Utilities module based on the JWT package. 17 | - **[@nestjs/config](https://github.com/nestjs/config)** - Configuration module for Nest. 18 | - **[@nestjs/typeorm](https://github.com/nestjs/typeorm)** - TypeORM module for Nest. 19 | - **[@nestjs/swagger](https://github.com/nestjs/swagger)** - OpenAPI (Swagger) module for Nest. 20 | - **[@nestjs/passport](https://github.com/nestjs/passport)** - .Passport module for Nest. 21 | - **[@nestjs/platform-express](https://www.npmjs.com/package/@nestjs/platform-express)** - Under the hood, Nest makes use of Express. 22 | - **[@nestjs/microservices](https://www.npmjs.com/package/@nestjs/microservices)** - In Nest, a microservice is fundamentally an application. 23 | - **[Swagger](https://swagger.io)** - API Documentation & Design Tools for Teams. 24 | - **[RabbitMQ](https://www.rabbitmq.com)** - Messaging that just works. 25 | - **[amqplib](https://github.com/squaremo/amqp.node)** - AMQP 0-9-1 library and client for NodeJS. 26 | - **[amqp-connection-manager](https://github.com/jwalton/node-amqp-connection-manager)** - Auto-reconnect and round robin support for amqplib. 27 | - **[Passport](http://www.passportjs.org)** - Simple, unobtrusive authentication for NodeJS. 28 | - **[passport-jwt](https://github.com/mikenicholson/passport-jwt)** - Passport authentication using JSON Web Tokens. 29 | - **[RxJS](https://rxjs.dev)** - A reactive programming library for JS. 30 | - **[Bcrypt](https://github.com/kelektiv/node.bcrypt.js)** - A library to help you hash passwords. 31 | - **[TypeORM](https://typeorm.io)** - Amazing ORM for TS and JS. 32 | - **[Reflect Metadata](https://github.com/rbuckton/reflect-metadata)** - Prototype for a Metadata Reflection API for ECMAScript. 33 | - **[Class Validator](https://github.com/typestack/class-validator)** - Decorator-based property validation for classes. 34 | - **[Class Transformer](https://github.com/typestack/class-transformer)** - Decorator-based transform-, serializ-, and deserialization between objects and classes. 35 | - **[TypeScript](https://www.typescriptlang.org)** - Typed JS at Any Scale. 36 | - **[Prettier](https://prettier.io)** - Opinionated Code Formatter. 37 | - **[ESLint](https://eslint.org)** - Pluggable JS linter. 38 | - **[typescript-eslint](https://typescript-eslint.io)** - Monorepo for all the tooling which enables ESLint to support TypeScript. 39 | - **[eslint-config-prettier](https://github.com/prettier/eslint-config-prettier)** - Turns off all rules that are unnecessary or might conflict with Prettier. 40 | - **[eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier)** - ESLint plugin for Prettier formatting. 41 | - **[eslint-plugin-import-x](https://github.com/antfu/eslint-plugin-import-x)** - ESLint plugin with rules that help validate proper imports. 42 | - **[Husky](https://github.com/typicode/husky)** - Git hooks made easy. 43 | - **[commitlint](https://github.com/conventional-changelog/commitlint)** - Lint commit messages. 44 | - **[@commitlint/cli](https://www.npmjs.com/package/@commitlint/cli)** - Primary way to interact with commitlint. 45 | - **[@commitlint/config-conventional](https://www.npmjs.com/package/@commitlint/config-conventional)** - Shareable commitlint config enforcing conventional commits. 46 | 47 | ## 🔮 Usage 48 | 49 | Run development environment: 50 | 51 | ```bash 52 | # Install packages 53 | $ yarn 54 | # Up docker compose environment 55 | $ docker-compose up 56 | # Setup dotenv variables 57 | $ cp .env.example .env 58 | # Launch app 59 | $ yarn dev 60 | ``` 61 | 62 | Build & Run production environment: 63 | 64 | ```bash 65 | # Install packages 66 | $ yarn 67 | # Build project 68 | $ yarn build 69 | # Launch app through Yarn 70 | $ yarn start 71 | # Launch app through Node 72 | $ node dist/main.js 73 | ``` 74 | 75 | ## 🖋 Author 76 | 77 | miZyind 78 | 79 | ## 📇 License 80 | 81 | Licensed under the [MIT](LICENSE) License. 82 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | db: 3 | container_name: nestjs-demo-db 4 | image: mysql:9 5 | environment: 6 | MYSQL_DATABASE: 'nestjs_demo' 7 | MYSQL_ALLOW_EMPTY_PASSWORD: 'yes' 8 | ports: 9 | - 3306:3306 10 | volumes: 11 | - ./volumes/mysql:/var/lib/mysql 12 | command: 13 | - 'mysqld' 14 | - '--character-set-server=utf8mb4' 15 | - '--collation-server=utf8mb4_unicode_ci' 16 | mq: 17 | container_name: nestjs-demo-mq 18 | image: rabbitmq:3-management-alpine 19 | ports: 20 | - '5672:5672' 21 | - '15672:15672' 22 | volumes: 23 | - ./volumes/rabbitmq:/var/lib/rabbitmq 24 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | export { typescript as default } from 'eslint-plugin-mizyind'; 2 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src", 4 | "compilerOptions": { 5 | "plugins": [ 6 | { 7 | "name": "@nestjs/swagger", 8 | "options": { 9 | "dtoFileNameSuffix": [ 10 | ".dto.ts", 11 | ".response.ts" 12 | ] 13 | } 14 | } 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-demo", 3 | "version": "1.0.0", 4 | "description": "A demo project for NestJS", 5 | "repository": "git@github.com:miZyind/nestjs-demo.git", 6 | "author": "miZyind ", 7 | "license": "MIT", 8 | "scripts": { 9 | "prepare": "husky", 10 | "clean": "rm -rf dist", 11 | "dev": "nest start --path tsconfig.json --watch", 12 | "lint": "eslint src --max-warnings 0", 13 | "build": "nest build --path tsconfig.json", 14 | "start": "node dist/main.js", 15 | "typeorm": "typeorm-ts-node-commonjs -d src/db.ts", 16 | "typeorm:generate": "typeorm-ts-node-commonjs migration:generate -d src/db.ts" 17 | }, 18 | "engines": { 19 | "node": ">=22", 20 | "yarn": ">=1.22.19" 21 | }, 22 | "packageManager": "yarn@1.22.22", 23 | "dependencies": { 24 | "@nestjs/common": "^11.1.3", 25 | "@nestjs/core": "^11.1.3", 26 | "@nestjs/jwt": "^11.0.0", 27 | "@nestjs/microservices": "^11.1.3", 28 | "@nestjs/platform-express": "^11.1.3", 29 | "@nestjs/schedule": "^6.0.0", 30 | "@nestjs/typeorm": "^11.0.0", 31 | "amqp-connection-manager": "^4.1.14", 32 | "amqplib": "^0.10.8", 33 | "bcrypt": "^6.0.0", 34 | "mysql2": "^3.14.1", 35 | "nestjs-xion": "^8.0.1", 36 | "passport-jwt": "^4.0.1", 37 | "reflect-metadata": "^0.2.2", 38 | "rxjs": "^7.8.2", 39 | "typeorm": "^0.3.24" 40 | }, 41 | "devDependencies": { 42 | "@commitlint/cli": "^19.8.1", 43 | "@commitlint/config-conventional": "^19.8.1", 44 | "@nestjs/cli": "^11.0.7", 45 | "@types/amqplib": "^0.10.7", 46 | "@types/bcrypt": "^5.0.2", 47 | "@types/node": "^22.15.30", 48 | "@types/passport-jwt": "^4.0.1", 49 | "eslint-plugin-mizyind": "^8.2.1", 50 | "husky": "^9.1.7", 51 | "ts-node": "^10.9.2", 52 | "typescript": "^5.8.3" 53 | }, 54 | "prettier": { 55 | "singleQuote": true, 56 | "trailingComma": "all" 57 | }, 58 | "commitlint": { 59 | "extends": [ 60 | "@commitlint/config-conventional" 61 | ] 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/app/app.base.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Inject } from '@nestjs/common'; 2 | import { ApiExcludeEndpoint } from '@nestjs/swagger'; 3 | 4 | import Config, { AppConfig } from '#configs'; 5 | 6 | @Controller() 7 | export class AppBaseController { 8 | constructor( 9 | @Inject(`CONFIGURATION(${Config.App})`) 10 | private readonly appConfig: AppConfig, 11 | ) {} 12 | 13 | @Get() 14 | @ApiExcludeEndpoint() 15 | getAppConfig(): Pick { 16 | const { name, host, port } = this.appConfig; 17 | 18 | return { name, host, port }; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/app/app.constant.ts: -------------------------------------------------------------------------------- 1 | export const BCRYPT_SALT_ROUNDS = 10; 2 | 3 | export enum LocaleCode { 4 | English = 'en-US', 5 | Vietnamese = 'vi-VN', 6 | SimplifiedChinese = 'zh-CN', 7 | TraditionalChinese = 'zh-TW', 8 | } 9 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { ConfigModule, ConfigService } from 'nestjs-xion/config'; 2 | 3 | import { Module } from '@nestjs/common'; 4 | import { TypeOrmModule } from '@nestjs/typeorm'; 5 | 6 | import { AppBaseController } from '#app/app.base.controller'; 7 | import Config from '#configs'; 8 | import { AuthModule } from '#modules/auth/auth.module'; 9 | import { SystemLogModule } from '#modules/system-log/system-log.module'; 10 | import { TermsOfServiceModule } from '#modules/terms-of-service/terms-of-service.module'; 11 | import { TodoModule } from '#modules/todo/todo.module'; 12 | import { UserModule } from '#modules/user/user.module'; 13 | import { AdminModule } from '#platforms/admin/admin.module'; 14 | import { AppModule } from '#platforms/app/app.module'; 15 | import { WebModule } from '#platforms/web/web.module'; 16 | 17 | import type { TypeOrmModuleOptions } from '@nestjs/typeorm'; 18 | 19 | @Module({ 20 | imports: [ 21 | ConfigModule.forRoot(), 22 | TypeOrmModule.forRootAsync({ 23 | useFactory: (config: ConfigService) => 24 | config.get(Config.Database) as TypeOrmModuleOptions, 25 | inject: [ConfigService], 26 | }), 27 | AuthModule, 28 | SystemLogModule, 29 | TermsOfServiceModule, 30 | TodoModule, 31 | UserModule, 32 | // Platform Modules 33 | AdminModule, 34 | AppModule, 35 | WebModule, 36 | ], 37 | controllers: [AppBaseController], 38 | }) 39 | export class BaseAppModule {} 40 | -------------------------------------------------------------------------------- /src/configs/app.ts: -------------------------------------------------------------------------------- 1 | export = { 2 | name: String(process.env.APP_NAME), 3 | host: String(process.env.APP_HOST), 4 | port: Number(process.env.APP_PORT), 5 | secret: String(process.env.APP_SECRET), 6 | swagger: process.env.APP_SWAGGER === 'true', 7 | jwt: { 8 | secret: String(process.env.APP_JWT_SECRET), 9 | signOptions: { 10 | expiresIn: Number(process.env.APP_JWT_EXPIRES), 11 | }, 12 | }, 13 | }; 14 | -------------------------------------------------------------------------------- /src/configs/database.ts: -------------------------------------------------------------------------------- 1 | export = { 2 | type: String(process.env.TYPEORM_CONNECTION), 3 | host: String(process.env.TYPEORM_HOST), 4 | port: Number(process.env.TYPEORM_PORT), 5 | username: String(process.env.TYPEORM_USERNAME), 6 | password: String(process.env.TYPEORM_PASSWORD), 7 | database: String(process.env.TYPEORM_DATABASE), 8 | logging: process.env.TYPEORM_LOGGING === 'true', 9 | entities: process.env.TYPEORM_ENTITIES?.split(','), 10 | migrations: process.env.TYPEORM_MIGRATIONS?.split(','), 11 | migrationsRun: process.env.TYPEORM_MIGRATIONS_RUN === 'true', 12 | synchronize: process.env.TYPEORM_SYNCHRONIZE === 'true', 13 | dropSchema: process.env.TYPEORM_DROP_SCHEMA === 'true', 14 | // Extra 15 | bigNumberStrings: false, 16 | timezone: 'Z', 17 | // CLI 18 | entitiesDir: String(process.env.TYPEORM_ENTITIES_DIR), 19 | migrationsDir: String(process.env.TYPEORM_MIGRATIONS_DIR), 20 | }; 21 | -------------------------------------------------------------------------------- /src/configs/index.ts: -------------------------------------------------------------------------------- 1 | export type AppConfig = typeof import('./app'); 2 | export type DatabaseConfig = typeof import('./database'); 3 | export type RMQConfig = typeof import('./rmq'); 4 | 5 | enum Config { 6 | App = 'APP', 7 | Database = 'DATABASE', 8 | RMQ = 'RMQ', 9 | } 10 | 11 | export default Config; 12 | -------------------------------------------------------------------------------- /src/configs/rmq.ts: -------------------------------------------------------------------------------- 1 | export = { 2 | enable: process.env.RMQ_ENABLE === 'true', 3 | options: { 4 | urls: [String(process.env.RMQ_URL)], 5 | queue: 'nestjs_demo_queue', 6 | prefetchCount: 1, 7 | noAck: false, 8 | queueOptions: { durable: false }, 9 | socketOptions: { noDelay: true }, 10 | }, 11 | }; 12 | -------------------------------------------------------------------------------- /src/configs/swagger.ts: -------------------------------------------------------------------------------- 1 | export = { 2 | enable: process.env.SWAGGER_ENABLE === 'true', 3 | }; 4 | -------------------------------------------------------------------------------- /src/db.ts: -------------------------------------------------------------------------------- 1 | import { DataSource } from 'typeorm'; 2 | 3 | import options from '#configs/database'; 4 | 5 | import type { DataSourceOptions } from 'typeorm'; 6 | 7 | export default new DataSource(options as DataSourceOptions); 8 | -------------------------------------------------------------------------------- /src/entities/base.entity.ts: -------------------------------------------------------------------------------- 1 | import { CreateDateColumn, UpdateDateColumn } from 'typeorm'; 2 | 3 | export abstract class Base { 4 | @CreateDateColumn() 5 | readonly createdAt!: Date; 6 | 7 | @UpdateDateColumn() 8 | readonly updatedAt!: Date; 9 | } 10 | -------------------------------------------------------------------------------- /src/entities/system-log.entity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Column, 3 | CreateDateColumn, 4 | Entity, 5 | PrimaryGeneratedColumn, 6 | } from 'typeorm'; 7 | 8 | export enum SystemLogType { 9 | UserStatistic = 'USER_STATISTIC', 10 | } 11 | 12 | @Entity() 13 | export class SystemLog { 14 | @CreateDateColumn() 15 | readonly loggedAt!: Date; 16 | 17 | @PrimaryGeneratedColumn() 18 | readonly id!: number; 19 | 20 | @Column() 21 | readonly type!: SystemLogType; 22 | 23 | @Column('text') 24 | readonly note!: string; 25 | 26 | @Column({ type: 'json' }) 27 | readonly data!: Record; 28 | } 29 | -------------------------------------------------------------------------------- /src/entities/terms-of-service-translation.entity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Column, 3 | Entity, 4 | JoinColumn, 5 | ManyToOne, 6 | PrimaryGeneratedColumn, 7 | } from 'typeorm'; 8 | 9 | import { LocaleCode } from '#app/app.constant'; 10 | import { TermsOfService } from '#entities/terms-of-service.entity'; 11 | 12 | @Entity() 13 | export class TermsOfServiceTranslation { 14 | @PrimaryGeneratedColumn() 15 | readonly id!: number; 16 | 17 | @Column() 18 | readonly code!: LocaleCode; 19 | 20 | @Column() 21 | readonly content!: string; 22 | 23 | @JoinColumn({ name: 'termsOfServiceVersion' }) 24 | @ManyToOne(() => TermsOfService, { nullable: false, onDelete: 'CASCADE' }) 25 | readonly termsOfService!: TermsOfService; 26 | } 27 | 28 | export type TermsOfServiceTranslations = Pick< 29 | TermsOfServiceTranslation, 30 | 'code' | 'content' 31 | >[]; 32 | -------------------------------------------------------------------------------- /src/entities/terms-of-service.entity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Column, 3 | Entity, 4 | JoinColumn, 5 | ManyToOne, 6 | OneToMany, 7 | PrimaryGeneratedColumn, 8 | } from 'typeorm'; 9 | 10 | import { Base } from '#entities/base.entity'; 11 | import { TermsOfServiceTranslation } from '#entities/terms-of-service-translation.entity'; 12 | import { User } from '#entities/user.entity'; 13 | 14 | @Entity() 15 | export class TermsOfService extends Base { 16 | @PrimaryGeneratedColumn() 17 | readonly version!: number; 18 | 19 | @Column('text') 20 | readonly note!: string; 21 | 22 | @OneToMany( 23 | () => TermsOfServiceTranslation, 24 | ({ termsOfService }) => termsOfService, 25 | { eager: true, cascade: true }, 26 | ) 27 | readonly translations!: TermsOfServiceTranslation[]; 28 | 29 | @JoinColumn({ name: 'creatorUUID' }) 30 | @ManyToOne(() => User, { nullable: false }) 31 | readonly creator!: User; 32 | 33 | @JoinColumn({ name: 'modifierUUID' }) 34 | @ManyToOne(() => User) 35 | readonly modifier!: User | null; 36 | } 37 | -------------------------------------------------------------------------------- /src/entities/todo.entity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Column, 3 | Entity, 4 | JoinColumn, 5 | ManyToOne, 6 | PrimaryGeneratedColumn, 7 | } from 'typeorm'; 8 | 9 | import { User } from '#entities/user.entity'; 10 | import { Base } from '#entities/base.entity'; 11 | 12 | export enum TodoStatus { 13 | Doing = 'DOING', 14 | Done = 'DONE', 15 | } 16 | 17 | @Entity() 18 | export class Todo extends Base { 19 | @PrimaryGeneratedColumn('uuid') 20 | readonly uuid!: string; 21 | 22 | @Column({ default: TodoStatus.Doing }) 23 | readonly status!: TodoStatus; 24 | 25 | @Column('text') 26 | readonly message!: string; 27 | 28 | @JoinColumn({ name: 'userUUID' }) 29 | @ManyToOne(() => User) 30 | readonly user!: User; 31 | } 32 | -------------------------------------------------------------------------------- /src/entities/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { compare, hash } from 'bcrypt'; 2 | import { 3 | BeforeInsert, 4 | Column, 5 | Entity, 6 | OneToMany, 7 | PrimaryGeneratedColumn, 8 | } from 'typeorm'; 9 | 10 | import { BCRYPT_SALT_ROUNDS } from '#app/app.constant'; 11 | import { Base } from '#entities/base.entity'; 12 | import { Todo } from '#entities/todo.entity'; 13 | 14 | export enum Role { 15 | User = 'User', 16 | Admin = 'Admin', 17 | } 18 | 19 | export enum UserStatus { 20 | ApprovePending = 'APPROVE_PENDING', 21 | Approved = 'APPROVED', 22 | Banned = 'BANNED', 23 | } 24 | 25 | @Entity() 26 | export class User extends Base { 27 | @PrimaryGeneratedColumn('uuid') 28 | readonly uuid!: string; 29 | 30 | @Column() 31 | readonly status!: UserStatus; 32 | 33 | @Column() 34 | readonly role!: Role; 35 | 36 | @Column({ unique: true }) 37 | readonly email!: string; 38 | 39 | @Column() 40 | password!: string; 41 | 42 | @OneToMany(() => Todo, ({ user }) => user) 43 | readonly todos!: Todo[]; 44 | 45 | @BeforeInsert() 46 | async hashPassword(): Promise { 47 | this.password = await hash(this.password, BCRYPT_SALT_ROUNDS); 48 | } 49 | 50 | async comparePassword(attempt: string): Promise { 51 | return compare(attempt, this.password); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { ConfigService } from 'nestjs-xion/config'; 2 | import { ErrorFilter } from 'nestjs-xion/error'; 3 | import { StandardResponseInterceptor } from 'nestjs-xion/interceptor'; 4 | 5 | import { ValidationPipe } from '@nestjs/common'; 6 | import { NestFactory } from '@nestjs/core'; 7 | 8 | import { BaseAppModule } from '#app/app.module'; 9 | import Config from '#configs'; 10 | 11 | import type { AppConfig, RMQConfig } from '#configs'; 12 | 13 | async function bootstrap(): Promise { 14 | const app = await NestFactory.create(BaseAppModule); 15 | const config = app.get(ConfigService); 16 | const appConf = config.get(Config.App) as AppConfig; 17 | const rmqConf = config.get(Config.RMQ) as RMQConfig; 18 | 19 | app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true })); 20 | app.useGlobalFilters(new ErrorFilter()); 21 | app.useGlobalInterceptors(new StandardResponseInterceptor()); 22 | 23 | if (rmqConf.enable) { 24 | (await import('./utils/rmq')).setup(app, rmqConf.options); 25 | } 26 | if (appConf.swagger) { 27 | (await import('./utils/swagger')).setup(app, appConf); 28 | } 29 | 30 | await app.startAllMicroservices(); 31 | await app.listen(appConf.port, appConf.host); 32 | } 33 | 34 | bootstrap().catch((error) => { 35 | throw error; 36 | }); 37 | -------------------------------------------------------------------------------- /src/modules/auth/auth.constant.ts: -------------------------------------------------------------------------------- 1 | export enum AuthStrategy { 2 | JWT = 'JWT', 3 | Secret = 'SECRET', 4 | } 5 | export enum AuthError { 6 | InvalidLoginCredentials = 'Invalid login credentials', 7 | InvalidToken = 'Invalid token', 8 | InvalidSecret = 'Invalid secret', 9 | } 10 | -------------------------------------------------------------------------------- /src/modules/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { ConfigService } from 'nestjs-xion/config'; 2 | 3 | import { Module } from '@nestjs/common'; 4 | import { JwtModule } from '@nestjs/jwt'; 5 | import { PassportModule } from '@nestjs/passport'; 6 | 7 | import Config from '#configs'; 8 | import { AuthPublicController } from '#modules/auth/auth.public.controller'; 9 | import { AuthService } from '#modules/auth/auth.service'; 10 | import { JWTStrategy } from '#modules/auth/strategies/jwt.strategy'; 11 | import { SecretStrategy } from '#modules/auth/strategies/secret.strategy'; 12 | import { UserModule } from '#modules/user/user.module'; 13 | 14 | import type { AppConfig } from '#configs'; 15 | 16 | @Module({ 17 | imports: [ 18 | UserModule, 19 | JwtModule.registerAsync({ 20 | useFactory: (config: ConfigService) => 21 | (config.get(Config.App) as AppConfig).jwt, 22 | inject: [ConfigService], 23 | }), 24 | PassportModule, 25 | ], 26 | providers: [AuthService, JWTStrategy, SecretStrategy], 27 | controllers: [AuthPublicController], 28 | }) 29 | export class AuthModule {} 30 | -------------------------------------------------------------------------------- /src/modules/auth/auth.public.controller.ts: -------------------------------------------------------------------------------- 1 | import { ApiStandardResponse } from 'nestjs-xion/decorator'; 2 | 3 | import { Body, Controller, Patch } from '@nestjs/common'; 4 | import { ApiOperation, ApiTags } from '@nestjs/swagger'; 5 | 6 | import { AuthService } from '#modules/auth/auth.service'; 7 | import { LogInDTO } from '#modules/auth/dtos/log-in.dto'; 8 | import { LogInResponse } from '#modules/auth/responses/log-in.response'; 9 | 10 | @ApiTags('Auth') 11 | @Controller('public/auth') 12 | export class AuthPublicController { 13 | constructor(private readonly service: AuthService) {} 14 | 15 | @Patch('log-in') 16 | @ApiOperation({ summary: 'Log in to the system' }) 17 | @ApiStandardResponse({ type: LogInResponse }) 18 | async login(@Body() dto: LogInDTO): Promise { 19 | return this.service.validateAttemptAndSignToken(dto); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/modules/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { hasValue } from 'nestjs-xion/guarder'; 2 | 3 | import { BadRequestException, Injectable, Logger } from '@nestjs/common'; 4 | import { JwtService } from '@nestjs/jwt'; 5 | 6 | import { AuthError } from '#modules/auth/auth.constant'; 7 | import { UserService } from '#modules/user/user.service'; 8 | 9 | import type { Role } from '#entities/user.entity'; 10 | import type { LogInDTO } from '#modules/auth/dtos/log-in.dto'; 11 | import type { LogInResponse } from '#modules/auth/responses/log-in.response'; 12 | import type { JWTPayload } from '#modules/auth/strategies/jwt.strategy'; 13 | 14 | @Injectable() 15 | export class AuthService { 16 | private readonly logger = new Logger(AuthService.name); 17 | 18 | constructor( 19 | private readonly userService: UserService, 20 | private readonly jwtService: JwtService, 21 | ) {} 22 | 23 | async validateAttemptAndSignToken({ 24 | email, 25 | attempt, 26 | }: LogInDTO): Promise { 27 | const entity = await this.userService.findOne({ 28 | select: ['uuid', 'status', 'password'], 29 | where: { email }, 30 | }); 31 | 32 | if (hasValue(entity) && (await entity.comparePassword(attempt))) { 33 | this.userService.validateStatus(entity.status); 34 | 35 | const token = await this.jwtService.signAsync({ 36 | uuid: entity.uuid, 37 | email, 38 | } as JWTPayload); 39 | 40 | this.logger.debug(`User [${email}] logged in`); 41 | 42 | return { token }; 43 | } 44 | 45 | throw new BadRequestException(AuthError.InvalidLoginCredentials); 46 | } 47 | 48 | async validateUserAndGetRole(uuid: string): Promise { 49 | const entity = await this.userService.findOne({ 50 | select: ['status', 'role'], 51 | where: { uuid }, 52 | }); 53 | 54 | if (hasValue(entity)) { 55 | this.userService.validateStatus(entity.status); 56 | 57 | return entity.role; 58 | } 59 | 60 | throw new BadRequestException(AuthError.InvalidToken); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/modules/auth/dtos/log-in.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; 2 | 3 | import { ApiProperty } from '@nestjs/swagger'; 4 | 5 | export class LogInDTO { 6 | @IsEmail() 7 | @ApiProperty({ format: 'email', example: 'todo@example.com' }) 8 | readonly email!: string; 9 | 10 | @IsNotEmpty() 11 | @IsString() 12 | @ApiProperty({ format: 'password', example: '123456' }) 13 | readonly attempt!: string; 14 | } 15 | -------------------------------------------------------------------------------- /src/modules/auth/guards/jwt-admin.guard.ts: -------------------------------------------------------------------------------- 1 | import { UseGuards, applyDecorators } from '@nestjs/common'; 2 | import { ApiSecurity } from '@nestjs/swagger'; 3 | 4 | import { Role } from '#entities/user.entity'; 5 | import { AuthStrategy } from '#modules/auth/auth.constant'; 6 | import { JWTRolesGuard } from '#modules/auth/strategies/jwt.strategy'; 7 | 8 | export function JWTAdminGuard(): ClassDecorator & MethodDecorator { 9 | return applyDecorators( 10 | UseGuards(JWTRolesGuard(Role.Admin)), 11 | ApiSecurity(AuthStrategy.JWT), 12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /src/modules/auth/guards/jwt-user.guard.ts: -------------------------------------------------------------------------------- 1 | import { UseGuards, applyDecorators } from '@nestjs/common'; 2 | import { ApiSecurity } from '@nestjs/swagger'; 3 | 4 | import { Role } from '#entities/user.entity'; 5 | import { AuthStrategy } from '#modules/auth/auth.constant'; 6 | import { JWTRolesGuard } from '#modules/auth/strategies/jwt.strategy'; 7 | 8 | export function JWTUserGuard(): ClassDecorator & MethodDecorator { 9 | return applyDecorators( 10 | UseGuards(JWTRolesGuard(Role.Admin, Role.User)), 11 | ApiSecurity(AuthStrategy.JWT), 12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /src/modules/auth/guards/secret.guard.ts: -------------------------------------------------------------------------------- 1 | import { UseGuards, applyDecorators } from '@nestjs/common'; 2 | import { AuthGuard } from '@nestjs/passport'; 3 | import { ApiSecurity } from '@nestjs/swagger'; 4 | 5 | import { AuthStrategy } from '#modules/auth/auth.constant'; 6 | 7 | export function SecretGuard(): ClassDecorator & MethodDecorator { 8 | return applyDecorators( 9 | UseGuards(AuthGuard(AuthStrategy.Secret)), 10 | ApiSecurity(AuthStrategy.Secret), 11 | ); 12 | } 13 | -------------------------------------------------------------------------------- /src/modules/auth/responses/log-in.response.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class LogInResponse { 4 | @ApiProperty({ example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' }) 5 | readonly token!: string; 6 | } 7 | -------------------------------------------------------------------------------- /src/modules/auth/strategies/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { ExtractJwt, Strategy } from 'passport-jwt'; 2 | 3 | import { Inject, Injectable } from '@nestjs/common'; 4 | import { AuthGuard, PassportStrategy } from '@nestjs/passport'; 5 | 6 | import Config, { AppConfig } from '#configs'; 7 | import { AuthStrategy } from '#modules/auth/auth.constant'; 8 | import { AuthService } from '#modules/auth/auth.service'; 9 | 10 | import type { ExecutionContext } from '@nestjs/common'; 11 | import type { IAuthGuard, Type } from '@nestjs/passport'; 12 | import type { Role } from '#entities/user.entity'; 13 | 14 | export interface JWTPayload { 15 | uuid: string; 16 | email: string; 17 | } 18 | 19 | export interface JWTUserPayload extends JWTPayload { 20 | role: Role; 21 | } 22 | 23 | @Injectable() 24 | export class JWTStrategy extends PassportStrategy(Strategy, AuthStrategy.JWT) { 25 | constructor( 26 | private readonly service: AuthService, 27 | @Inject(`CONFIGURATION(${Config.App})`) { jwt }: AppConfig, 28 | ) { 29 | super({ 30 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 31 | secretOrKey: jwt.secret, 32 | }); 33 | } 34 | 35 | async validate(payload: JWTPayload): Promise { 36 | const role = await this.service.validateUserAndGetRole(payload.uuid); 37 | 38 | return { ...payload, role }; 39 | } 40 | } 41 | 42 | export function JWTRolesGuard(...roles: Role[]): Type { 43 | @Injectable() 44 | class RolesGuardMixin extends AuthGuard(AuthStrategy.JWT) { 45 | async canActivate(context: ExecutionContext): Promise { 46 | const isVerified = (await super.canActivate(context)) as boolean; 47 | 48 | if (isVerified) { 49 | const request = context 50 | .switchToHttp() 51 | .getRequest<{ user: JWTUserPayload }>(); 52 | 53 | return roles.includes(request.user.role); 54 | } 55 | 56 | return false; 57 | } 58 | } 59 | 60 | return RolesGuardMixin; 61 | } 62 | -------------------------------------------------------------------------------- /src/modules/auth/strategies/secret.strategy.ts: -------------------------------------------------------------------------------- 1 | import { Strategy as BaseStrategy } from 'passport-strategy'; 2 | 3 | import { BadRequestException, Inject, Injectable } from '@nestjs/common'; 4 | import { PassportStrategy } from '@nestjs/passport'; 5 | 6 | import Config, { AppConfig } from '#configs'; 7 | import { AuthError, AuthStrategy } from '#modules/auth/auth.constant'; 8 | 9 | import type { Request } from 'express'; 10 | 11 | class Strategy extends BaseStrategy { 12 | constructor( 13 | private readonly verify: ( 14 | req: Request, 15 | verified: (error: Error | null) => void, 16 | ) => void, 17 | ) { 18 | super(); 19 | } 20 | 21 | authenticate(req: Request): void { 22 | try { 23 | this.verify(req, (error) => { 24 | if (error) { 25 | this.error(error); 26 | } else { 27 | this.success(true); 28 | } 29 | }); 30 | } catch (error) { 31 | this.error(error as Error); 32 | } 33 | } 34 | } 35 | 36 | @Injectable() 37 | export class SecretStrategy extends PassportStrategy( 38 | Strategy, 39 | AuthStrategy.Secret, 40 | ) { 41 | constructor( 42 | @Inject(`CONFIGURATION(${Config.App})`) private readonly config: AppConfig, 43 | ) { 44 | super(); 45 | } 46 | 47 | validate(req: Request): void { 48 | if (req.header(AuthStrategy.Secret) !== this.config.secret) { 49 | throw new BadRequestException(AuthError.InvalidSecret); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/modules/system-log/system-log.interface.ts: -------------------------------------------------------------------------------- 1 | import type { SystemLogType } from '#entities/system-log.entity'; 2 | 3 | export interface CreateSystemLogDTO { 4 | type: SystemLogType; 5 | note: string; 6 | data: Record; 7 | } 8 | -------------------------------------------------------------------------------- /src/modules/system-log/system-log.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | 4 | import { SystemLog } from '#entities/system-log.entity'; 5 | import { SystemLogService } from '#modules/system-log/system-log.service'; 6 | 7 | @Module({ 8 | imports: [TypeOrmModule.forFeature([SystemLog])], 9 | providers: [SystemLogService], 10 | exports: [SystemLogService], 11 | }) 12 | export class SystemLogModule {} 13 | -------------------------------------------------------------------------------- /src/modules/system-log/system-log.service.ts: -------------------------------------------------------------------------------- 1 | import { CRUDService } from 'nestjs-xion/crud'; 2 | import { Repository } from 'typeorm'; 3 | 4 | import { Injectable, Logger } from '@nestjs/common'; 5 | import { InjectRepository } from '@nestjs/typeorm'; 6 | 7 | import { SystemLog } from '#entities/system-log.entity'; 8 | 9 | import type { CreateSystemLogDTO } from '#modules/system-log/system-log.interface'; 10 | 11 | @Injectable() 12 | export class SystemLogService extends CRUDService { 13 | private readonly logger = new Logger(SystemLogService.name); 14 | 15 | constructor( 16 | @InjectRepository(SystemLog) 17 | protected readonly repo: Repository, 18 | ) { 19 | super(repo); 20 | } 21 | 22 | log(dto: CreateSystemLogDTO): void { 23 | void this.repo 24 | .save(this.repo.create(dto)) 25 | .catch((error) => this.logger.error(error)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/modules/terms-of-service/terms-of-service.interface.ts: -------------------------------------------------------------------------------- 1 | import type { TermsOfServiceTranslations } from '#entities/terms-of-service-translation.entity'; 2 | 3 | export interface GetLatestOneResponse { 4 | updatedAt: Date; 5 | version: number; 6 | content: string; 7 | } 8 | 9 | export interface UpsertTermsOfServiceDTO { 10 | version?: number; 11 | note: string; 12 | translations: TermsOfServiceTranslations; 13 | } 14 | 15 | export interface UpsertTermsOfServiceResponse { 16 | version: number; 17 | } 18 | -------------------------------------------------------------------------------- /src/modules/terms-of-service/terms-of-service.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | 4 | import { TermsOfServiceTranslation } from '#entities/terms-of-service-translation.entity'; 5 | import { TermsOfService } from '#entities/terms-of-service.entity'; 6 | import { TermsOfServiceService } from '#modules/terms-of-service/terms-of-service.service'; 7 | 8 | @Module({ 9 | imports: [ 10 | TypeOrmModule.forFeature([TermsOfService, TermsOfServiceTranslation]), 11 | ], 12 | providers: [TermsOfServiceService], 13 | exports: [TermsOfServiceService], 14 | }) 15 | export class TermsOfServiceModule {} 16 | -------------------------------------------------------------------------------- /src/modules/terms-of-service/terms-of-service.service.ts: -------------------------------------------------------------------------------- 1 | import { CRUDService } from 'nestjs-xion/crud'; 2 | import { hasValue } from 'nestjs-xion/guarder'; 3 | import { Repository } from 'typeorm'; 4 | 5 | import { Injectable } from '@nestjs/common'; 6 | import { InjectRepository } from '@nestjs/typeorm'; 7 | 8 | import { LocaleCode } from '#app/app.constant'; 9 | import { TermsOfServiceTranslation } from '#entities/terms-of-service-translation.entity'; 10 | import { TermsOfService } from '#entities/terms-of-service.entity'; 11 | 12 | import type { 13 | GetLatestOneResponse, 14 | UpsertTermsOfServiceDTO, 15 | UpsertTermsOfServiceResponse, 16 | } from '#modules/terms-of-service/terms-of-service.interface'; 17 | 18 | @Injectable() 19 | export class TermsOfServiceService extends CRUDService { 20 | constructor( 21 | @InjectRepository(TermsOfService) 22 | protected repo: Repository, 23 | @InjectRepository(TermsOfServiceTranslation) 24 | private readonly txnRepo: Repository, 25 | ) { 26 | super(repo); 27 | } 28 | 29 | async getLatestOne(code: LocaleCode): Promise { 30 | const entity = await this.repo 31 | .createQueryBuilder('tos') 32 | .select(['tos.updatedAt', 'tos.version', 'txn.content']) 33 | .innerJoin('tos.translations', 'txn') 34 | .where('txn.code = :code', { code }) 35 | .orderBy('tos.version', 'DESC') 36 | .getOne(); 37 | 38 | if (entity) { 39 | const { updatedAt, version, translations } = entity; 40 | const [{ content }] = translations; 41 | 42 | return { updatedAt, version, content }; 43 | } 44 | 45 | return null; 46 | } 47 | 48 | async upsert( 49 | operatorUUID: string, 50 | { version, note, translations }: UpsertTermsOfServiceDTO, 51 | ): Promise { 52 | const hasExisting = hasValue(version); 53 | 54 | if (hasExisting) { 55 | const entity = await this.repo.findOne({ 56 | select: { version: true }, 57 | where: { version }, 58 | relations: { translations: true }, 59 | }); 60 | 61 | if (entity) { 62 | await this.txnRepo.remove(entity.translations); 63 | } 64 | } 65 | 66 | const entity = await this.repo.save({ 67 | version, 68 | note, 69 | translations: translations 70 | .filter(({ code }) => Object.values(LocaleCode).includes(code)) 71 | .map(({ code, content }) => ({ code, content })), 72 | [hasExisting ? 'modifier' : 'creator']: { uuid: operatorUUID }, 73 | }); 74 | 75 | return { version: entity.version }; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/modules/todo/todo.constant.ts: -------------------------------------------------------------------------------- 1 | export enum TodoError { 2 | TodoNotFound = 'Todo not found', 3 | } 4 | -------------------------------------------------------------------------------- /src/modules/todo/todo.interface.ts: -------------------------------------------------------------------------------- 1 | import type { TodoStatus } from '#entities/todo.entity'; 2 | 3 | export interface CreateTodoDTO { 4 | message: string; 5 | } 6 | 7 | export interface CreateTodoResponse { 8 | uuid: string; 9 | } 10 | 11 | export interface UpdateTodoDTO { 12 | status?: TodoStatus; 13 | message?: string; 14 | } 15 | -------------------------------------------------------------------------------- /src/modules/todo/todo.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | 4 | import { Todo } from '#entities/todo.entity'; 5 | import { TodoService } from '#modules/todo/todo.service'; 6 | 7 | @Module({ 8 | imports: [TypeOrmModule.forFeature([Todo])], 9 | providers: [TodoService], 10 | exports: [TodoService], 11 | }) 12 | export class TodoModule {} 13 | -------------------------------------------------------------------------------- /src/modules/todo/todo.service.ts: -------------------------------------------------------------------------------- 1 | import { CRUDService } from 'nestjs-xion/crud'; 2 | import { Repository } from 'typeorm'; 3 | 4 | import { BadRequestException, Injectable } from '@nestjs/common'; 5 | import { InjectRepository } from '@nestjs/typeorm'; 6 | 7 | import { Todo } from '#entities/todo.entity'; 8 | import { TodoError } from '#modules/todo/todo.constant'; 9 | 10 | import type { CRUDRequest } from 'nestjs-xion/crud'; 11 | import type { StandardList } from 'nestjs-xion/model'; 12 | import type { 13 | CreateTodoDTO, 14 | CreateTodoResponse, 15 | UpdateTodoDTO, 16 | } from '#modules/todo/todo.interface'; 17 | 18 | @Injectable() 19 | export class TodoService extends CRUDService { 20 | constructor( 21 | @InjectRepository(Todo) protected readonly repo: Repository, 22 | ) { 23 | super(repo); 24 | } 25 | 26 | async getDetails(userUUID: string, uuid: string): Promise { 27 | const entity = await this.repo.findOneBy({ 28 | user: { uuid: userUUID }, 29 | uuid, 30 | }); 31 | 32 | if (entity) { 33 | return entity; 34 | } 35 | 36 | throw new BadRequestException(TodoError.TodoNotFound); 37 | } 38 | 39 | async getAll( 40 | userUUID: string, 41 | req: CRUDRequest, 42 | ): Promise> { 43 | req.search.$and = [{ userUUID }]; 44 | 45 | return this.getMany(req, { allow: ['uuid', 'status', 'message'] }); 46 | } 47 | 48 | async create( 49 | userUUID: string, 50 | { message }: CreateTodoDTO, 51 | ): Promise { 52 | const todo = await this.repo.save( 53 | this.repo.create({ message, user: { uuid: userUUID } }), 54 | ); 55 | 56 | return { uuid: todo.uuid }; 57 | } 58 | 59 | async update( 60 | userUUID: string, 61 | uuid: string, 62 | dto: UpdateTodoDTO, 63 | ): Promise { 64 | await this.repo.update({ uuid, user: { uuid: userUUID } }, dto); 65 | } 66 | 67 | async delete(userUUID: string, uuid: string): Promise { 68 | await this.repo.delete({ uuid, user: { uuid: userUUID } }); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/modules/user/user.constant.ts: -------------------------------------------------------------------------------- 1 | export const INITIAL_COUNT_OF_EACH_STATUS = 0; 2 | export enum UserError { 3 | ThisEmailAlreadyExists = 'This email already exists', 4 | InvalidUserStatus = 'Invalid user status', 5 | UserNotFound = 'User not found', 6 | ThisUserHasNotBeenApproved = 'This user has not been approved', 7 | ThisUserHasBeenBanned = 'This user has been banned', 8 | } 9 | -------------------------------------------------------------------------------- /src/modules/user/user.interface.ts: -------------------------------------------------------------------------------- 1 | export interface CreateUserDTO { 2 | email: string; 3 | password: string; 4 | } 5 | -------------------------------------------------------------------------------- /src/modules/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | 4 | import { User } from '#entities/user.entity'; 5 | import { SystemLogModule } from '#modules/system-log/system-log.module'; 6 | import { UserSchedule } from '#modules/user/user.schedule'; 7 | import { UserService } from '#modules/user/user.service'; 8 | 9 | @Module({ 10 | imports: [TypeOrmModule.forFeature([User]), SystemLogModule], 11 | providers: [UserSchedule, UserService], 12 | exports: [UserService], 13 | }) 14 | export class UserModule {} 15 | -------------------------------------------------------------------------------- /src/modules/user/user.schedule.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { Cron } from '@nestjs/schedule'; 3 | 4 | import { SystemLogType } from '#entities/system-log.entity'; 5 | import { SystemLogService } from '#modules/system-log/system-log.service'; 6 | import { UserService } from '#modules/user/user.service'; 7 | import { CronTime } from '#utils/time'; 8 | 9 | @Injectable() 10 | export class UserSchedule { 11 | constructor( 12 | private readonly service: UserService, 13 | private readonly systemLogService: SystemLogService, 14 | ) {} 15 | 16 | @Cron(CronTime.Daily) 17 | async statisticTotalUserCountOfEachStatus(): Promise { 18 | this.systemLogService.log({ 19 | type: SystemLogType.UserStatistic, 20 | note: 'Statistic total user count of each status.', 21 | data: await this.service.getTotalCountOfEachStatus(), 22 | }); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/modules/user/user.service.ts: -------------------------------------------------------------------------------- 1 | import { CRUDService } from 'nestjs-xion/crud'; 2 | import { Repository } from 'typeorm'; 3 | 4 | import { BadRequestException, Injectable, Logger } from '@nestjs/common'; 5 | import { InjectRepository } from '@nestjs/typeorm'; 6 | 7 | import { Role, User, UserStatus } from '#entities/user.entity'; 8 | import { 9 | INITIAL_COUNT_OF_EACH_STATUS, 10 | UserError, 11 | } from '#modules/user/user.constant'; 12 | 13 | import type { CRUDRequest } from 'nestjs-xion/crud'; 14 | import type { StandardList } from 'nestjs-xion/model'; 15 | import type { CreateUserDTO } from '#modules/user/user.interface'; 16 | 17 | @Injectable() 18 | export class UserService extends CRUDService { 19 | private readonly logger = new Logger(UserService.name); 20 | 21 | constructor(@InjectRepository(User) protected repo: Repository) { 22 | super(repo); 23 | } 24 | 25 | async getAll(req: CRUDRequest): Promise> { 26 | const { data, total } = await this.getMany(req, { 27 | allow: ['createdAt', 'updatedAt', 'uuid', 'status', 'role', 'email'], 28 | join: { 29 | todos: { 30 | allow: ['createdAt', 'updatedAt', 'uuid', 'status', 'message'], 31 | }, 32 | }, 33 | sort: [{ field: 'updatedAt', order: 'DESC' }], 34 | }); 35 | 36 | return { data, total }; 37 | } 38 | 39 | async createAdmin({ email, password }: CreateUserDTO): Promise { 40 | await this.create(Role.Admin, email, password); 41 | this.logger.debug(`Admin account [${email}] created`); 42 | } 43 | 44 | async register({ email, password }: CreateUserDTO): Promise { 45 | await this.create(Role.User, email, password); 46 | this.logger.debug(`Account [${email}] registered`); 47 | } 48 | 49 | async approve(uuid: string): Promise { 50 | await this.repo.update(uuid, { status: UserStatus.Approved }); 51 | } 52 | 53 | async reject(uuid: string): Promise { 54 | await this.repo.update(uuid, { status: UserStatus.Banned }); 55 | } 56 | 57 | async getTotalCountOfEachStatus(): Promise> { 58 | const data = await this.repo 59 | .createQueryBuilder() 60 | .select(['status', 'COUNT(*) AS count']) 61 | .groupBy('status') 62 | .getRawMany<{ status: UserStatus; count: number }>(); 63 | 64 | return Object.values(UserStatus).reduce( 65 | (results, status) => { 66 | results[status] = 67 | data.find((item) => item.status === status)?.count ?? 68 | INITIAL_COUNT_OF_EACH_STATUS; 69 | 70 | return results; 71 | }, 72 | { 73 | [UserStatus.ApprovePending]: INITIAL_COUNT_OF_EACH_STATUS, 74 | [UserStatus.Approved]: INITIAL_COUNT_OF_EACH_STATUS, 75 | [UserStatus.Banned]: INITIAL_COUNT_OF_EACH_STATUS, 76 | }, 77 | ); 78 | } 79 | 80 | validateStatus(status: UserStatus): void { 81 | switch (status) { 82 | case UserStatus.ApprovePending: 83 | throw new BadRequestException(UserError.ThisUserHasNotBeenApproved); 84 | case UserStatus.Approved: 85 | break; 86 | case UserStatus.Banned: 87 | throw new BadRequestException(UserError.ThisUserHasBeenBanned); 88 | default: 89 | throw new BadRequestException(UserError.InvalidUserStatus); 90 | } 91 | } 92 | 93 | private async create( 94 | role: Role, 95 | email: string, 96 | password: string, 97 | ): Promise { 98 | if (await this.repo.countBy({ email })) { 99 | throw new BadRequestException(UserError.ThisEmailAlreadyExists); 100 | } 101 | 102 | await this.repo.save( 103 | this.repo.create({ 104 | status: 105 | role === Role.Admin ? UserStatus.Approved : UserStatus.ApprovePending, 106 | role, 107 | email, 108 | password, 109 | }), 110 | ); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/platforms/admin/admin.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | 3 | import { TermsOfServiceModule } from '#modules/terms-of-service/terms-of-service.module'; 4 | import { UserModule } from '#modules/user/user.module'; 5 | import { AdminProtectedController } from '#platforms/admin/admin.protected.controller'; 6 | 7 | @Module({ 8 | imports: [TermsOfServiceModule, UserModule], 9 | providers: [], 10 | controllers: [AdminProtectedController], 11 | }) 12 | export class AdminModule {} 13 | -------------------------------------------------------------------------------- /src/platforms/admin/admin.protected.controller.ts: -------------------------------------------------------------------------------- 1 | import { CRUDInterceptor, CRUDRequest, ParsedRequest } from 'nestjs-xion/crud'; 2 | import { 3 | ApiCrudQueries, 4 | ApiStandardListResponse, 5 | ApiStandardResponse, 6 | User, 7 | } from 'nestjs-xion/decorator'; 8 | import { UUIDParamDTO } from 'nestjs-xion/dto'; 9 | 10 | import { 11 | Body, 12 | Controller, 13 | Delete, 14 | Get, 15 | HttpStatus, 16 | Param, 17 | Patch, 18 | Post, 19 | Put, 20 | UseInterceptors, 21 | } from '@nestjs/common'; 22 | import { ApiOperation, ApiTags } from '@nestjs/swagger'; 23 | 24 | import { JWTAdminGuard } from '#modules/auth/guards/jwt-admin.guard'; 25 | import { SecretGuard } from '#modules/auth/guards/secret.guard'; 26 | import { JWTUserPayload } from '#modules/auth/strategies/jwt.strategy'; 27 | import { TermsOfServiceService } from '#modules/terms-of-service/terms-of-service.service'; 28 | import { UserService } from '#modules/user/user.service'; 29 | import { AdminCreateAdminUserDTO } from '#platforms/admin/dtos/create-admin-user.dto'; 30 | import { AdminUpsertTermsOfServiceDTO } from '#platforms/admin/dtos/upsert-terms-of-service.dto'; 31 | import { AdminFormattedUser } from '#platforms/admin/responses/formatted-user.response'; 32 | import { AdminUpsertTermsOfServiceResponse } from '#platforms/admin/responses/upsert-terms-of-service.response'; 33 | 34 | @ApiTags('Platform [Admin]') 35 | @Controller('protected/admin') 36 | export class AdminProtectedController { 37 | constructor( 38 | private readonly userService: UserService, 39 | private readonly tosService: TermsOfServiceService, 40 | ) {} 41 | 42 | @Post('admin-users') 43 | @SecretGuard() 44 | @ApiOperation({ summary: 'Create an admin user' }) 45 | @ApiStandardResponse({ status: HttpStatus.CREATED }) 46 | async createAdmin(@Body() dto: AdminCreateAdminUserDTO): Promise { 47 | return this.userService.createAdmin(dto); 48 | } 49 | 50 | @Get('users') 51 | @JWTAdminGuard() 52 | @UseInterceptors(CRUDInterceptor) 53 | @ApiOperation({ summary: 'Get all users and their todo items' }) 54 | @ApiCrudQueries() 55 | @ApiStandardListResponse({ type: AdminFormattedUser }) 56 | async getAllUsers( 57 | @ParsedRequest() req: CRUDRequest, 58 | ): ReturnType { 59 | return this.userService.getAll(req); 60 | } 61 | 62 | @Patch('users/:uuid') 63 | @JWTAdminGuard() 64 | @ApiOperation({ summary: 'Approve an user creation request' }) 65 | @ApiStandardResponse() 66 | async approveUser(@Param() { uuid }: UUIDParamDTO): Promise { 67 | return this.userService.approve(uuid); 68 | } 69 | 70 | @Delete('users/:uuid') 71 | @JWTAdminGuard() 72 | @ApiOperation({ summary: 'Reject an user creation request or ban an user' }) 73 | @ApiStandardResponse() 74 | async rejectUser(@Param() { uuid }: UUIDParamDTO): Promise { 75 | return this.userService.reject(uuid); 76 | } 77 | 78 | @Put('terms-of-services') 79 | @JWTAdminGuard() 80 | @ApiOperation({ summary: 'Upsert terms of service' }) 81 | @ApiStandardResponse({ type: AdminUpsertTermsOfServiceResponse }) 82 | async upsertTermsOfServices( 83 | @User() { uuid: operatorUUID }: JWTUserPayload, 84 | @Body() dto: AdminUpsertTermsOfServiceDTO, 85 | ): ReturnType { 86 | return this.tosService.upsert(operatorUUID, dto); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/platforms/admin/dtos/create-admin-user.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; 2 | 3 | import { ApiProperty } from '@nestjs/swagger'; 4 | 5 | export class AdminCreateAdminUserDTO { 6 | @IsEmail() 7 | @ApiProperty({ format: 'email', example: 'todo@example.com' }) 8 | readonly email!: string; 9 | 10 | @IsNotEmpty() 11 | @IsString() 12 | @ApiProperty({ format: 'password', example: '123456' }) 13 | readonly password!: string; 14 | } 15 | -------------------------------------------------------------------------------- /src/platforms/admin/dtos/upsert-terms-of-service.dto.ts: -------------------------------------------------------------------------------- 1 | import { Type } from 'class-transformer'; 2 | import { 3 | ArrayNotEmpty, 4 | IsArray, 5 | IsInstance, 6 | IsInt, 7 | IsLocale, 8 | IsNotEmpty, 9 | IsOptional, 10 | IsPositive, 11 | IsString, 12 | } from 'class-validator'; 13 | 14 | import { ApiProperty } from '@nestjs/swagger'; 15 | 16 | import { LocaleCode } from '#app/app.constant'; 17 | import { TermsOfServiceTranslation } from '#entities/terms-of-service-translation.entity'; 18 | 19 | class AdminUpsertTermsOfServiceTranslation { 20 | @IsLocale() 21 | @ApiProperty({ 22 | pattern: '^[A-z]{2,4}([_-]([A-z]{4}|[d]{3}))?([_-]([A-z]{2}|[d]{3}))?$', 23 | example: 'en-US', 24 | }) 25 | readonly code!: LocaleCode; 26 | 27 | @IsNotEmpty() 28 | @IsString() 29 | @ApiProperty({ 30 | example: 31 | 'A terms of service agreement explains the guidelines of your website.', 32 | }) 33 | readonly content!: string; 34 | } 35 | 36 | export class AdminUpsertTermsOfServiceDTO { 37 | @IsOptional() 38 | @IsPositive() 39 | @IsInt() 40 | @ApiProperty({ type: 'integer', minimum: 1 }) 41 | readonly version?: number; 42 | 43 | @IsNotEmpty() 44 | @IsString() 45 | @ApiProperty({ example: 'This is the first version of terms of service' }) 46 | readonly note!: string; 47 | 48 | @IsArray() 49 | @ArrayNotEmpty() 50 | @IsInstance(TermsOfServiceTranslation, { each: true }) 51 | @Type(() => TermsOfServiceTranslation) 52 | @ApiProperty() 53 | readonly translations!: AdminUpsertTermsOfServiceTranslation[]; 54 | } 55 | -------------------------------------------------------------------------------- /src/platforms/admin/responses/formatted-user.response.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | import { TodoStatus } from '#entities/todo.entity'; 4 | import { Role, UserStatus } from '#entities/user.entity'; 5 | 6 | export class AdminFormattedUserTodo { 7 | @ApiProperty() 8 | readonly createdAt!: Date; 9 | 10 | @ApiProperty() 11 | readonly updatedAt!: Date; 12 | 13 | @ApiProperty({ format: 'uuid' }) 14 | readonly uuid!: string; 15 | 16 | @ApiProperty() 17 | readonly status!: TodoStatus; 18 | 19 | @ApiProperty() 20 | readonly message!: string; 21 | } 22 | 23 | export class AdminFormattedUser { 24 | @ApiProperty() 25 | readonly createdAt!: Date; 26 | 27 | @ApiProperty() 28 | readonly updatedAt!: Date; 29 | 30 | @ApiProperty({ format: 'uuid' }) 31 | readonly uuid!: string; 32 | 33 | @ApiProperty() 34 | readonly status!: UserStatus; 35 | 36 | @ApiProperty() 37 | readonly role!: Role; 38 | 39 | @ApiProperty({ format: 'email' }) 40 | readonly email!: string; 41 | 42 | @ApiProperty() 43 | readonly todos!: AdminFormattedUserTodo[]; 44 | } 45 | -------------------------------------------------------------------------------- /src/platforms/admin/responses/upsert-terms-of-service.response.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class AdminUpsertTermsOfServiceResponse { 4 | @ApiProperty({ type: 'integer', minimum: 1 }) 5 | readonly version!: number; 6 | } 7 | -------------------------------------------------------------------------------- /src/platforms/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | 3 | @Module({ 4 | imports: [], 5 | providers: [], 6 | controllers: [], 7 | }) 8 | export class AppModule {} 9 | -------------------------------------------------------------------------------- /src/platforms/web/dtos/create-todo.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty, IsString } from 'class-validator'; 2 | 3 | import { ApiProperty } from '@nestjs/swagger'; 4 | 5 | export class WebCreateTodoDTO { 6 | @IsNotEmpty() 7 | @IsString() 8 | @ApiProperty({ example: 'Remember to buy 3 eggs before tonight' }) 9 | readonly message!: string; 10 | } 11 | -------------------------------------------------------------------------------- /src/platforms/web/dtos/register.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; 2 | 3 | import { ApiProperty } from '@nestjs/swagger'; 4 | 5 | export class WebRegisterDTO { 6 | @IsEmail() 7 | @ApiProperty({ format: 'email', example: 'todo@example.com' }) 8 | readonly email!: string; 9 | 10 | @IsNotEmpty() 11 | @IsString() 12 | @ApiProperty({ format: 'password', example: '123456' }) 13 | readonly password!: string; 14 | } 15 | -------------------------------------------------------------------------------- /src/platforms/web/dtos/update-todo.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator'; 2 | 3 | import { ApiPropertyOptional } from '@nestjs/swagger'; 4 | 5 | import { TodoStatus } from '#entities/todo.entity'; 6 | 7 | export class WebUpdateTodoDTO { 8 | @IsOptional() 9 | @IsEnum(TodoStatus) 10 | @ApiPropertyOptional({ example: TodoStatus.Done }) 11 | readonly status?: TodoStatus; 12 | 13 | @IsOptional() 14 | @IsNotEmpty() 15 | @IsString() 16 | @ApiPropertyOptional({ example: 'Remember to buy 4 eggs before tonight' }) 17 | readonly message?: string; 18 | } 19 | -------------------------------------------------------------------------------- /src/platforms/web/responses/create-todo.response.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class WebCreateTodoResponse { 4 | @ApiProperty({ format: 'uuid' }) 5 | readonly uuid!: string; 6 | } 7 | -------------------------------------------------------------------------------- /src/platforms/web/responses/formatted-todo.response.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | import { TodoStatus } from '#entities/todo.entity'; 4 | 5 | export class WebFormattedTodoResponse { 6 | @ApiProperty({ format: 'uuid' }) 7 | readonly uuid!: string; 8 | 9 | @ApiProperty({ example: TodoStatus.Done }) 10 | readonly status!: TodoStatus; 11 | 12 | @ApiProperty({ example: 'Remember to buy 3 eggs before tonight' }) 13 | readonly message!: string; 14 | } 15 | -------------------------------------------------------------------------------- /src/platforms/web/responses/get-latest-terms-of-service.response.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class WebGetLatestTermsOfServiceResponse { 4 | @ApiProperty() 5 | readonly updatedAt!: Date; 6 | 7 | @ApiProperty({ type: 'integer', minimum: 1 }) 8 | readonly version!: number; 9 | 10 | @ApiProperty() 11 | readonly content!: string; 12 | } 13 | -------------------------------------------------------------------------------- /src/platforms/web/responses/get-todo-details.response.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | import { TodoStatus } from '#entities/todo.entity'; 4 | 5 | export class WebGetTodoDetailsResponse { 6 | @ApiProperty() 7 | readonly createdAt!: Date; 8 | 9 | @ApiProperty() 10 | readonly updatedAt?: Date; 11 | 12 | @ApiProperty({ format: 'uuid' }) 13 | readonly uuid!: string; 14 | 15 | @ApiProperty({ example: TodoStatus.Done }) 16 | readonly status!: TodoStatus; 17 | 18 | @ApiProperty({ example: 'Remember to buy 3 eggs before tonight' }) 19 | readonly message!: string; 20 | } 21 | -------------------------------------------------------------------------------- /src/platforms/web/web.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | 3 | import { TermsOfServiceModule } from '#modules/terms-of-service/terms-of-service.module'; 4 | import { TodoModule } from '#modules/todo/todo.module'; 5 | import { UserModule } from '#modules/user/user.module'; 6 | import { WebProtectedController } from '#platforms/web/web.protected.controller'; 7 | import { WebPublicController } from '#platforms/web/web.public.controller'; 8 | 9 | @Module({ 10 | imports: [TermsOfServiceModule, TodoModule, UserModule], 11 | providers: [], 12 | controllers: [WebProtectedController, WebPublicController], 13 | }) 14 | export class WebModule {} 15 | -------------------------------------------------------------------------------- /src/platforms/web/web.protected.controller.ts: -------------------------------------------------------------------------------- 1 | import { CRUDInterceptor, CRUDRequest, ParsedRequest } from 'nestjs-xion/crud'; 2 | import { 3 | ApiStandardListResponse, 4 | ApiStandardResponse, 5 | User, 6 | } from 'nestjs-xion/decorator'; 7 | import { UUIDParamDTO } from 'nestjs-xion/dto'; 8 | 9 | import { 10 | Body, 11 | Controller, 12 | Delete, 13 | Get, 14 | HttpStatus, 15 | Param, 16 | Patch, 17 | Post, 18 | UseInterceptors, 19 | } from '@nestjs/common'; 20 | import { ApiOperation, ApiTags } from '@nestjs/swagger'; 21 | 22 | import { JWTUserGuard } from '#modules/auth/guards/jwt-user.guard'; 23 | import { JWTUserPayload } from '#modules/auth/strategies/jwt.strategy'; 24 | import { TodoService } from '#modules/todo/todo.service'; 25 | import { WebCreateTodoDTO } from '#platforms/web/dtos/create-todo.dto'; 26 | import { WebUpdateTodoDTO } from '#platforms/web/dtos/update-todo.dto'; 27 | import { WebCreateTodoResponse } from '#platforms/web/responses/create-todo.response'; 28 | import { WebFormattedTodoResponse } from '#platforms/web/responses/formatted-todo.response'; 29 | import { WebGetTodoDetailsResponse } from '#platforms/web/responses/get-todo-details.response'; 30 | 31 | @ApiTags('Platform [Web]') 32 | @JWTUserGuard() 33 | @Controller('protected/web') 34 | export class WebProtectedController { 35 | constructor(private readonly todoService: TodoService) {} 36 | 37 | @Post('todos') 38 | @ApiOperation({ summary: 'Create a new todo item' }) 39 | @ApiStandardResponse({ 40 | status: HttpStatus.CREATED, 41 | type: WebCreateTodoResponse, 42 | }) 43 | async createTodo( 44 | @User() { uuid: userUUID }: JWTUserPayload, 45 | @Body() dto: WebCreateTodoDTO, 46 | ): ReturnType { 47 | return this.todoService.create(userUUID, dto); 48 | } 49 | 50 | @Get('todos') 51 | @UseInterceptors(CRUDInterceptor) 52 | @ApiOperation({ summary: 'Get all todo items' }) 53 | @ApiStandardListResponse({ type: WebFormattedTodoResponse }) 54 | async getAllTodos( 55 | @User() { uuid: userUUID }: JWTUserPayload, 56 | @ParsedRequest() req: CRUDRequest, 57 | ): ReturnType { 58 | return this.todoService.getAll(userUUID, req); 59 | } 60 | 61 | @Get('todos/:uuid') 62 | @ApiOperation({ summary: 'Get details of a todo item' }) 63 | @ApiStandardResponse({ type: WebGetTodoDetailsResponse }) 64 | async getTodoDetails( 65 | @User() { uuid: userUUID }: JWTUserPayload, 66 | @Param() { uuid }: UUIDParamDTO, 67 | ): ReturnType { 68 | return this.todoService.getDetails(userUUID, uuid); 69 | } 70 | 71 | @Patch('todos/:uuid') 72 | @ApiOperation({ summary: 'Update an existing todo item' }) 73 | @ApiStandardResponse() 74 | async updateTodo( 75 | @User() { uuid: userUUID }: JWTUserPayload, 76 | @Param() { uuid }: UUIDParamDTO, 77 | @Body() dto: WebUpdateTodoDTO, 78 | ): Promise { 79 | return this.todoService.update(userUUID, uuid, dto); 80 | } 81 | 82 | @Delete('todos/:uuid') 83 | @ApiOperation({ summary: 'Delete an existing todo item' }) 84 | @ApiStandardResponse() 85 | async deleteTodo( 86 | @User() { uuid: userUUID }: JWTUserPayload, 87 | @Param() { uuid }: UUIDParamDTO, 88 | ): Promise { 89 | return this.todoService.delete(userUUID, uuid); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/platforms/web/web.public.controller.ts: -------------------------------------------------------------------------------- 1 | import { ApiStandardResponse } from 'nestjs-xion/decorator'; 2 | 3 | import { Body, Controller, Get, HttpStatus, Post } from '@nestjs/common'; 4 | import { ApiOperation, ApiTags } from '@nestjs/swagger'; 5 | 6 | import { LocaleCode } from '#app/app.constant'; 7 | import { TermsOfServiceService } from '#modules/terms-of-service/terms-of-service.service'; 8 | import { UserService } from '#modules/user/user.service'; 9 | import { WebRegisterDTO } from '#platforms/web/dtos/register.dto'; 10 | import { WebGetLatestTermsOfServiceResponse } from '#platforms/web/responses/get-latest-terms-of-service.response'; 11 | import { ApiLocale, Locale } from '#utils/decorator'; 12 | 13 | @ApiTags('Platform [Web]') 14 | @Controller('public/web') 15 | export class WebPublicController { 16 | constructor( 17 | private readonly userService: UserService, 18 | private readonly tosService: TermsOfServiceService, 19 | ) {} 20 | 21 | @Get('terms-of-services/latest') 22 | @ApiLocale() 23 | @ApiOperation({ summary: 'Get the latest terms of service' }) 24 | @ApiStandardResponse({ type: WebGetLatestTermsOfServiceResponse }) 25 | async getLatestTermsOfService( 26 | @Locale() code: LocaleCode, 27 | ): ReturnType { 28 | return this.tosService.getLatestOne(code); 29 | } 30 | 31 | @Post('users') 32 | @ApiOperation({ summary: 'Register as a new user' }) 33 | @ApiStandardResponse({ status: HttpStatus.CREATED }) 34 | async registerUser(@Body() dto: WebRegisterDTO): Promise { 35 | return this.userService.register(dto); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/utils/decorator.ts: -------------------------------------------------------------------------------- 1 | import { createParamDecorator } from '@nestjs/common'; 2 | import { ApiQuery } from '@nestjs/swagger'; 3 | 4 | import { LocaleCode } from '#app/app.constant'; 5 | 6 | import type { Request } from 'express'; 7 | import type { ExecutionContext } from '@nestjs/common'; 8 | 9 | export function Locale(): ParameterDecorator { 10 | return createParamDecorator((_, ctx: ExecutionContext) => { 11 | const { locale } = ctx.switchToHttp().getRequest().query; 12 | 13 | switch (locale) { 14 | default: 15 | return LocaleCode.English; 16 | case LocaleCode.English: 17 | case LocaleCode.Vietnamese: 18 | case LocaleCode.SimplifiedChinese: 19 | case LocaleCode.TraditionalChinese: 20 | return locale; 21 | } 22 | })(); 23 | } 24 | 25 | export function ApiLocale(): MethodDecorator { 26 | return (...params): void => { 27 | ApiQuery({ name: 'locale', example: 'en-US' })(...params); 28 | }; 29 | } 30 | -------------------------------------------------------------------------------- /src/utils/rmq.ts: -------------------------------------------------------------------------------- 1 | import { Transport } from '@nestjs/microservices'; 2 | 3 | import type { INestApplication } from '@nestjs/common'; 4 | import type { RMQConfig } from '#configs'; 5 | 6 | export function setup( 7 | app: INestApplication, 8 | options: RMQConfig['options'], 9 | ): void { 10 | app.connectMicroservice({ transport: Transport.RMQ, options }); 11 | } 12 | -------------------------------------------------------------------------------- /src/utils/swagger.ts: -------------------------------------------------------------------------------- 1 | import { customOptions } from 'nestjs-xion/swagger'; 2 | 3 | import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; 4 | 5 | import { BaseAppModule } from '#app/app.module'; 6 | import { AuthStrategy } from '#modules/auth/auth.constant'; 7 | 8 | import type { INestApplication } from '@nestjs/common'; 9 | import type { AppConfig } from '#configs'; 10 | 11 | export function setup(app: INestApplication, { name }: AppConfig): void { 12 | const config = new DocumentBuilder() 13 | .setTitle(name) 14 | .addBearerAuth({ type: 'http' }, AuthStrategy.JWT) 15 | .addSecurity(AuthStrategy.Secret, { 16 | type: 'apiKey', 17 | name: AuthStrategy.Secret, 18 | in: 'header', 19 | }); 20 | 21 | SwaggerModule.setup( 22 | 'doc', 23 | app, 24 | SwaggerModule.createDocument(app, config.build(), { 25 | include: [BaseAppModule], 26 | deepScanRoutes: true, 27 | }), 28 | customOptions(name), 29 | ); 30 | } 31 | -------------------------------------------------------------------------------- /src/utils/time.ts: -------------------------------------------------------------------------------- 1 | export enum CronTime { 2 | Daily = '0 0 * * *', // Every 00:00:00 3 | } 4 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | /* TSConfig Reference https://www.typescriptlang.org/tsconfig */ 2 | { 3 | /* File Inclusion */ 4 | "include": ["src", "@types"], 5 | "exclude": ["dist", "node_modules"], 6 | "compilerOptions": { 7 | /* Project Options */ 8 | "target": "ESNext", 9 | "module": "CommonJS", 10 | "importHelpers": true, 11 | "isolatedModules": true, 12 | "outDir": "dist", 13 | "removeComments": true, 14 | /* Strict Checks */ 15 | "strict": true, 16 | /* Module Resolution */ 17 | "allowSyntheticDefaultImports": true, 18 | "baseUrl": ".", 19 | "esModuleInterop": true, 20 | "moduleResolution": "Node10", 21 | "paths": { 22 | "#app/*": ["src/app/*"], 23 | "#configs": ["src/configs"], 24 | "#configs/*": ["src/configs/*"], 25 | "#entities/*": ["src/entities/*"], 26 | "#modules/*": ["src/modules/*"], 27 | "#platforms/*": ["src/platforms/*"], 28 | "#utils/*": ["src/utils/*"] 29 | }, 30 | /* Linter Checks */ 31 | "noFallthroughCasesInSwitch": true, 32 | "noImplicitReturns": true, 33 | "noUnusedLocals": true, 34 | "noUnusedParameters": true, 35 | /* Experimental */ 36 | "emitDecoratorMetadata": true, 37 | "experimentalDecorators": true, 38 | /* Advanced */ 39 | "forceConsistentCasingInFileNames": true, 40 | "preserveConstEnums": true, 41 | "resolveJsonModule": true, 42 | "skipLibCheck": true 43 | } 44 | } 45 | --------------------------------------------------------------------------------