typeorm-connection
TypeScript icon, indicating that this package has built-in type declarations

0.0.6 • Public • Published

typeorm-connection

typeorm 数据库连接管理库。

API

  1. connect(config): 连接数据库, 其中 config 是一个 JSON 形式, 配置如下:

    1. logger?: ILoggerOption: 日志选项, 默认为: true
    2. connections: 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",
        },
      ],
    },
  },
});
  1. dataSource(entityOrAlias): 参数为 typeorm 的实体对象或者是连接名称, 例如: default;返回 typeormDataSource 对象

  2. manager(entityOrAlias): 获取 EntityManager 对象

  3. destroy(alias): 断开某个数据库连接: await destroy('default')

  4. 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 选项可以为普通的日志记录对象,具有 infowarnerror 函数;或者是一个 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 个基础的字段:

  1. id: 自增长的 id
  2. createTime: Date 对应的数据库字段为:create_time
  3. updateTime: Date 对应的数据库字段为: update_time

Package Sidebar

Install

npm i typeorm-connection

Weekly Downloads

1

Version

0.0.6

License

MIT

Unpacked Size

14.6 kB

Total Files

7

Last publish

Collaborators

  • lucidus