feat: redis conf

This commit is contained in:
mozzie 2023-02-16 17:58:27 +08:00
parent b8f6732327
commit 46602eda09
165 changed files with 10966 additions and 5346 deletions

11
apps/server/.editorconfig Normal file
View File

@ -0,0 +1,11 @@
# 🎨 editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true

View File

@ -0,0 +1,2 @@
# 代码中使用 process.env.OSS_SECRET
OSS_SECRET=12345

View File

@ -0,0 +1,7 @@
{
"extends": "./node_modules/mwts/",
"ignorePatterns": ["node_modules", "dist", "test", "jest.config.js", "typings"],
"env": {
"jest": true
}
}

View File

@ -1,35 +1,15 @@
# compiled output logs/
/dist npm-debug.log
/node_modules yarn-error.log
node_modules/
# Logs package-lock.json
logs yarn.lock
*.log coverage/
npm-debug.log* dist/
pnpm-debug.log* .idea/
yarn-debug.log* run/
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store .DS_Store
*.sw*
# Tests *.un~
/coverage .tsbuildinfo
/.nyc_output .tsbuildinfo.*
# 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

View File

@ -0,0 +1,3 @@
module.exports = {
...require('mwts/.prettierrc.json')
}

2
apps/server/bootstrap.js vendored Normal file
View File

@ -0,0 +1,2 @@
const { Bootstrap } = require('@midwayjs/bootstrap');
Bootstrap.run();

View File

@ -1,77 +1,57 @@
{ {
"name": "@backset/server", "name": "@backset/server",
"version": "0.0.1", "version": "1.0.0",
"private": true, "private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"dev:be": "cross-env RUNNING_ENV=dev nest start --watch",
"prod:be": "cross-env RUNNING_ENV=prod node dist/main",
"dev:fe": "cross-env RUNNING_ENV=dev webpack -w",
"build:fe": "cross-env RUNNING_ENV=prod webpack build",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"new:page": "node ./script/new.page.js",
"new:mvc": "node ./script/new.mvc.js"
},
"dependencies": { "dependencies": {
"@backset/ui": "workspace:^1.0.0", "@midwayjs/bootstrap": "^3.0.0",
"@backset/util": "workspace:^1.0.0", "@midwayjs/core": "^3.0.0",
"@nestjs-modules/ioredis": "1.0.1", "@midwayjs/decorator": "^3.0.0",
"@nestjs/common": "^9.0.0", "@midwayjs/info": "^3.0.0",
"@nestjs/config": "2.3.1", "@midwayjs/koa": "^3.0.0",
"@nestjs/core": "^9.0.0", "@midwayjs/logger": "^2.14.0",
"@nestjs/mongoose": "7.2.4", "@midwayjs/validate": "^3.0.0",
"@nestjs/platform-express": "^9.0.0", "@midwayjs/view-ejs": "^3.0.0",
"axios": "0.27.2", "@midwayjs/static-file": "^3.0.0",
"cookie": "0.5.0", "@midwayjs/redis": "^3.0.0",
"ioredis": "5.3.1", "@midwayjs/typeorm": "^3.0.0",
"jsonwebtoken": "9.0.0", "mongoose": "^6.0.7",
"mongoose": "5.13.15", "@midwayjs/typegoose": "3.0.0",
"@typegoose/typegoose": "10.1.1",
"typeorm": "~0.3.0",
"mysql2": "3.0.1", "mysql2": "3.0.1",
"reflect-metadata": "^0.1.13", "dotenv": "16.0.3"
"rxjs": "^7.2.0",
"typeorm": "0.3.11"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "7.20.12", "@midwayjs/cli": "^2.0.0",
"@babel/preset-env": "7.20.2", "@midwayjs/mock": "^3.0.0",
"@nestjs/cli": "^9.0.0", "@types/koa": "^2.13.4",
"@nestjs/schematics": "^9.0.0", "@types/node": "14",
"@nestjs/typeorm": "9.0.1", "cross-env": "^6.0.0",
"@types/express": "^4.17.13", "jest": "^29.2.2",
"@types/mongoose": "^5.11.97", "mwts": "^1.0.5",
"@types/node": "18.11.18", "typescript": "~4.8.0",
"@typescript-eslint/eslint-plugin": "^5.0.0", "@types/mongoose": "^5.11.97"
"@typescript-eslint/parser": "^5.0.0", },
"babel-loader": "8.1.0", "engines": {
"buffer": "^6.0.3", "node": ">=12.0.0"
"cash-dom": "8.1.3", },
"chalk": "4.1.2", "scripts": {
"copy-webpack-plugin": "5.1.2", "start": "NODE_ENV=production node ./bootstrap.js",
"cross-env": "7.0.3", "dev:be": "cross-env NODE_ENV=local midway-bin dev --ts",
"crypto-browserify": "^3.12.0", "cov": "midway-bin cov --ts",
"stream-browserify": "3.0.0", "lint": "mwts check",
"css-loader": "6.7.3", "lint:fix": "mwts fix",
"ejs": "3.1.8", "ci": "npm run cov",
"eslint": "^8.0.1", "build": "midway-bin build -c"
"eslint-config-prettier": "^8.3.0", },
"eslint-plugin-prettier": "^4.0.0", "midway-bin-clean": [
"inquirer": "8.0.0", ".vscode/.tsbuildinfo",
"less": "3.8.0", "dist"
"less-loader": "4.1.0", ],
"mini-css-extract-plugin": "2.7.2", "repository": {
"prettier": "^2.3.2", "type": "git",
"process": "^0.11.10", "url": ""
"source-map-support": "^0.5.20", },
"ts-loader": "9.4.2", "author": "anonymous",
"ts-node": "^10.0.0", "license": "MIT"
"tsconfig-paths": "4.1.1",
"typescript": "^4.7.4",
"url-loader": "4.1.1",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"assert": "2.0.0"
}
} }

View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
404
</body>
</html>

View File

@ -0,0 +1,16 @@
import { MidwayAppInfo, MidwayConfig } from '@midwayjs/core';
export default (appInfo: MidwayAppInfo): MidwayConfig => {
return {
keys: '1676532942172_2248',
koa: {
port: 7001,
},
// ...
view: {
mapping: {
'.ejs': 'ejs',
},
},
};
};

View File

@ -0,0 +1,47 @@
import { MidwayAppInfo, MidwayConfig } from '@midwayjs/core';
export default (appInfo: MidwayAppInfo): MidwayConfig => {
return {
typeorm: {
dataSource: {
default: {
/**
*
*/
type: 'mysql',
host: 'mozzie.cn',
port: 6033,
username: 'root',
password: 'cr654654.',
database: 'backset',
synchronize: true, // 如果第一次使用,不存在表,有同步的需求可以写 true注意会丢数据
logging: false,
// 扫描形式, 配置实体模型 entities: [Photo]
entities: ['**/entity/*.entity{.ts,.js}'],
},
},
},
redis: {
client: {
port: 16379, // Redis port
host: 'mozzie.cn', // Redis host
password: 'cr654654.',
db: 0,
},
},
mongoose: {
dataSource: {
default: {
uri: 'mongodb://mozzie.cn:27017/backset',
options: {
useNewUrlParser: true,
useUnifiedTopology: true,
user: 'backset',
pass: 'cr654654.',
},
},
},
},
} as MidwayConfig;
};

View File

