fastify-bookshelf
fastify
中使用 Bookshelf.js
连接数据库,并配置映射 Model
。
安装
yarn add fastify-bookshelf
# 安装下面的其中一个,根据连接的数据库选择
yarn add pg
yarn add sqlite3
yarn add mysql
yarn add mysql2
yarn add mariasql
yarn add strong-oracle
yarn add oracle
yarn add mssql
使用
const bookshelf = require('fastify-bookshelf');
fastify.register(bookshelf, {
client: 'mysql2',
connection: 'mysql://usernmae:password@127.0.0.1:3306/database_name',
models: ['User', 'Role'],
});
fastify.get('/', (request, reply) => {
new fastify.models.User({ id: 1 }).fetch();
});
该示例连接上数据库后,会在 fastify
实例上映射一个 models
对象,该对象包含两个一个是 User
对应的数据库表为 users
,一个是 Role
对应的数据库表名 roles
配置项
-
client?: string
:使用的连接数据库的插件,需要进行npm install
安装,详情参见:knex 文档;如果不填默认为:mysql2
-
connection?: string | Knex.StaticConnectionConfig | Knex.ConnectionConfigProvider;
:数据库连接地址,详情 knex 文档 -
models: string[]
:配置需要映射的Model
, 如果 为string
类型, 则Model - name
为填写的名称,映射的数据库表名为:首字母小写, 末尾 s。直接使用字符串的时候,使用了 requireFetch: false;如果填写的object
类型,则配置项为 bookshelf.model 函数的第 2 个参数的基础上增加name
字段表示Model - name
;例如:[ // 对应的 Role, 表名为: roles 'Role', // 在 bookshelf 基础上新增了 name 字段 { name: 'User', tableName: 'users', hasTimestamps: true, author() { return this.belongsTo('Author'); }, }, ];