TypeORM 使用之配置篇

简介

TypeORM 是一个能运行在 node 环境下的数据库驱动。 实际开发中主要用的是mysql, 以下讲的基本围绕着mysql的配置展开,但部分参数对于不同的数据库类型还是共用的。

创建连接

基本配置参数

type: 当前要连接的数据库类型(mysql,mssql, moongo, ...)
host: 数据库服务暴露的host
port: 数据库服务暴露的端口
username: 连接数据库服务的用户名
password: 连接数据库服务的用户名
database: 连接数据库名

import { createConnections } from 'typeorm';

const connection = await createConnection({
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'test',
  password: 'test',
  database: 'test',
});

以上是官方的例子,但参数并不仅仅是这几个,翻阅文档, 会发现其实还是有几个关键的参数,了解多一点对于平时开发及生产环境都有一定的帮助

额外参数

  • name: 设置连接名,连多个数据库的时候,需要获取连接的时候可用 getConnection('name') 的方式取得对应的数据库连接;
  • entities: 要加载并用于此连接的实体。写法类似:
 entities: [Post, Category, "entity/*.js", "modules/**/entity/*.js"]
  • entityPrefix: 表名前缀
  • extra: 拓展的参数值, 如设置连接池连接数量等;
  • logging

    查询(query):记录所有查询。
    错误(error):记录所有失败的查询和错误。
    模式(schema):记录模式构建过程。
    警告(warn):记录内部orm警告。
    记录(info):内部orm信息信息。
    日志(log):记录内部orm日志消息。

如果只是简单的打印基本的数据库操作(包含错误)则设置 logging: true
如果要打印以上全部类型,则设置 logging: 'all'
如果只是打印其中的1~2个(如query, error),则可设置 logging: ['query', 'error']

  • logger: 可设置的类型有 advanced-console,simple-console,file, debug, 在开启 logging 的情况下,logger默认使用类型是 advanced-console, 这个模式会高亮字体和标示sql语句。
  • cache: 对查询的 sql 结果进行缓存。 支持数据库或者redis。看了下api,redis更为方便一点。
    cache 的 interface 定义如下:
    readonly cache?: boolean | {
        /**
         * Type of caching.
         *
         * - "database" means cached values will be stored in the separate table in database. This is default value.
         * - "redis" means cached values will be stored inside redis. You must provide redis connection options.
         */
        readonly type?: "database" | "redis";
        /**
         * Used to provide redis connection options.
         */
        readonly options?: any;
        /**
         * If set to true then queries (using find methods and QueryBuilder's methods) will always be cached.
         */
        readonly alwaysEnabled?: boolean;
        /**
         * Time in milliseconds in which cache will expire.
         * This can be setup per-query.
         * Default value is 1000 which is equivalent to 1 second.
         */
        readonly duration?: number;
    };

如果type:'redis',则optoins的配置可见:如何配置options,
下面会举例 cache 的基本配置

   cache: {
        type: 'redis', // 必须参数
        options: {
            host: 'localhost',
            port: 6379,
            username: '',
            password:'',
            db: 1, // 这个任君选择,0~15库都可以选
        }
    }

在补充以上参数后,我们的数据库连接配置如下:

import { createConnections } from 'typeorm';

const connection = await createConnection({
  name: 'account', // 给这个连接起个名字,如果是用户库,则可以起名 account
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'test',
  password: 'test',
  database: 'test',
  entities: [__dirname + '/entity/*{.js,.ts}'], // 用此连接的实体
  logging: true, // 开启所有数据库信息打印
  logger: 'advanced-console', // 高亮字体的打印信息
  extra: {
    connectionLimit:  10, // 连接池最大连接数量, 查阅资料 建议是  core number  * 2 + n 
  },
  cache: {
    type: 'redis',
    options: {
       host: 'localhost',
       port: 6379,
       username: '',
       password:'',
       db: 1, // 这个任君选择,0~15库都可以选
     }
  }, // 如果对cache没有需求,设置`cache:false`或者干脆不填此个参数也是可以的
});

创建多个数据库连接

假设创建用户库和作品库的连接

import { createConnections } from 'typeorm';

const connections = await createConnections([{
    name: 'account',
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    username: 'root',
    password: 'admin',
    database: 'account',
    entities: [__dirname + '/entity/*{.js,.ts}'],
    logging: true, // 开启所有数据库信息打印
    logger: 'advanced-console', // 高亮字体的打印信息
    extra: {
      connectionLimit:  10, // 连接池最大连接数量, 查阅资料 建议是  core number  * 2 + n 
    },
}, {
    name: 'work',
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    username: 'root',
    password: 'root',
    database: 'work',
    entities: [__dirname + '/entity/*{.js,.ts}'],
    logging: true, // 开启所有数据库信息打印
    logger: 'advanced-console', // 高亮字体的打印信息
    extra: {
      connectionLimit:  10, // 连接池最大连接数量, 查阅资料 建议是  core number  * 2 + n 
    },
}]);

获取指定数据库连接

假设需要获取用户及作品库的连接

  • 方式一:
import { getConnection } from 'typeorm';

const account_connection = getConnection('account');
const work_connection = getConnection('work');
  • 方式二:
import { getConnectionManager } from "typeorm";

const account_connection = getConnectionManager().get('account');
const work_connection  = getConnectionManager().get('work');

文档参考

TypeORM 配置

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,192评论 2 89
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,159评论 19 139
  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 10,993评论 0 9
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,157评论 6 342
  • 文/海欧 细数我们先前犯下的过错,大多都是因为年轻气盛。没错,年轻气盛,好像年轻就一定要气盛似的,其实不然。年轻,...
    海欧亭亭阅读 9,365评论 7 79

友情链接更多精彩内容