ad nest
parent
3e51df19d9
commit
8640838804
|
@ -1,7 +1,7 @@
|
|||
/** @type {import('ts-jest').JestConfigWithTsJest} **/
|
||||
export default {
|
||||
testEnvironment: 'node',
|
||||
testEnvironment: "node",
|
||||
transform: {
|
||||
'^.+.tsx?$': ['ts-jest', {}],
|
||||
"^.+.tsx?$": ["ts-jest", {}],
|
||||
},
|
||||
};
|
||||
|
|
|
@ -63,7 +63,8 @@
|
|||
"jest": "catalog:",
|
||||
"prisma": "catalog:",
|
||||
"ts-jest": "catalog:",
|
||||
"tsx": "catalog:"
|
||||
"tsx": "catalog:",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"prisma": {
|
||||
"schema": "src/database/schema"
|
||||
|
|
|
@ -65,6 +65,7 @@ export const postApi = app
|
|||
if (!validated.success) {
|
||||
return c.json(
|
||||
createErrorResult("请求数据验证失败", validated.error.errors),
|
||||
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Tests
|
||||
/coverage
|
||||
/.nyc_output
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.dev
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
.tmp
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
|
@ -0,0 +1,98 @@
|
|||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Project setup
|
||||
|
||||
```bash
|
||||
$ pnpm install
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ pnpm run start
|
||||
|
||||
# watch mode
|
||||
$ pnpm run start:dev
|
||||
|
||||
# production mode
|
||||
$ pnpm run start:prod
|
||||
```
|
||||
|
||||
## Run tests
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ pnpm run test
|
||||
|
||||
# e2e tests
|
||||
$ pnpm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ pnpm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ pnpm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
|
@ -0,0 +1,6 @@
|
|||
```javascript
|
||||
eslint.config.mjs
|
||||
|
||||
// 在nestjs中,需要关闭consistent-type-imports,否则注入的依赖不是类而是类型,
|
||||
"@typescript-eslint/consistent-type-imports": "off",
|
||||
```
|
|
@ -0,0 +1,3 @@
|
|||
import eslint from "@repo/eslint-config/nest-js";
|
||||
|
||||
export default eslint;
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
{
|
||||
"name": "talk",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"description": "",
|
||||
"author": "",
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "cross-env NODE_ENV=dev nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@3rapp/utils": "workspace:*",
|
||||
"@nestjs/common": "^11.1.0",
|
||||
"@nestjs/config": "^4.0.2",
|
||||
"@nestjs/core": "^11.1.0",
|
||||
"@nestjs/jwt": "^11.0.0",
|
||||
"@nestjs/platform-express": "^11.1.0",
|
||||
"@nestjs/swagger": "^11.2.0",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.2",
|
||||
"dayjs": "^1.11.13",
|
||||
"dotenv": "^16.5.0",
|
||||
"joi": "^17.13.3",
|
||||
"lodash": "catalog:",
|
||||
"nest-winston": "^1.10.2",
|
||||
"pg": "catalog:",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"request-ip": "^3.3.0",
|
||||
"rxjs": "^7.8.2",
|
||||
"typeorm": "^0.3.23",
|
||||
"uuid": "catalog:",
|
||||
"validator": "^13.15.0",
|
||||
"winston": "^3.17.0",
|
||||
"winston-daily-rotate-file": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^11.0.7",
|
||||
"@nestjs/schematics": "^11.0.5",
|
||||
"@nestjs/testing": "^11.1.0",
|
||||
"@repo/eslint-config": "workspace:*",
|
||||
"@swc/cli": "^0.6.0",
|
||||
"@swc/core": "^1.11.24",
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/express": "^5.0.1",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/lodash": "catalog:",
|
||||
"@types/node": "^22.15.17",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"cross-env": "^7.0.3",
|
||||
"globals": "^16.1.0",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^3.5.3",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.1.0",
|
||||
"ts-jest": "^29.3.2",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
import { Global, Logger, Module, ValidationPipe } from "@nestjs/common";
|
||||
import { APP_FILTER, APP_PIPE } from "@nestjs/core";
|
||||
|
||||
import { ConfigModule } from "./common/config/config.module";
|
||||
import { database } from "./config/database.config";
|
||||
import { AppFilter } from "./filters/app.filter";
|
||||
import { Env } from "./modules/config/env";
|
||||
import { DatabaseModule } from "./modules/database/database.module";
|
||||
import { UserModule } from "./modules/user/user.module";
|
||||
|
||||
// 当providers 为空时,就会从di容器从import的模块中查找->其他模块需要两个部分一个是providers,一个是exports,providers是用来提供实例的,exports是用来导出模块的
|
||||
// 第二种直接在当前providers中导入其他模块的providers,然后在当前模块的providers中导入其他模块的exports,这样就可以实现模块间的依赖注入
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [
|
||||
DatabaseModule.forRoot(database(new Env())),
|
||||
UserModule,
|
||||
ConfigModule.forRoot(),
|
||||
],
|
||||
controllers: [],
|
||||
exports: [
|
||||
{
|
||||
module: Logger,
|
||||
global: true,
|
||||
},
|
||||
],
|
||||
providers: [
|
||||
Logger,
|
||||
|
||||
{
|
||||
provide: APP_PIPE,
|
||||
useClass: ValidationPipe,
|
||||
},
|
||||
{
|
||||
provide: APP_FILTER,
|
||||
useClass: AppFilter,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppModule {
|
||||
static forRoot() {
|
||||
return {};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
/* eslint-disable node/prefer-global/process */
|
||||
import { Module } from "@nestjs/common";
|
||||
import { ConfigModule as NestConfigModule } from "@nestjs/config";
|
||||
import * as Joi from "joi";
|
||||
const envFilePath = [`.env.${process.env.NODE_ENV || `development`}`, `.env`];
|
||||
const schema = Joi.object({
|
||||
NODE_ENV: Joi.string().valid("development", "dev", "prod", "prodution"),
|
||||
PORT: Joi.number().default(3000),
|
||||
});
|
||||
@Module({})
|
||||
export class ConfigModule {
|
||||
static forRoot() {
|
||||
return {
|
||||
module: ConfigModule,
|
||||
imports: [
|
||||
NestConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
validationSchema: schema,
|
||||
envFilePath,
|
||||
}),
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
import type { DataSourceOptions } from "typeorm";
|
||||
|
||||
import { toNumber } from "lodash";
|
||||
import { Env } from "src/modules/config/env";
|
||||
import { AccessTokenEntity } from "src/modules/user/entities/access-token.entity";
|
||||
import { RefreshTokenEntity } from "src/modules/user/entities/refresh-token.entity";
|
||||
import { UserEntity } from "src/modules/user/entities/user.entity";
|
||||
export function database(env: Env): DataSourceOptions {
|
||||
console.log("env", env.get("DB_HOST"));
|
||||
|
||||
return {
|
||||
type: "postgres",
|
||||
host: env.get("DB_HOST", "127.0.0.1"),
|
||||
port: toNumber(env.get("DB_PORT", "5432")),
|
||||
schema: "public",
|
||||
username: env.get("DB_USERNAME"),
|
||||
password: env.get("DB_PASSWORD"),
|
||||
database: env.get("DB_DATABASE"),
|
||||
logging: false,
|
||||
entities: [UserEntity, AccessTokenEntity, RefreshTokenEntity],
|
||||
synchronize: true,
|
||||
};
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
import {
|
||||
ArgumentsHost,
|
||||
BadRequestException,
|
||||
Catch,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Type,
|
||||
} from "@nestjs/common";
|
||||
import { BaseExceptionFilter } from "@nestjs/core";
|
||||
import { isObject } from "lodash";
|
||||
import {
|
||||
EntityNotFoundError,
|
||||
EntityPropertyNotFoundError,
|
||||
QueryFailedError,
|
||||
} from "typeorm";
|
||||
|
||||
/**
|
||||
* 全局过滤器,用于响应自定义异常
|
||||
*/
|
||||
@Catch()
|
||||
export class AppFilter extends BaseExceptionFilter<Error> {
|
||||
protected resExceptions: Array<{ class: Type<Error>; status: number }> = [
|
||||
{ class: EntityNotFoundError, status: HttpStatus.NOT_FOUND },
|
||||
{ class: QueryFailedError, status: HttpStatus.BAD_REQUEST },
|
||||
{ class: EntityPropertyNotFoundError, status: HttpStatus.BAD_REQUEST },
|
||||
// nestjs默认的异常
|
||||
{ class: BadRequestException, status: HttpStatus.BAD_REQUEST },
|
||||
];
|
||||
|
||||
catch(exception: Error, host: ArgumentsHost) {
|
||||
const applicationRef =
|
||||
this.applicationRef ||
|
||||
(this.httpAdapterHost && this.httpAdapterHost.httpAdapter)!;
|
||||
// 是否在自定义的异常处理类列表中
|
||||
const resException = this.resExceptions.find(
|
||||
// exception 是异常的实例,item 是异常类
|
||||
(item) => exception instanceof item.class,
|
||||
);
|
||||
let res: string | object = "";
|
||||
let status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
if (exception instanceof HttpException) {
|
||||
res = exception.getResponse();
|
||||
status = exception.getStatus();
|
||||
} else if (resException) {
|
||||
// 如果在自定义异常处理类列表中
|
||||
res = exception.message;
|
||||
status = resException.status;
|
||||
}
|
||||
const message = isObject(res)
|
||||
? res
|
||||
: {
|
||||
statusCode: status,
|
||||
message: res,
|
||||
};
|
||||
applicationRef!.reply(host.getArgByIndex(1), message, status);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
declare type BaseType = string | number | boolean;
|
||||
declare type ParseType<T extends BaseType = string> = (value: string) => T;
|
|
@ -0,0 +1,23 @@
|
|||
import { ConfigService } from "@nestjs/config";
|
||||
import { NestFactory } from "@nestjs/core";
|
||||
import { useContainer } from "class-validator";
|
||||
import { WinstonModule } from "nest-winston";
|
||||
|
||||
import { AppModule } from "./app.module";
|
||||
import { findup } from "./modules/config/findup";
|
||||
import { instance } from "./until/winstonconfig";
|
||||
|
||||
const envFile = findup(".env");
|
||||
console.log(envFile);
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
logger: WinstonModule.createLogger({ instance }),
|
||||
});
|
||||
// 为class-validator添加容器以便在自定义约束中可以注入dataSource等依赖
|
||||
useContainer(app.select(AppModule), { fallbackOnErrors: true });
|
||||
const configService = app.get(ConfigService);
|
||||
const port = configService.get<number>("PORT", 4000);
|
||||
await app.listen(port);
|
||||
}
|
||||
bootstrap();
|
|
@ -0,0 +1 @@
|
|||
export class Configure {}
|
|
@ -0,0 +1,60 @@
|
|||
import { parse } from "dotenv";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { findup } from "./findup";
|
||||
|
||||
enum EnvironmentType {
|
||||
DEV = "dev",
|
||||
PROD = "prod",
|
||||
}
|
||||
export class Env {
|
||||
constructor() {
|
||||
this.load();
|
||||
}
|
||||
load() {
|
||||
if (process.env.NODE_ENV === undefined) {
|
||||
process.env.NODE_ENV = EnvironmentType.DEV;
|
||||
}
|
||||
let envFile = [findup(".env")];
|
||||
if (this.isDev()) {
|
||||
envFile.push(findup(`.env.${EnvironmentType.DEV}`));
|
||||
}
|
||||
if (this.isProd()) {
|
||||
envFile.push(findup(`.env.${EnvironmentType.PROD}`));
|
||||
}
|
||||
envFile = envFile.filter((v) => v !== undefined);
|
||||
// Load environment variables from.env files
|
||||
const fileEnvs = envFile
|
||||
.map((file) => {
|
||||
return file && parse(readFileSync(file));
|
||||
})
|
||||
.reduce((acc, cur) => ({ ...acc, ...cur }), {});
|
||||
// Merge environment variables from.env files and process.env
|
||||
const envs = { ...process.env, ...fileEnvs };
|
||||
|
||||
const envKeys = Object.keys(envs).filter((key) => !(key in process.env));
|
||||
// Set environment variables to process.env
|
||||
envKeys.forEach((key) => (process.env[key] = envs[key]));
|
||||
}
|
||||
run() {
|
||||
return process.env.NODE_ENV as EnvironmentType;
|
||||
}
|
||||
isDev() {
|
||||
return this.run() === EnvironmentType.DEV;
|
||||
}
|
||||
isProd() {
|
||||
return this.run() === EnvironmentType.PROD;
|
||||
}
|
||||
get(): Record<string, string>;
|
||||
get(key: string): string | undefined;
|
||||
get<T extends BaseType>(key: string, defaultValue: T): T;
|
||||
get<T extends BaseType>(key?: string, defaultValue?: T) {
|
||||
if (key === undefined) {
|
||||
return process.env as { [key: string]: string };
|
||||
}
|
||||
if (defaultValue !== undefined) {
|
||||
return defaultValue;
|
||||
}
|
||||
return process.env[key];
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
import { existsSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
|
||||
/**
|
||||
*
|
||||
* @param filename 要查找的文件名
|
||||
* @param cwd 起始目录,默认为当前工作目录
|
||||
*/
|
||||
export function findup(
|
||||
filename: string,
|
||||
cwd = process.cwd(),
|
||||
): string | undefined {
|
||||
const filepath = resolve(cwd);
|
||||
if (existsSync(join(filepath, filename))) {
|
||||
return join(filepath, filename);
|
||||
}
|
||||
const parentDir = dirname(filepath);
|
||||
if (parentDir === filepath) {
|
||||
// 达到根目录,停止递归
|
||||
return undefined;
|
||||
}
|
||||
return findup(filename, parentDir);
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
import type { DynamicModule, ModuleMetadata } from "@nestjs/common";
|
||||
import type { TypeOrmModuleOptions } from "@nestjs/typeorm";
|
||||
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
|
||||
import { UniqueConstraint } from "../user/constraints/unique.constraint";
|
||||
|
||||
@Global()
|
||||
@Module({})
|
||||
export class DatabaseModule {
|
||||
static forRoot(config: TypeOrmModuleOptions): DynamicModule {
|
||||
const providers: ModuleMetadata["providers"] = [UniqueConstraint];
|
||||
return {
|
||||
global: true,
|
||||
module: DatabaseModule,
|
||||
imports: [TypeOrmModule.forRoot(config)],
|
||||
providers,
|
||||
exports: providers,
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
import { JwtConfig, UserConfig } from "./types";
|
||||
|
||||
export const defaultUserConfig = (
|
||||
tokenConfig: JwtConfig = {
|
||||
token_expired: 60 * 60, // 1 hour
|
||||
refresh_token_expired: 60 * 60 * 24, // 24 hours
|
||||
},
|
||||
): UserConfig => ({
|
||||
hash: 10,
|
||||
jwt: {
|
||||
token_expired: tokenConfig.token_expired,
|
||||
refresh_token_expired: tokenConfig.refresh_token_expired,
|
||||
},
|
||||
});
|
|
@ -0,0 +1,4 @@
|
|||
export enum UserOrderType {
|
||||
CREATED = "createdAt",
|
||||
UPDATED = "updatedAt",
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
import { Injectable } from "@nestjs/common";
|
||||
import {
|
||||
registerDecorator,
|
||||
ValidationArguments,
|
||||
ValidationOptions,
|
||||
ValidatorConstraint,
|
||||
ValidatorConstraintInterface,
|
||||
} from "class-validator";
|
||||
import { isNil, merge } from "lodash";
|
||||
import { DataSource, ObjectType } from "typeorm";
|
||||
|
||||
interface Condition {
|
||||
entity: ObjectType<any>;
|
||||
/**
|
||||
* 如果没有指定字段则使用当前验证的属性作为查询依据
|
||||
*/
|
||||
property?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证某个字段的唯一性
|
||||
*/
|
||||
@ValidatorConstraint({ name: "dataUnique", async: true })
|
||||
@Injectable()
|
||||
export class UniqueConstraint implements ValidatorConstraintInterface {
|
||||
constructor(private dataSource: DataSource) {}
|
||||
|
||||
async validate(value: any, args: ValidationArguments) {
|
||||
// 获取要验证的模型和字段
|
||||
const config: Omit<Condition, "entity"> = {
|
||||
property: args.property,
|
||||
};
|
||||
const condition = ("entity" in args.constraints[0]
|
||||
? merge(config, args.constraints[0])
|
||||
: {
|
||||
...config,
|
||||
entity: args.constraints[0],
|
||||
}) as unknown as Required<Condition>;
|
||||
if (!condition.entity) return false;
|
||||
try {
|
||||
// 查询是否存在数据,如果已经存在则验证失败
|
||||
const repo = await this.dataSource
|
||||
.getRepository(condition.entity)
|
||||
.findOne({
|
||||
where: { [condition.property]: value },
|
||||
});
|
||||
|
||||
return isNil(repo);
|
||||
} catch (err) {
|
||||
// 如果数据库操作异常则验证失败
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
defaultMessage(args: ValidationArguments) {
|
||||
const { entity, property } = args.constraints[0];
|
||||
const queryProperty = property ?? args.property;
|
||||
if (!(args.object as any).getManager) {
|
||||
return "getManager function not been found!";
|
||||
}
|
||||
if (!entity) {
|
||||
return "Model not been specified!";
|
||||
}
|
||||
return `${queryProperty} of ${entity.name} must been unique!`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据唯一性验证
|
||||
* @param params Entity类或验证条件对象
|
||||
* @param validationOptions
|
||||
*/
|
||||
export function IsUnique(
|
||||
params: ObjectType<any> | Condition,
|
||||
validationOptions?: ValidationOptions,
|
||||
) {
|
||||
return (object: Record<string, any>, propertyName: string) => {
|
||||
registerDecorator({
|
||||
target: object.constructor,
|
||||
propertyName,
|
||||
options: validationOptions,
|
||||
constraints: [params],
|
||||
validator: UniqueConstraint,
|
||||
});
|
||||
};
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
import { Body, Controller, Get, Post, SerializeOptions } from "@nestjs/common";
|
||||
|
||||
import { CreateUserDto } from "../dtos/user.dto";
|
||||
import { UserEntity } from "../entities/user.entity";
|
||||
import { UserService } from "../services/user.service";
|
||||
|
||||
@Controller("users")
|
||||
export class UserController {
|
||||
constructor(private readonly service: UserService) {}
|
||||
@Get("/")
|
||||
async index() {
|
||||
return UserEntity.find();
|
||||
}
|
||||
@Post("/")
|
||||
@SerializeOptions({})
|
||||
async create(@Body() data: CreateUserDto) {
|
||||
return this.service.create(data);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
import { PickType } from "@nestjs/swagger";
|
||||
import { Length } from "class-validator";
|
||||
|
||||
import { UserCommonDto } from "./common.dto";
|
||||
|
||||
export class UpdateAccountDto extends PickType(UserCommonDto, [
|
||||
"username",
|
||||
"nickname",
|
||||
]) {}
|
||||
|
||||
/**
|
||||
* 更改用户密码
|
||||
*/
|
||||
|
||||
export class UpdatePasswordDto extends PickType(UserCommonDto, [
|
||||
"password",
|
||||
"plainPassword",
|
||||
]) {
|
||||
/**
|
||||
* 旧密码:用户在更改密码时需要输入的原密码
|
||||
*/
|
||||
|
||||
@Length(8, 50, {
|
||||
message: "密码长度不得少于$constraint1",
|
||||
always: true,
|
||||
})
|
||||
oldPassword: string;
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
import { PickType } from "@nestjs/swagger";
|
||||
|
||||
import { UserCommonDto } from "./common.dto";
|
||||
|
||||
/**
|
||||
* 用户正常方式登录
|
||||
*/
|
||||
export class CredentialDto extends PickType(UserCommonDto, [
|
||||
"credential",
|
||||
"password",
|
||||
]) {}
|
||||
|
||||
/**
|
||||
* 普通方式注册用户
|
||||
*/
|
||||
|
||||
export class RegisterDto extends PickType(UserCommonDto, [
|
||||
"username",
|
||||
"nickname",
|
||||
"password",
|
||||
"plainPassword",
|
||||
] as const) {}
|
|
@ -0,0 +1,75 @@
|
|||
import { Injectable } from "@nestjs/common";
|
||||
import { IsEmail, IsNotEmpty, IsOptional, Length } from "class-validator";
|
||||
|
||||
import { IsUnique } from "../constraints/unique.constraint";
|
||||
import { UserEntity } from "../entities/user.entity";
|
||||
|
||||
@Injectable()
|
||||
export class UserCommonDto {
|
||||
/**
|
||||
* 登录凭证:可以是用户名,手机号,邮箱地址
|
||||
*/
|
||||
@Length(4, 30, {
|
||||
message: "登录凭证长度必须为$constraint1到$constraint2",
|
||||
always: true,
|
||||
})
|
||||
@IsNotEmpty({ message: "登录凭证不得为空", always: true })
|
||||
credential: string;
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
|
||||
@Length(4, 30, {
|
||||
always: true,
|
||||
message: "用户名长度必须为$constraint1到$constraint2",
|
||||
})
|
||||
@IsUnique(UserEntity, { message: "用户名已被注册", always: true })
|
||||
username: string;
|
||||
|
||||
/**
|
||||
* 昵称:不设置则为用户名
|
||||
*/
|
||||
@Length(3, 20, {
|
||||
always: true,
|
||||
message: "昵称必须为$constraint1到$constraint2",
|
||||
})
|
||||
@IsOptional({ always: true })
|
||||
nickname?: string;
|
||||
|
||||
/**
|
||||
* 手机号:必须是区域开头的,比如+86.15005255555
|
||||
*/
|
||||
// @IsUnique(UserEntity, { message: "手机号已被注册", always: true })
|
||||
@Length(7, 20, {
|
||||
message: "手机号长度必须为$constraint1到$constraint2",
|
||||
always: true,
|
||||
})
|
||||
@IsNotEmpty({ message: "手机号不得为空", always: true })
|
||||
@IsUnique(UserEntity, { message: "手机号已被注册", always: true })
|
||||
phone: string;
|
||||
|
||||
/**
|
||||
* 邮箱地址:必须符合邮箱地址规则
|
||||
*/
|
||||
@IsEmail(undefined, { message: "邮箱格式不正确", always: true })
|
||||
@IsUnique(UserEntity, { message: "邮箱已被注册", always: true })
|
||||
email: string;
|
||||
|
||||
/**
|
||||
* 用户密码:密码必须由小写字母,大写字母,数字以及特殊字符组成
|
||||
*/
|
||||
|
||||
@Length(8, 50, {
|
||||
message: "密码长度不得少于$constraint1",
|
||||
always: true,
|
||||
})
|
||||
password: string;
|
||||
|
||||
/**
|
||||
* 确认密码:必须与用户密码输入相同的字符串
|
||||
*/
|
||||
|
||||
@IsNotEmpty({ message: "请再次输入密码以确认", always: true })
|
||||
plainPassword: string;
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
/**
|
||||
* 创建用的请求数据验证
|
||||
*/
|
||||
|
||||
import { PartialType, PickType } from "@nestjs/swagger";
|
||||
import { IsDefined, IsEnum } from "class-validator";
|
||||
|
||||
import { UserOrderType } from "../constants";
|
||||
import { UserCommonDto } from "./common.dto";
|
||||
|
||||
export class CreateUserDto extends PickType(UserCommonDto, [
|
||||
"username",
|
||||
"nickname",
|
||||
"password",
|
||||
"phone",
|
||||
"email",
|
||||
]) {}
|
||||
|
||||
/**
|
||||
* 更新用户
|
||||
*/
|
||||
|
||||
export class UpdateUserDto extends PartialType(CreateUserDto) {
|
||||
/**
|
||||
* 待更新的用户ID
|
||||
*/
|
||||
|
||||
@IsDefined({ groups: ["update"], message: "用户ID必须指定" })
|
||||
id: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询用户列表的Query数据验证
|
||||
*/
|
||||
|
||||
export class QueryUserDto {
|
||||
/**
|
||||
* 排序规则:可指定用户列表的排序规则,默认为按创建时间降序排序
|
||||
*/
|
||||
@IsEnum(UserOrderType)
|
||||
orderBy?: UserOrderType;
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
import type { Relation } from "typeorm";
|
||||
|
||||
import { Entity, ManyToOne, OneToOne } from "typeorm";
|
||||
|
||||
import { BaseToken } from "./base.token";
|
||||
import { RefreshTokenEntity } from "./refresh-token.entity";
|
||||
import { UserEntity } from "./user.entity";
|
||||
|
||||
@Entity("user_access_tokens")
|
||||
export class AccessTokenEntity extends BaseToken {
|
||||
/**
|
||||
* 关联的刷新令牌
|
||||
*/
|
||||
@OneToOne(
|
||||
() => RefreshTokenEntity,
|
||||
(refreshToken) => refreshToken.accessToken,
|
||||
{
|
||||
cascade: true,
|
||||
},
|
||||
)
|
||||
refreshToken: RefreshTokenEntity;
|
||||
@ManyToOne((_) => UserEntity, (user) => user.accessTokens, {
|
||||
onDelete: "CASCADE",
|
||||
})
|
||||
user: Relation<UserEntity>;
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
import { Exclude } from "class-transformer";
|
||||
import { BaseEntity, Column, CreateDateColumn, PrimaryColumn } from "typeorm";
|
||||
|
||||
@Exclude()
|
||||
export abstract class BaseToken extends BaseEntity {
|
||||
@PrimaryColumn({ type: "uuid", generated: "uuid" })
|
||||
id: string;
|
||||
|
||||
@Column({ length: 500, comment: "令牌字符串" })
|
||||
value: string;
|
||||
|
||||
@Column({
|
||||
comment: "令牌过期时间",
|
||||
})
|
||||
expired_at: Date;
|
||||
|
||||
@CreateDateColumn({
|
||||
comment: "令牌创建时间",
|
||||
})
|
||||
createdAt: Date;
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
import type { Relation } from "typeorm";
|
||||
|
||||
import { Entity, JoinColumn, OneToOne } from "typeorm";
|
||||
|
||||
import { AccessTokenEntity } from "./access-token.entity";
|
||||
import { BaseToken } from "./base.token";
|
||||
|
||||
@Entity("user_refresh_tokens")
|
||||
export class RefreshTokenEntity extends BaseToken {
|
||||
/**
|
||||
* 关联的登录令牌
|
||||
*/
|
||||
@OneToOne(
|
||||
(_) => AccessTokenEntity,
|
||||
(accessToken) => accessToken.refreshToken,
|
||||
{
|
||||
onDelete: "CASCADE",
|
||||
},
|
||||
)
|
||||
@JoinColumn()
|
||||
accessToken: Relation<AccessTokenEntity>;
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
import {
|
||||
BaseEntity,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
DeleteDateColumn,
|
||||
Entity,
|
||||
OneToMany,
|
||||
PrimaryColumn,
|
||||
UpdateDateColumn,
|
||||
} from "typeorm";
|
||||
|
||||
import { AccessTokenEntity } from "./access-token.entity";
|
||||
|
||||
@Entity("talkusers")
|
||||
export class UserEntity extends BaseEntity {
|
||||
@PrimaryColumn({ type: "uuid", generated: "uuid" })
|
||||
id: string;
|
||||
|
||||
@Column({
|
||||
comment: "姓名",
|
||||
nullable: true,
|
||||
})
|
||||
nickname?: string;
|
||||
|
||||
@Column({ comment: "用户名", unique: true })
|
||||
username: string;
|
||||
|
||||
@Column({ comment: "密码", length: 500, select: true })
|
||||
password: string;
|
||||
|
||||
@Column({ comment: "手机号", nullable: true, unique: true })
|
||||
phone?: string;
|
||||
|
||||
@Column({ comment: "邮箱", nullable: true, unique: true })
|
||||
email?: string;
|
||||
|
||||
@OneToMany((_) => AccessTokenEntity, (accessToken) => accessToken.user)
|
||||
accessTokens: AccessTokenEntity[];
|
||||
|
||||
@CreateDateColumn({
|
||||
comment: "用户创建时间",
|
||||
})
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({
|
||||
comment: "用户更新时间",
|
||||
})
|
||||
updatedAt: Date;
|
||||
|
||||
@DeleteDateColumn({
|
||||
comment: "删除时间",
|
||||
})
|
||||
deletedAt: Date;
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
import bcrypt from "bcrypt";
|
||||
|
||||
import { UserConfig } from "./types";
|
||||
/**
|
||||
* 加密明文密码
|
||||
* @param configure
|
||||
* @param password
|
||||
*/
|
||||
export const encrypt = async (config: UserConfig, password: string) => {
|
||||
const hash = config.hash;
|
||||
return bcrypt.hashSync(password, hash);
|
||||
};
|
||||
|
||||
/**
|
||||
* 验证密码
|
||||
* @param password
|
||||
* @param hashed
|
||||
*/
|
||||
export const decrypt = (password: string, hashed: string) => {
|
||||
return bcrypt.compareSync(password, hashed);
|
||||
};
|
|
@ -0,0 +1,70 @@
|
|||
import { Injectable } from "@nestjs/common";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import dayjs from "dayjs";
|
||||
import { v7 } from "uuid";
|
||||
|
||||
import { AccessTokenEntity } from "../entities/access-token.entity";
|
||||
import { RefreshTokenEntity } from "../entities/refresh-token.entity";
|
||||
import { UserEntity } from "../entities/user.entity";
|
||||
import { JwtConfig, JwtPayload } from "../types";
|
||||
|
||||
@Injectable()
|
||||
export class TokenService {
|
||||
private config: JwtConfig = {
|
||||
token_expired: 60,
|
||||
refresh_token_expired: 60 * 24 * 7,
|
||||
};
|
||||
private access_secret = "hTVLuGqhuKZW9HUnKzs83yvVBitlwc5d0PNfJqDRsRs=";
|
||||
constructor(protected jwtService: JwtService) {}
|
||||
|
||||
// Generate access token
|
||||
async generateToken(user: UserEntity, now: dayjs.Dayjs) {
|
||||
const accessTokenPayload: JwtPayload = {
|
||||
sub: user.id,
|
||||
iat: now.unix(),
|
||||
};
|
||||
|
||||
const signed = this.jwtService.sign(accessTokenPayload);
|
||||
const accessToken = new AccessTokenEntity();
|
||||
accessToken.value = signed;
|
||||
accessToken.user = user;
|
||||
accessToken.expired_at = now
|
||||
.add(this.config.token_expired, "second")
|
||||
.toDate();
|
||||
await accessToken.save();
|
||||
const refreshToken = await this.generateRefreshToken(accessToken, now);
|
||||
return { accessToken, refreshToken };
|
||||
}
|
||||
|
||||
async generateRefreshToken(accessToken: AccessTokenEntity, now: dayjs.Dayjs) {
|
||||
const refreshTokenPayload = {
|
||||
uuid: v7(),
|
||||
};
|
||||
const refreshToken = new RefreshTokenEntity();
|
||||
refreshToken.value = this.jwtService.sign(refreshTokenPayload, {
|
||||
secret: this.access_secret,
|
||||
});
|
||||
refreshToken.accessToken = accessToken;
|
||||
refreshToken.expired_at = now
|
||||
.add(this.config.refresh_token_expired, "second")
|
||||
.toDate();
|
||||
await refreshToken.save();
|
||||
return refreshToken;
|
||||
}
|
||||
async checkAccessToken(token: string) {
|
||||
return AccessTokenEntity.findOne({
|
||||
where: { value: token },
|
||||
relations: ["user", "refreshToken"],
|
||||
});
|
||||
}
|
||||
async rmAccessToken(token: string) {
|
||||
const accessToken = await AccessTokenEntity.findOne({
|
||||
where: { value: token },
|
||||
});
|
||||
accessToken && (await accessToken.remove());
|
||||
}
|
||||
async verifyAccessToken(token: string) {
|
||||
const user = await this.jwtService.verify(token, {});
|
||||
return user || false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
import type { Repository } from "typeorm";
|
||||
import type { SelectQueryBuilder } from "typeorm/query-builder/SelectQueryBuilder";
|
||||
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
|
||||
import type { CreateUserDto } from "../dtos/user.dto";
|
||||
|
||||
import { UserEntity } from "../entities/user.entity";
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
private qb: SelectQueryBuilder<UserEntity>;
|
||||
constructor(
|
||||
@InjectRepository(UserEntity)
|
||||
private usersRepository: Repository<UserEntity>,
|
||||
) {
|
||||
this.qb = this.usersRepository.createQueryBuilder("user");
|
||||
}
|
||||
|
||||
async create(data: CreateUserDto) {
|
||||
const user = await this.qb.insert().values(data).execute();
|
||||
return this.findById(user.identifiers[0].id);
|
||||
}
|
||||
async findByPhone(phone: string) {
|
||||
return await this.qb.where("user.phone = :phone", { phone }).getOne();
|
||||
}
|
||||
async findByUsername(username: string) {
|
||||
return await this.qb
|
||||
.where("user.username = :username", { username })
|
||||
.getOne();
|
||||
}
|
||||
async findByAll() {
|
||||
const users = await this.qb.getMany();
|
||||
console.log("users", users);
|
||||
|
||||
return users;
|
||||
}
|
||||
async findById(id: string) {
|
||||
return await this.qb.where("user.id = :id", { id }).getOne();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
import { randomBytes } from "node:crypto";
|
||||
import {
|
||||
DataSource,
|
||||
EntitySubscriberInterface,
|
||||
EventSubscriber,
|
||||
InsertEvent,
|
||||
} from "typeorm";
|
||||
|
||||
import { defaultUserConfig } from "../config";
|
||||
import { UserEntity } from "../entities/user.entity";
|
||||
import { encrypt } from "../helpers";
|
||||
|
||||
@EventSubscriber()
|
||||
export class UserSubscriber implements EntitySubscriberInterface<UserEntity> {
|
||||
protected entity = UserEntity;
|
||||
constructor(protected datasource: DataSource) {
|
||||
datasource.subscribers.push(this);
|
||||
}
|
||||
listenTo() {
|
||||
return this.entity;
|
||||
}
|
||||
protected async generateUserName(event: InsertEvent<UserEntity>) {
|
||||
const username = `user_${randomBytes(4).toString("hex").slice(0, 8)}`;
|
||||
const user = await this.datasource
|
||||
.getRepository(this.entity)
|
||||
.findOne({ where: { username } });
|
||||
return user ? this.generateUserName(event) : username;
|
||||
}
|
||||
async beforeInsert(event: InsertEvent<UserEntity>) {
|
||||
console.log(event.entity, "beforeInsert");
|
||||
|
||||
if (!event.entity.username) {
|
||||
event.entity.username = await this.generateUserName(event);
|
||||
}
|
||||
if (!event.entity.password) {
|
||||
event.entity.password = randomBytes(16).toString("hex").slice(0, 8);
|
||||
}
|
||||
event.entity.password = await encrypt(
|
||||
defaultUserConfig(),
|
||||
event.entity.password,
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
/**
|
||||
*@param hash: 对密码进行混淆时的hash数量值
|
||||
*@param jwt: jwt token的生成配置
|
||||
*/
|
||||
|
||||
export interface UserConfig {
|
||||
hash: number;
|
||||
jwt: JwtConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param token_expired: token过期时间,单位:秒
|
||||
* @param refresh_token_expired: refresh token过期时间,单位:秒
|
||||
*/
|
||||
|
||||
export interface JwtConfig {
|
||||
token_expired: number;
|
||||
refresh_token_expired: number;
|
||||
}
|
||||
/**
|
||||
* @param sub: 用户id
|
||||
* @param iat: 签出时间
|
||||
*/
|
||||
|
||||
export interface JwtPayload {
|
||||
sub: string;
|
||||
iat: number;
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
|
||||
import { UniqueConstraint } from "./constraints/unique.constraint";
|
||||
import { UserController } from "./controller/user.controller";
|
||||
import { UserEntity } from "./entities/user.entity";
|
||||
import { UserService } from "./services/user.service";
|
||||
import { UserSubscriber } from "./subscribers/user.subscriber";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([UserEntity])],
|
||||
providers: [UserSubscriber, UserService, UniqueConstraint],
|
||||
controllers: [UserController],
|
||||
exports: [],
|
||||
})
|
||||
export class UserModule {}
|
|
@ -0,0 +1,64 @@
|
|||
import { utilities as nestWinstonModuleUtilities } from "nest-winston";
|
||||
import * as winston from "winston";
|
||||
import "winston-daily-rotate-file";
|
||||
import { createLogger } from "winston";
|
||||
export const instance = createLogger({
|
||||
// options of Winston
|
||||
transports: [
|
||||
new winston.transports.Console({
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.ms(),
|
||||
nestWinstonModuleUtilities.format.nestLike("MyApp", {
|
||||
colors: true,
|
||||
prettyPrint: true,
|
||||
processId: true,
|
||||
appName: true,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
new winston.transports.DailyRotateFile({
|
||||
dirname: "logs",
|
||||
level: "info",
|
||||
filename: "info-%DATE%.log",
|
||||
datePattern: "YYYY-MM-DD-HH",
|
||||
zippedArchive: true,
|
||||
maxSize: "20m",
|
||||
maxFiles: "14d",
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.ms(),
|
||||
winston.format.simple(),
|
||||
),
|
||||
}),
|
||||
new winston.transports.DailyRotateFile({
|
||||
dirname: "logs",
|
||||
level: "warn",
|
||||
filename: "warn-%DATE%.log",
|
||||
datePattern: "YYYY-MM-DD-HH",
|
||||
zippedArchive: true,
|
||||
maxSize: "20m",
|
||||
maxFiles: "14d",
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.ms(),
|
||||
winston.format.simple(),
|
||||
),
|
||||
}),
|
||||
new winston.transports.DailyRotateFile({
|
||||
dirname: "logs",
|
||||
level: "error",
|
||||
filename: "error-%DATE%.log",
|
||||
datePattern: "YYYY-MM-DD-HH",
|
||||
zippedArchive: true,
|
||||
maxSize: "20m",
|
||||
maxFiles: "14d",
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.ms(),
|
||||
winston.format.simple(),
|
||||
),
|
||||
}),
|
||||
// other transports...
|
||||
],
|
||||
});
|
|
@ -0,0 +1,28 @@
|
|||
import type { INestApplication } from "@nestjs/common";
|
||||
import type { TestingModule } from "@nestjs/testing";
|
||||
import type { App } from "supertest/types";
|
||||
|
||||
import { Test } from "@nestjs/testing";
|
||||
import * as request from "supertest";
|
||||
|
||||
import { AppModule } from "./../src/app.module";
|
||||
|
||||
describe("AppController (e2e)", () => {
|
||||
let app: INestApplication<App>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
|
||||
it("/ (GET)", () => {
|
||||
return request(app.getHttpServer())
|
||||
.get("/")
|
||||
.expect(200)
|
||||
.expect("Hello World!");
|
||||
});
|
||||
});
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"incremental": true,
|
||||
"target": "ES2023",
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"baseUrl": "./",
|
||||
"module": "commonjs",
|
||||
"strictBindCallApply": false,
|
||||
"strictNullChecks": true,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
"noImplicitAny": false,
|
||||
"declaration": true,
|
||||
"outDir": "./dist",
|
||||
"removeComments": true,
|
||||
"sourceMap": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"skipLibCheck": true
|
||||
}
|
||||
}
|
|
@ -54,7 +54,7 @@
|
|||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "1.0.4",
|
||||
"cookie": "^1.0.2",
|
||||
"cookie": "1.0.2",
|
||||
"cookies-next": "^5.1.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
|
@ -65,7 +65,7 @@
|
|||
"md-editor-rt": "^5.5.0",
|
||||
"micromatch": "^4.0.8",
|
||||
"motion": "^12.9.4",
|
||||
"next": "15.1.3",
|
||||
"next": "15.3.2",
|
||||
"next-mdx-remote-client": "^2.1.2",
|
||||
"next-themes": "^0.4.6",
|
||||
"pinyin": "4.0.0-alpha.2",
|
||||
|
@ -96,12 +96,13 @@
|
|||
"unist-util-visit": "^5.0.0",
|
||||
"vaul": "^1.1.2",
|
||||
"vfile": "^6.0.3",
|
||||
"zod": "^3.24.2",
|
||||
"zustand": "5.0.3"
|
||||
"zod": "catalog:",
|
||||
"zustand": "5.0.3",
|
||||
"lodash":"catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jsonwebtoken": "^9.0.9",
|
||||
"@types/lodash": "^4.17.16",
|
||||
"@types/lodash": "catalog:",
|
||||
"@types/mdx": "^2.0.13",
|
||||
"@types/micromatch": "^4.0.9",
|
||||
"@types/node": "^20.17.32",
|
||||
|
@ -119,7 +120,7 @@
|
|||
"postcss-nesting": "^12.1.5",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.8.3",
|
||||
"typescript": "5.8.3",
|
||||
"utility-types": "^3.11.0"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
"use client";
|
||||
import type { AuthLoginRequest } from "@repo/api";
|
||||
import type { AuthLoginRequest } from "@repo/api/types";
|
||||
|
||||
import { setAccessToken } from "@/lib/token";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
|
|
@ -137,9 +137,10 @@ export function HeaderNav() {
|
|||
</NavigationMenuContent>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<Link href="/docs" legacyBehavior passHref>
|
||||
<NavigationMenuLink>Documentation</NavigationMenuLink>
|
||||
</Link>
|
||||
<NavigationMenuLink href="/docs" >
|
||||
Documentation
|
||||
</NavigationMenuLink>
|
||||
|
||||
</NavigationMenuItem>
|
||||
</NavigationMenuList>
|
||||
</NavigationMenu>
|
||||
|
|
|
@ -70,6 +70,7 @@ const config = antfu(
|
|||
],
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
plugins: {
|
||||
"unused-imports": unusedImports,
|
||||
|
|
|
@ -0,0 +1,97 @@
|
|||
import antfu from "@antfu/eslint-config";
|
||||
import eslintConfigPrettier from "eslint-config-prettier";
|
||||
import perfectionist from "eslint-plugin-perfectionist";
|
||||
import eslintPluginPrettierRecommended from "eslint-plugin-prettier/recommended";
|
||||
import unusedImports from "eslint-plugin-unused-imports";
|
||||
|
||||
const config = antfu(
|
||||
{
|
||||
isInEditor: true,
|
||||
|
||||
typescript: true,
|
||||
stylistic: false,
|
||||
markdown: false,
|
||||
toml: false,
|
||||
ignores: [
|
||||
"public",
|
||||
"node_modules",
|
||||
"build",
|
||||
".history",
|
||||
".next",
|
||||
"public",
|
||||
"pnpm-lock.yaml",
|
||||
"package-lock.json",
|
||||
"next-env.d.ts",
|
||||
],
|
||||
},
|
||||
{
|
||||
files: ["**/*.{ts,tsx,js,jsx}"],
|
||||
languageOptions: {
|
||||
ecmaVersion: "latest",
|
||||
},
|
||||
rules: {
|
||||
// 在nestjs中,需要关闭consistent-type-imports,否则注入的依赖不是类而是类型,
|
||||
"@typescript-eslint/consistent-type-imports": "off",
|
||||
"no-console": "off",
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"ts/no-use-before-define": "off",
|
||||
"ts/strict-boolean-expressions": "off",
|
||||
"ts/no-unsafe-member-access": "off",
|
||||
"ts/no-unsafe-call": "off",
|
||||
"ts/no-unsafe-assignment": "off",
|
||||
"ts/no-unsafe-return": "off",
|
||||
"ts/no-unsafe-argument": "off",
|
||||
"ts/no-misused-promises": "off",
|
||||
"ts/no-floating-promises": "off",
|
||||
"node/prefer-global/process": "off",
|
||||
"node/prefer-global/buffer": "off",
|
||||
"import/no-named-default": "off",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "perfectionist",
|
||||
rules: {
|
||||
"import/order": "off",
|
||||
"sort-imports": "off",
|
||||
"perfectionist/sort-imports":
|
||||
perfectionist.configs["recommended-natural"].rules[
|
||||
"perfectionist/sort-imports"
|
||||
],
|
||||
"perfectionist/sort-exports":
|
||||
perfectionist.configs["recommended-natural"].rules[
|
||||
"perfectionist/sort-exports"
|
||||
],
|
||||
"perfectionist/sort-named-imports":
|
||||
perfectionist.configs["recommended-natural"].rules[
|
||||
"perfectionist/sort-named-imports"
|
||||
],
|
||||
"perfectionist/sort-named-exports":
|
||||
perfectionist.configs["recommended-natural"].rules[
|
||||
"perfectionist/sort-named-exports"
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
plugins: {
|
||||
"unused-imports": unusedImports,
|
||||
},
|
||||
rules: {
|
||||
"unused-imports/no-unused-imports": "error",
|
||||
"unused-imports/no-unused-vars": [
|
||||
"warn",
|
||||
{
|
||||
vars: "all",
|
||||
varsIgnorePattern: "^_",
|
||||
args: "after-used",
|
||||
argsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
eslintConfigPrettier,
|
||||
eslintPluginPrettierRecommended,
|
||||
);
|
||||
export default config;
|
|
@ -6,14 +6,17 @@
|
|||
"exports": {
|
||||
"./base": "./base.mjs",
|
||||
"./next-js": "./next.mjs",
|
||||
"./nest-js": "./nest.mjs",
|
||||
"./react-internal": "./react-internal.mjs"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^4.11.0",
|
||||
"@eslint/js": "^9.23.0",
|
||||
"@next/eslint-plugin-next": "^15.2.2",
|
||||
"eslint": "^9.23.0",
|
||||
"eslint-config-prettier": "^10.1.1",
|
||||
"eslint-plugin-import": "^2.31.0",
|
||||
"eslint-plugin-jsx-a11y": "^6.10.2",
|
||||
"eslint-plugin-only-warn": "^1.1.0",
|
||||
"eslint-plugin-perfectionist": "^4.7.0",
|
||||
|
|
|
@ -22,46 +22,46 @@
|
|||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.0.1",
|
||||
"@radix-ui/react-accordion": "^1.2.2",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.4",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.1",
|
||||
"@radix-ui/react-avatar": "^1.1.2",
|
||||
"@radix-ui/react-checkbox": "^1.1.3",
|
||||
"@radix-ui/react-collapsible": "^1.1.2",
|
||||
"@radix-ui/react-context-menu": "^2.2.4",
|
||||
"@radix-ui/react-dialog": "^1.1.4",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.4",
|
||||
"@radix-ui/react-hover-card": "^1.1.4",
|
||||
"@radix-ui/react-accordion": "^1.2.10",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.13",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.6",
|
||||
"@radix-ui/react-avatar": "^1.1.9",
|
||||
"@radix-ui/react-checkbox": "^1.3.1",
|
||||
"@radix-ui/react-collapsible": "^1.1.10",
|
||||
"@radix-ui/react-context-menu": "^2.2.14",
|
||||
"@radix-ui/react-dialog": "^1.1.13",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.14",
|
||||
"@radix-ui/react-hover-card": "^1.1.13",
|
||||
"@radix-ui/react-icons": "^1.3.2",
|
||||
"@radix-ui/react-label": "^2.1.2",
|
||||
"@radix-ui/react-menubar": "^1.1.4",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.3",
|
||||
"@radix-ui/react-popover": "^1.1.4",
|
||||
"@radix-ui/react-progress": "^1.1.1",
|
||||
"@radix-ui/react-radio-group": "^1.2.2",
|
||||
"@radix-ui/react-scroll-area": "^1.2.2",
|
||||
"@radix-ui/react-select": "^2.1.4",
|
||||
"@radix-ui/react-separator": "^1.1.1",
|
||||
"@radix-ui/react-slider": "^1.2.2",
|
||||
"@radix-ui/react-slot": "^1.2.0",
|
||||
"@radix-ui/react-switch": "^1.1.2",
|
||||
"@radix-ui/react-tabs": "^1.1.2",
|
||||
"@radix-ui/react-toggle": "^1.1.1",
|
||||
"@radix-ui/react-toggle-group": "^1.1.1",
|
||||
"@radix-ui/react-tooltip": "^1.1.6",
|
||||
"@radix-ui/react-label": "^2.1.6",
|
||||
"@radix-ui/react-menubar": "^1.1.14",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.12",
|
||||
"@radix-ui/react-popover": "^1.1.13",
|
||||
"@radix-ui/react-progress": "^1.1.6",
|
||||
"@radix-ui/react-radio-group": "^1.3.6",
|
||||
"@radix-ui/react-scroll-area": "^1.2.8",
|
||||
"@radix-ui/react-select": "^2.2.4",
|
||||
"@radix-ui/react-separator": "^1.1.6",
|
||||
"@radix-ui/react-slider": "^1.3.4",
|
||||
"@radix-ui/react-slot": "^1.2.2",
|
||||
"@radix-ui/react-switch": "^1.2.4",
|
||||
"@radix-ui/react-tabs": "^1.1.11",
|
||||
"@radix-ui/react-toggle": "^1.1.8",
|
||||
"@radix-ui/react-toggle-group": "^1.1.9",
|
||||
"@radix-ui/react-tooltip": "^1.2.6",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "1.0.4",
|
||||
"date-fns": "^4.1.0",
|
||||
"embla-carousel-react": "^8.5.2",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"input-otp": "^1.4.2",
|
||||
"lucide-react": "^0.441.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"radix-ui": "^1.3.4",
|
||||
"radix-ui": "^1.4.1",
|
||||
"react-day-picker": "9.6.7",
|
||||
"react-hook-form": "^7.56.2",
|
||||
"react-resizable-panels": "^2.1.7",
|
||||
"recharts": "^2.15.0",
|
||||
"react-hook-form": "^7.56.3",
|
||||
"react-resizable-panels": "^2.1.9",
|
||||
"recharts": "^2.15.3",
|
||||
"sonner": "^2.0.3",
|
||||
"tailwind-merge": "^3.2.0",
|
||||
"vaul": "^1.1.2"
|
||||
|
@ -70,9 +70,9 @@
|
|||
"@repo/eslint-config": "workspace:*",
|
||||
"@repo/tailwind-config": "workspace:*",
|
||||
"@repo/typescript-config": "workspace:*",
|
||||
"@types/react": "19",
|
||||
"react": "19",
|
||||
"typescript": " 5.8.3",
|
||||
"@types/react": "^19.1.3",
|
||||
"react": "^19.1.0",
|
||||
"typescript": "5.8.3",
|
||||
"zod": "3.24.3"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
"exports": {
|
||||
"import": {
|
||||
"types": "./dist/es/index.d.ts",
|
||||
"default": "./dist/es/index.js"
|
||||
"default": "./dist/es/index.mjs"
|
||||
}
|
||||
},
|
||||
"main": "./dist/cjs/index.js",
|
||||
|
@ -20,7 +20,6 @@
|
|||
"lint": "eslint . --ext ts,tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/lodash": "catalog:",
|
||||
"dayjs": "^1.11.13",
|
||||
"deepmerge": "^4.3.1",
|
||||
"lodash": "catalog:"
|
||||
|
@ -28,6 +27,7 @@
|
|||
"devDependencies": {
|
||||
"@repo/eslint-config": "workspace:*",
|
||||
"@repo/typescript-config": "workspace:*",
|
||||
"@types/lodash": "catalog:",
|
||||
"@types/node": "^22.8.6",
|
||||
"bunchee": "^5.6.1",
|
||||
"typescript": "^5.6.3"
|
||||
|
|
5986
pnpm-lock.yaml
5986
pnpm-lock.yaml
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue