发布于 2026-01-06 0 阅读
0

使用 Postgres 和 Knex 设置 Node API 的结论

使用 Postgres 和 Knex 设置 Node API

结论

在本文中,我将搭建一个使用 Postgres 数据库和 Knex 查询构建器的 Node 项目。

Knex是什么?

Knex.js 是一个“内置电池”的 SQL 查询构建器,支持 Postgres、MSSQL、MySQL、MariaDB、SQLite3、Oracle 和 Amazon Redshift,设计灵活、可移植且易于使用。

首先,我们需要初始化项目以创建package.json文件。

npm init -y
Enter fullscreen mode Exit fullscreen mode

数据库设置

我将使用名为 Elephantsql 的在线数据库来搭建我的数据库。您可以在这里注册。

注册完成后,创建数据库。示例如下。

组装 Knex

安装项目所需的依赖项

npm i knex -g
npm i pg express dotenv --save
Enter fullscreen mode Exit fullscreen mode

.env在项目根目录下创建一个文件,并添加数据库 URL。示例如下。

DB_URL=URL (where URL is the database connection string)
Enter fullscreen mode Exit fullscreen mode

在终端中运行以下命令来初始化 knex

knex init
Enter fullscreen mode Exit fullscreen mode

上述命令会knexfile.js在项目根目录生成一个文件,其内容如下所示。

// Update with your config settings.

module.exports = {

  development: {
    client: 'sqlite3',
    connection: {
      filename: './dev.sqlite3'
    }
  },

  staging: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  },

  production: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  }

};

Enter fullscreen mode Exit fullscreen mode

我将修改knexfile.js配置文件Postgres,并指定迁移文件和种子文件的保存目录。请将knexfile.js文件编辑为以下代码。

require('dotenv').config();

module.exports = {
  development: {
    client: 'pg',
    connection: process.env.DB_URL,
    migrations: {
      directory: './data/migrations',
    },
    seeds: { directory: './data/seeds' },
  },

  testing: {
    client: 'pg',
    connection: process.env.DB_URL,
    migrations: {
      directory: './data/migrations',
    },
    seeds: { directory: './data/seeds' },
  },

  production: {
    client: 'pg',
    connection: process.env.DB_URL,
    migrations: {
      directory: './data/migrations',
    },
    seeds: { directory: './data/seeds' },
  },
};


Enter fullscreen mode Exit fullscreen mode

数据库配置

在数据目录下创建一个db.js文件data,用于存放我们的 Knex 配置。该文件将保存我们各个环境的配置信息。

将以下代码添加到db.js文件中。

const knex = require('knex');

const knexfile = require('../knexfile');


const env = process.env.NODE_ENV || 'development';
const configOptions = knexfile[env];

module.exports = knex(configOptions);
Enter fullscreen mode Exit fullscreen mode

迁徙

迁移功能允许您定义一系列架构更改,从而使数据库升级变得轻而易举。

要创建/生成迁移文件,请运行以下命令。

knex migrate:make todo 
Enter fullscreen mode Exit fullscreen mode

注意:todo上面的命令中是迁移名称。

上述命令会在指定的迁移路径下创建一个迁移文件。在本例中。/data/migrations

然后我们可以编辑迁移文件,添加待办事项表中需要的列。

exports.up = knex =>
  knex.schema.createTable("todo", tbl => {
    tbl.increments();
    tbl.text("task", 128).notNullable();
  });

exports.down = knex => knex.schema.dropTableIfExists("todo");
Enter fullscreen mode Exit fullscreen mode

要运行迁移,您可以运行以下命令。

knex migrate:latest
Enter fullscreen mode Exit fullscreen mode

knex migrate:latest它会遍历我们所有的迁移文件,并运行up相应的函数,然后在我们的数据库中创建表。

要回滚迁移,您可以运行以下命令。

knex migrate:rollback
Enter fullscreen mode Exit fullscreen mode

knex migrate:rollback它会遍历我们所有的迁移文件,并运行down那些会删除数据库中表的函数。

种子

种子文件允许您使用测试或种子数据填充数据库,而无需依赖迁移文件。

要生成种子,请在终端运行以下命令。

knex seed:make todo
Enter fullscreen mode Exit fullscreen mode

这将todo.js在您的种子目录中创建一个文件,该文件指定用于我们的种子knexfile.js,然后可以对其进行编辑以包含我们的测试数据。
以下是一个种子文件示例。


exports.seed = function(knex) {
  // Deletes ALL existing entries
  return knex('todo').del()
    .then(function () {
      // Inserts seed entries
      return knex('todo').insert([
        {id: 1, task: 'Create API'},
        {id: 2, task: 'Watch Money Heist'},
        {id: 3, task: 'Do Dishex'}
      ]);
    });
};

Enter fullscreen mode Exit fullscreen mode

要运行种子文件,我们可以在终端上运行以下命令。

knex seed:run 
Enter fullscreen mode Exit fullscreen mode

运行命令会获取所有种子文件,然后将它们添加到我们的数据库中。

脚本

您可以向package.json文件中添加脚本。

 "scripts": {
    "start": "node index",
    "migrate": "knex migrate:latest",
    "unmigrate": "knex migrate:rollback",
    "seed": "knex seed:run "
  }
Enter fullscreen mode Exit fullscreen mode

start此命令用于启动我们的应用程序。
migrate此命令用于将迁移添加到我们的数据库。
unmigrate此命令用于回滚/删除数据库中所有现有的迁移。

要查询数据库,您只需导入db.js我们创建的文件并执行查询即可。示例如下所示。

const db = require("./data/db.js"); // importing the db config

app.get("/todo", async (req, res) => {
  const todos = await db("todo"); // making a query to get all todos
  res.json({ todos });
});
Enter fullscreen mode Exit fullscreen mode

结论

在本文中,我们已经能够了解如何使用 Postgres 数据库和 Knex 查询构建器设置 Node API。

本文演示中使用的源代码可以在这里找到。

点击此处了解更多关于Knex的信息

如果您有任何疑问或反馈,请留言。

感谢阅读。

这篇文章最初发表在我的博客上。

文章来源:https://dev.to/easybuoy/setting-up-a-node-api-with-postgres-and-knex-588f