@ -0,0 +1,45 @@
import { Configuration, App } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import * as validate from '@midwayjs/validate';
import * as info from '@midwayjs/info';
import * as view from '@midwayjs/view-ejs';
import * as staticFile from '@midwayjs/static-file';
import * as orm from '@midwayjs/typeorm';
import * as dotenv from 'dotenv';
import * as redis from '@midwayjs/redis';
import * as typegoose from '@midwayjs/typegoose';
import { join } from 'path';
// import { DefaultErrorFilter } from './filter/default.filter';
// import { NotFoundFilter } from './filter/notfound.filter';
import { ReportMiddleware } from './middleware/report.middleware';
import { LocalMiddleware } from './middleware/local.middleware';
dotenv.config();
@Configuration({
imports: [
koa,
validate,
staticFile,
view,
orm,
redis,
typegoose,
{
component: info,
enabledEnvironment: ['local'],
},
],
importConfigs: [join(__dirname, './config')],
})
export class ContainerLifeCycle {
@App()
app: koa.Application;
async onReady() {
// add middleware
this.app.useMiddleware([ReportMiddleware, LocalMiddleware]);
// add filter
// this.app.useFilter([NotFoundFilter, DefaultErrorFilter]);
}
}

View File

@ -0,0 +1,18 @@
import { Inject, Controller, Post, Body } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { Validate } from '@midwayjs/validate';
import { UserDTO } from '../dto/user.dto';
@Controller('/api')
export class APIController {
@Inject()
ctx: Context;
@Post('/get_user')
@Validate({
errorStatus: 422,
})
async getUser(@Body() user: UserDTO) {
return { success: true, message: 'OK', data: user };
}
}

View File

@ -0,0 +1,40 @@
import { Controller, Get, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Context } from '@midwayjs/koa';
import { Photo } from '../entity/photo.entity';
import { Repository } from 'typeorm';
@Controller('/')
export class HomeController {
@Inject()
ctx: Context;
@InjectEntityModel(Photo)
photoModel: Repository<Photo>;
@Get('/')
async home() {
await this.ctx.render('hello.ejs', {
data: 'world',
});
}
@Get('/testMysql')
async testMysql() {
// create a entity object
let photo = new Photo();
photo.name = 'Me and Bears';
photo.description = 'I am near polar bears';
photo.filename = 'photo-with-bears.jpg';
photo.views = 1;
photo.isPublished = true;
// save entity
const photoResult = await this.photoModel.save(photo);
// save success
console.log('photo id = ', photoResult.id);
this.ctx.body = photoResult.id;
}
}

View File

@ -1,12 +1,16 @@
export interface IUserRequest { // src/dto/user.ts
user_login: string; import { Rule, RuleType } from '@midwayjs/validate';
user_pass: string;
user_phone: number | string;
}
export interface IUserLoginRequest { export class UserDTO {
login_type: 'password' | 'verifycode'; @Rule(RuleType.number().required())
user_login: string | number; id: number;
user_pass?: string;
verify_code?: string | number; @Rule(RuleType.string().required())
firstName: string;
@Rule(RuleType.string().max(10))
lastName: string;
@Rule(RuleType.number().max(60))
age: number;
} }

View File

@ -0,0 +1,25 @@
// entity/photo.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity('photo')
export class Photo {
@PrimaryGeneratedColumn()
id: number;
@Column({
length: 100,
})
name: string;
@Column('text')
description: string;
@Column()
filename: string;
@Column('double')
views: number;
@Column()
isPublished: boolean;
}

View File

@ -1,10 +1,3 @@
export interface IUser { export class User{
id?: number;
user_login?: string;
user_pass?: string;
user_phone?: string;
user_email?: string;
user_create_time?: number;
user_status?: number;
display_name?: string;
} }

View File

@ -0,0 +1,13 @@
import { Catch } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
@Catch()
export class DefaultErrorFilter {
async catch(err: Error, ctx: Context) {
// 所有的未分类错误会到这里
return {
success: false,
message: err.message,
};
}
}

View File

@ -0,0 +1,11 @@
import { Catch, httpError, MidwayHttpError } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
@Catch(httpError.NotFoundError)
export class NotFoundFilter {
async catch(err: MidwayHttpError, ctx: Context) {
// 404 错误会到这里
// ctx.redirect('/404.html');
ctx.body = '迷路了'
}
}

