fast-mysql
v1.0.6
Published
装饰器风格的Sql语句查询框架
Downloads
11
Maintainers
Readme
fast-mysql
装饰器风格的Sql语句查询框架
安装
npm i fast-mysql
使用
index.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import initMysql from 'fast-mysql';
async function bootstrap() {
initMysql({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 123456,
database: 'xuan_admin',
});
const app = await NestFactory.create(AppModule);
await app.listen(1234);
}
bootstrap();
userMapping.ts
import { Injectable } from '@nestjs/common';
import { Sql } from 'fast-mysql';
@Injectable()
export class LoginMapping {
@Sql('select * from user where id = #{id}')
findUser(id: number): any {}
}
useController.ts
import { Controller, Get, Post } from '@nestjs/common';
import { LoginMapping } from './login.mapping';
@Controller('user')
export class LoginController {
constructor(private readonly loginMapping: LoginMapping) {}
@Get()
async userlogin() {
const user = await this.loginMapping.findUser(1);
return user;
}
}
理论上fast-mysql
能搭配任意node框架使用,例如Koa
、express
等等,这里选择nest示例是因为nest框架更符合装饰器风格
装饰器
@Sql
@Sql("Sql语句")
被Sql标识的函数接收的参数填入Sql语句占位符内,并将查询出来的数据当做函数被调用时的返回值返回
示例:
@Sql('select * from user where id = #{id}')
findUser(id: number): any {}
findUser(777)
// 解析的Sql为 select * from user where id = '777'
上述的#{}
将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号
示例:
@Sql('select * from user where id = ${id}')
findUser(id: number): any {}
findUser(777)
// 解析的Sql为 select * from user where id = 777
上述的${}
将传入的数据直接显示生成在sql中,$方式无法防止Sql注入,应当谨慎使用!
示例:
@Sql('select * from user where id = ${id}')
findUser(user: User): any {}
findUser({ name:'我是用户',id:777 })
// 解析的Sql为 select * from user where id = 777
接收的参数可以是对象
@ResultType
@ResultType(实体类)
被ResultType标识的函数返回的参数将处理为指定的实体类进行返回
示例:
class User {
constructor(
readonly user_id: number,
readonly user_name: string,
readonly user_password: string,
) {}
}
@ResultType(User)
@Sql('select * from user where id = #{id}')
findUser(id: number): any {}
findUser(777)
上述的findUser
返回值为User
实体类字段,例如数据库字段有 用户id、用户名、用户密码、用户邮箱,但使用ResultType
约束后将只返回 用户id、用户名、用户密码
疑问交流
暂无