I frequently initialize projects, and some features are common across them. Implementing these common features from scratch every time is cumbersome, so I have extracted them into this project. github nestjs-pg-tmplate
Related Features
- ts strict true
- debugger vscode
- eslint, prettier, cSpell, commitLint, husky
- config yml env support
- validate and transform
- docker compose pg redis
- typeorm migration soft-delete
- user login register rbac
- app metaData
- open sdk generate
- logger dayjs
ts strict true
{
// ...
"strict": true,
"strictNullChecks": true,
"noImplicitAny": false,
"strictBindCallApply": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true
// ...
}
debugger vscode
// .vscode/settings.json
{
"editor.detectIndentation": false,
"editor.tabSize": 2,
"editor.indentSize": 2,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach NestJS WS",
"port": 9229,
"restart": true
}
]
}
// .vscode/extensions.json
{
"recommendations": [
"dbaeumer.vscode-eslint", // ESLint 插件
"esbenp.prettier-vscode", // Prettier 插件
// "rangav.vscode-thunder-client", // thunder client
"streetsidesoftware.code-spell-checker" // spell
]
}
eslint, prettier, cSpell, commitLint, husky
prettier-related changes
endOfLine: 'auto' // 主要针对不同系统换行及结尾问题
eslint and prettier are installed automatically when initializing a default NestJS project. You only need to make the relevant updates to the configuration files.
commitLint husky corresponding commit records
# npx husky init
"prepare": "husky"
pnpm i @commitlint/cli @commitlint/config-conventional husky -D
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
}
# .husky/pre-commit
pnpm test
pnpm lint
# .husky/commit-msg
npx --no -- commitlint --edit "$1"
config yml env
The project configuration has not been extracted into a separate package, and strict validation is applied to the configuration types.
config yml env related commit history
pnpm add --save class-validator class-transformer @nestjs/config js-yaml
pnpm add @types/js-yaml -D
// src/config/config.ts
import {
IsEnum,
IsNumber,
IsOptional,
IsString,
Validate,
ValidateIf,
} from 'class-validator'
export enum Env {
dev = 'dev',
pro = 'pro',
}
export class db {
@IsString()
host!: string
@IsNumber()
port!: number
@IsString()
username!: string
@IsString()
password!: string
@IsString()
database!: string
}
export class Security {
@IsString()
jwtKey!: string
/** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */
@IsOptional()
@ValidateIf((_, val) => typeof val === 'number')
@IsNumber()
@ValidateIf((_, val) => typeof val === 'string')
@IsString()
jwtExpiresIn?: number = 30 * 60
}
export class Config {
@IsOptional()
@IsEnum(Env)
env: Env = Env.dev
@IsOptional()
@IsString()
appName: string = 'server'
@Validate(() => Security)
security!: Security
@Validate(() => db)
db!: db
}
// src/config/configuration.ts
import { readFileSync } from 'fs'
import * as yaml from 'js-yaml'
import { join } from 'path'
import { Config } from './config'
import { plainToInstance } from 'class-transformer'
import { validateSync } from 'class-validator'
const YAML_CONFIG_FILENAME = 'config.yml'
let config: Config | undefined
export default () => {
if (config) return config
const configData = yaml.load(
readFileSync(join(process.cwd(), YAML_CONFIG_FILENAME), 'utf8')
) as Record<string, any>
// transform and valiate
const target = plainToInstance(Config, configData)
const error = validateSync(target)
if (error.length > 0) {
throw new Error(error.map(err => err.toString(true)).join('\n'))
} else {
config = target
return target
}
}
Validate and Transform
Extremely important, mainly for validation and transformation rules
// src/main.ts
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { ValidationPipe } from '@nestjs/common'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.useGlobalPipes(
new ValidationPipe({
transform: true,
transformOptions: {
strategy: 'excludeAll',
enableImplicitConversion: true,
excludeExtraneousValues: true,
},
})
)
app.enableCors()
await app.listen(3000)
}
bootstrap()
docker compose pg redis
Installing environment dependencies, primarily for local development environments; production environments should be handled separately. Redis is included here because it is commonly used for pub/sub or caching, although these features are not implemented in the template. This will be considered for future implementation.
docker compose pg redis related commit history
# .gitignore
volumes
# docker-compose-depend.yml
services:
redis:
image: redis:latest
container_name: redis
restart: unless-stopped
privileged: true
volumes:
- ./volumes/redis/datadir:/data
- ./volumes/redis/conf/redis.conf:/usr/local/etc/redis/redis.conf
- ./volumes/redis/logs:/logs
command:
# redis-server
# 两个写入操作 只是为了解决启动后警告 可以去掉
/bin/bash -c "echo 511 > /proc/sys/net/core/somaxconn && echo never > /sys/kernel/mm/transparent_hugepage/enabled && redis-server /usr/local/etc/redis/redis.conf"
ports:
- 6379:6379
networks:
- dev
pgsql:
image: postgres:latest
restart: unless-stopped
container_name: pgsql-new
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- TZ=Asia/Shanghai
ports:
- '5434:5432'
volumes:
# 初始的数据文件
- ./volumes/pgsql/data:/var/lib/postgresql/data
networks:
- dev
networks:
dev:
name: local-dev
# redis pgsql
docker compose -f docker-compose-depend.yml up -d
typeorm pg
This section mainly extracts the db module as a lib, supporting typeorm and related features such as basic entities, soft delete, migrations, rollback, and entity synchronization.
typeorm pg related commit history
nest g lib db
pnpm add --save @nestjs/typeorm typeorm pg
User Login Registration RBAC
Further consideration is needed. The permissions here are essentially metadata information for the interfaces. Role permissions are combinations of permissions, while user permissions are the union of role permissions and user-specific permissions.
Commit history related to user login, registration, and RBAC
pnpm add bcrypt @nestjs/jwt @nestjs/passport passport-jwt
nest g mo auth
nest g co auth
nest g s auth
nest g mo user
nest g co user
nest g s user
nest g mo role
nest g co role
nest g s role
There is a large amount of code. Only the implementation related to application metadata is shown here. For the rest, please refer to the relevant commit in the code repository.
import { Controller, Get } from '@nestjs/common'
import { DiscoveryService, Reflector } from '@nestjs/core'
import { Describe, DESCRIBE_KEY } from 'src/_decorator/describe'
import { ControllerInfo } from './dto/meta.dto'
// 做进程内缓存, 避免重复计算
let allControllerInfo: ControllerInfo[] | undefined
/**
* 权限管理
*/
@Controller('meta')
@Describe('权限管理')
export class MetaController {
constructor(
private readonly discoveryService: DiscoveryService,
private readonly reflector: Reflector
) {}
/**
* 获取所有权限信息
* @returns 权限信息
*/
@Get()
@Describe('所有权限信息')
allMetaData(): ControllerInfo[] {
if (allControllerInfo) return allControllerInfo
const controllers = this.discoveryService.getControllers()
const result: ControllerInfo[] = []
controllers.forEach(controller => {
const name = controller.name
const describe = this.reflector.get(DESCRIBE_KEY, controller.metatype)
if (!describe) return
const methods = Object.getOwnPropertyNames(controller.metatype.prototype)
const resMethods = methods
.map(method => {
if (method !== 'constructor') {
const methodDescribe = Reflect.getMetadata(
DESCRIBE_KEY,
controller.metatype.prototype[method]
)
if (methodDescribe)
return {
name: method,
describe: methodDescribe,
context: `${name}/${method}`,
}
}
})
.filter(Boolean) as ControllerInfo['methods']
result.push({ name, describe, methods: resMethods, context: name })
})
allControllerInfo = result
return result
}
}
open sdk generate
Documentation is written and SDKs are generated using the openapi branch. Currently, instead of publishing an npm package, it is referenced via a sub-repository.
open sdk generate related commit history
pnpm add @nestjs/swagger @hey-api/openapi-ts @hey-api/client-fetch -D
# change branch to openapi
npm version patch
git push --tags
git push
dayjs and logger
Logging Related
dayjs and logger related commit history
pnpm i winston nest-winston dayjs
import * as winston from 'winston'
import {
utilities as nestWinstonModuleUtilities,
WinstonModule,
} from 'nest-winston'
import * as path from 'path'
import configuration from 'src/config/configuration'
import { Env } from 'src/config/config'
const transports = {
console: new winston.transports.Console({
level: 'silly',
}),
logFile: new winston.transports.File({
dirname: path.join(process.cwd(), 'logs'),
filename: 'log.json',
level: 'silly',
}),
}
const getLogger = async () => {
const config = configuration()
// 如果是本地测试环境则启用 nest 风格的 log format
if (config.env == Env.dev) {
transports.console = new winston.transports.Console({
level: 'silly',
format: winston.format.combine(
winston.format.timestamp({
format: () =>
new Date().toLocaleString('chinese', {
timeZone: 'Asia/Shanghai',
hour12: false,
}),
}),
nestWinstonModuleUtilities.format.nestLike(config.appName)
),
})
}
const logger = WinstonModule.createLogger({
transports: [transports.console, transports.logFile],
level: 'silly',
})
return logger
}
export default getLogger
Data Migration
# 生成迁移 (根据实体信息)
npm run typeorm migration:generate -n ./libs/db/src/migrations/fix-data
# 新建迁移
npx typeorm migration:create ./libs/db/src/migrations/init-data
# 迁移
npm run typeorm migration:run --fake
# 回滚
npm run typeorm migration:revert
# 同步实体
npm run typeorm schema:sync
Commit Code
pnpm lint
# git commit -m "type: subject"
# rules view https://www.npmjs.com/package/@commitlint/config-conventional
Comments (0)
No comments yet. Be the first to leave one!