fastify-bookshelf
TypeScript icon, indicating that this package has built-in type declarations

0.0.3 • Public • Published

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

配置项

  1. client?: string:使用的连接数据库的插件,需要进行 npm install 安装,详情参见:knex 文档;如果不填默认为:mysql2

  2. connection?: string | Knex.StaticConnectionConfig | Knex.ConnectionConfigProvider;:数据库连接地址,详情 knex 文档

  3. 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');
        },
      },
    ];

文档

连接项的配置参见 knex、配置 Model 以及具体的使用参见 bookshelf

Package Sidebar

Install

npm i fastify-bookshelf

Weekly Downloads

0

Version

0.0.3

License

MIT

Unpacked Size

7.15 kB

Total Files

5

Last publish

Collaborators

  • lucidus