View File

@ -0,0 +1,6 @@
/**
* @description User-Service parameters
*/
export interface IUserOptions {
uid: number;
}

View File

@ -0,0 +1,21 @@
import { Middleware, IMiddleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
const locals = {
a: 1,
b: 2,
};
@Middleware()
export class LocalMiddleware implements IMiddleware<Context, NextFunction> {
resolve() {
return async (ctx: Context, next: NextFunction) => {
ctx.locals = locals;
await next();
};
}
static getName(): string {
return 'local';
}
}

View File

@ -0,0 +1,27 @@
import { Middleware, IMiddleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
@Middleware()
export class ReportMiddleware implements IMiddleware<Context, NextFunction> {
resolve() {
return async (ctx: Context, next: NextFunction) => {
// 控制器前执行的逻辑
const startTime = Date.now();
// 执行下一个 Web 中间件,最后执行到控制器
// 这里可以拿到下一个中间件或者控制器的返回值
const result = await next();
// 控制器之后执行的逻辑
ctx.logger.info(
`Report in "src/middleware/report.middleware.ts", rt = ${
Date.now() - startTime
}ms`
);
// 返回给上一个中间件的结果
return result;
};
}
static getName(): string {
return 'report';
}
}

View File

@ -1,23 +1,14 @@
import { EncryptUtil } from '@backset/util'; import { Provide } from '@midwayjs/core';
import { Injectable } from '@nestjs/common'; import { IUserOptions } from '../interface';
import { InjectDataSource } from '@nestjs/typeorm';
import { IUserLoginRequest, IUserRequest } from 'src/dto/user.dto';
import { IUser } from 'src/entity/user.entity';
import { DataSource } from 'typeorm';
import { UserServiceImpl } from './impl/user.interface';
@Injectable() @Provide()
export class UserService implements UserServiceImpl { export class UserService {
constructor(@InjectDataSource() private db: DataSource) {} async getUser(options: IUserOptions) {
return {
async createUser(p: IUserRequest): Promise<boolean> { uid: options.uid,
const create_sql = `INSERT INTO backset.user(user_login,user_pass,user_phone,user_create_time) VALUES(?,?,?,?)`; username: 'mockedName',
const { affectedRows } = await this.db.query(create_sql, [ phone: '12345678901',
p.user_login, email: 'xxx.xxx@xxx.com',
EncryptUtil.md5(p.user_pass), };
p.user_phone,
Date.now(),
]);
return affectedRows === 1;
} }
} }

View File

@ -1,22 +1,25 @@
{ {
"compileOnSave": true,
"compilerOptions": { "compilerOptions": {
"target": "es2018",
"module": "commonjs", "module": "commonjs",
"declaration": true, "moduleResolution": "node",
"removeComments": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"allowSyntheticDefaultImports": true, "emitDecoratorMetadata": true,
"target": "es2017", "inlineSourceMap":true,
"sourceMap": true, "noImplicitThis": true,
"outDir": "./dist", "noUnusedLocals": true,
"baseUrl": "./", "stripInternal": true,
"incremental": true,
"skipLibCheck": true, "skipLibCheck": true,
"strictNullChecks": false, "pretty": true,
"noImplicitAny": false, "declaration": true,
"strictBindCallApply": false, "forceConsistentCasingInFileNames": true,
"forceConsistentCasingInFileNames": false, "typeRoots": [ "./typings", "./node_modules/@types"],
"noFallthroughCasesInSwitch": false "outDir": "dist"
} },
"exclude": [
"dist",
"node_modules",
"test"
]
} }

View File

@ -0,0 +1,5 @@
hello <%= data %>
<!-- 全局变量 -->
<%= locals.a %>
<%= locals.b %>

0
apps/server2/.env Normal file
View File

35
apps/server2/.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# compiled output
/dist
/node_modules
# 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

77
apps/server2/package.json Normal file
View File

@ -0,0 +1,77 @@
{
"name": "@backset/server",
"version": "0.0.1",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"dev:be": "cross-env RUNNING_ENV=dev nest start --watch",
"prod:be": "cross-env RUNNING_ENV=prod node dist/main",
"dev:fe": "cross-env RUNNING_ENV=dev webpack -w",
"build:fe": "cross-env RUNNING_ENV=prod webpack build",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"new:page": "node ./script/new.page.js",
"new:mvc": "node ./script/new.mvc.js"
},
"dependencies": {
"@backset/ui": "workspace:^1.0.0",
"@backset/util": "workspace:^1.0.0",
"@nestjs-modules/ioredis": "1.0.1",
"@nestjs/common": "^9.0.0",
"@nestjs/config": "2.3.1",
"@nestjs/core": "^9.0.0",
"@nestjs/mongoose": "7.2.4",
"@nestjs/platform-express": "^9.0.0",
"axios": "0.27.2",
"cookie": "0.5.0",
"ioredis": "5.3.1",
"jsonwebtoken": "9.0.0",
"mongoose": "5.13.15",
"mysql2": "3.0.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0",
"typeorm": "0.3.11"
},
"devDependencies": {
"@babel/core": "7.20.12",
"@babel/preset-env": "7.20.2",
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/typeorm": "9.0.1",
"@types/express": "^4.17.13",
"@types/mongoose": "^5.11.97",
"@types/node": "18.11.18",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"babel-loader": "8.1.0",
"buffer": "^6.0.3",
"cash-dom": "8.1.3",
"chalk": "4.1.2",
"copy-webpack-plugin": "5.1.2",
"cross-env": "7.0.3",
"crypto-browserify": "^3.12.0",
"stream-browserify": "3.0.0",
"css-loader": "6.7.3",
"ejs": "3.1.8",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"inquirer": "8.0.0",
"less": "3.8.0",
"less-loader": "4.1.0",
"mini-css-extract-plugin": "2.7.2",
"prettier": "^2.3.2",
"process": "^0.11.10",
"source-map-support": "^0.5.20",
"ts-loader": "9.4.2",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.1",
"typescript": "^4.7.4",
"url-loader": "4.1.1",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"assert": "2.0.0"
}
}

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

View File

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

View File

@ -0,0 +1,12 @@
export interface IUserRequest {
user_login: string;
user_pass: string;
user_phone: number | string;
}
export interface IUserLoginRequest {
login_type: 'password' | 'verifycode';
user_login: string | number;
user_pass?: string;
verify_code?: string | number;
}

View File

@ -0,0 +1,10 @@
export interface IUser {
id?: number;
user_login?: string;
user_pass?: string;
user_phone?: string;
user_email?: string;
user_create_time?: number;
user_status?: number;
display_name?: string;
}

View File

@ -0,0 +1,23 @@
import { EncryptUtil } from '@backset/util';
import { Injectable } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { IUserLoginRequest, IUserRequest } from 'src/dto/user.dto';
import { IUser } from 'src/entity/user.entity';
import { DataSource } from 'typeorm';
import { UserServiceImpl } from './impl/user.interface';
@Injectable()
export class UserService implements UserServiceImpl {
constructor(@InjectDataSource() private db: DataSource) {}
async createUser(p: IUserRequest): Promise<boolean> {
const create_sql = `INSERT INTO backset.user(user_login,user_pass,user_phone,user_create_time) VALUES(?,?,?,?)`;
const { affectedRows } = await this.db.query(create_sql, [
p.user_login,
EncryptUtil.md5(p.user_pass),
p.user_phone,
Date.now(),
]);
return affectedRows === 1;
}
}

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

View File

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Some files were not shown because too many files have changed in this diff Show More