# typeorm-connection **Repository Path**: towardly/typeorm-connection ## Basic Information - **Project Name**: typeorm-connection - **Description**: typeorm 数据库连接管理库 - **Primary Language**: JavaScript - **License**: MIT - **Default Branch**: master - **Homepage**: https://gitee.com/towardly/typeorm-connection - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-08-08 - **Last Updated**: 2024-01-11 ## Categories & Tags **Categories**: Uncategorized **Tags**: MySQL, ORM, typeorm, connection, datasource ## README ## typeorm-connection `typeorm` 数据库连接管理库。 ### `API` 1. `connect(config)`: 连接数据库, 其中 `config` 是一个 `JSON` 形式, 配置如下: 1. `logger?: ILoggerOption`: 日志选项, 默认为: `true` 2. `connections`: `JSON` 形式的连接配置, `key` 表示连接的名称, `value` - 表示 [DataSource Options](https://typeorm.io/data-source-options) ```javascript // 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", }, ], }, }, }); ``` 2. `dataSource(entityOrAlias)`: 参数为 `typeorm` 的实体对象或者是连接名称, 例如: `default`;返回 `typeorm` 的 `DataSource` 对象 3. `manager(entityOrAlias)`: 获取 `EntityManager` 对象 4. `destroy(alias)`: 断开某个数据库连接: `await destroy('default')` 5. `destroyAll()`: 断开所有的数据库连接 ### 使用 ```javascript 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 }); ``` ### 日志 ```javascript await connect({ logger: true, ... }) await connect({ logger: console, ... }) await connect({ logger: Pino(), ... }) // 使用 Pino 记录日志 ``` `logger` 选项可以为普通的日志记录对象,具有 `info`、`warn`、`error` 函数;或者是一个 `typeorm` 的自定义日志对象。 ### 在 `fastify` 中使用 ```javascript 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`