0.0.6 • Published 2 years ago
typeorm-connection v0.0.6
typeorm-connection
typeorm 数据库连接管理库。
API
connect(config): 连接数据库, 其中config是一个JSON形式, 配置如下:logger?: ILoggerOption: 日志选项, 默认为:trueconnections:JSON形式的连接配置,key表示连接的名称,value- 表示 DataSource Options
// 1. 普通连接
await connect({
default: {
url: "mysql://root:x@x.x.x.x:3306/x",
entityPrefix: "sl_site_",
entities: Object.values(entities),
},
});
// 2. 读写分离支持
await connect({
default: {
entityPrefix: "sl_site_",
entities: Object.values(entities),
replication: {
// 配置读写数据库
master: {
url: "mysql://root:x@x.x.x.x:3306/x",
},
// 配置只读数据库
slaves: [
{
url: "mysql://root:x@x.x.x.x:3306/x",
},
],
},
},
});dataSource(entityOrAlias): 参数为typeorm的实体对象或者是连接名称, 例如:default;返回typeorm的DataSource对象manager(entityOrAlias): 获取EntityManager对象destroy(alias): 断开某个数据库连接:await destroy('default')destroyAll(): 断开所有的数据库连接
使用
import { connect, manager, BaseDataEntity } from 'typeorm-connnection'
/**
* 登录记录表
*/
@Entity({ name: 'login_record' })
export class LoginRecord extends BaseDataEntity {
@Column({ type: 'bigint', name: 'user_id', unsigned: true })
public userId: number;
@Column({ type: 'varchar', length: 50, nullable: true })
public ip: string;
@Column({ type: 'varchar', name: 'user_agent', length: 500, nullable: true })
public userAgent: string;
/** 登录的平台,wxh5-公众号,h5-网页 */
@Column({ type: 'varchar', length: 20, default: 'wxh5', comment: '登录的平台,wxh5-公众号,h5-网页' })
public platform: string;
}
// 1. 连接数据库
await connect({
default: {
url: 'mysql://root:x@x.x.x.x:3306/x',
entityPrefix: 'sl_site_',
entities: [LoginRecord]
},
})
const em = manager('default') // manager(LoginRecord)
// 查询数据
const record = await em.findOneBy(LoginRecord, { id: 1 });日志
await connect({ logger: true, ... })
await connect({ logger: console, ... })
await connect({ logger: Pino(), ... }) // 使用 Pino 记录日志logger 选项可以为普通的日志记录对象,具有 info、warn、error 函数;或者是一个 typeorm 的自定义日志对象。
在 fastify 中使用
import { register_fastify } from "typeorm-connection";
const app = fastify();
register_fastify(app, {
url: "mysql://root:x@x.x.x.x:3306/x",
entityPrefix: "sl_site_",
entities: [LoginRecord],
});基础的实体类
提供基础的数据实体类 BaseDataEntity,该实体类,包含 3 个基础的字段:
id: 自增长的idcreateTime:Date对应的数据库字段为:create_timeupdateTime:Date对应的数据库字段为:update_time