Node.js应用程序中的Sequelize ORM

147 阅读5分钟

大家好!在本教程中,我们将学习如何在Node js应用程序中对ORM进行排序。在本教程中,我们将学习如何在Node.js应用程序中Sequelize ORM。更具体地说,我们将在Node.js环境中建立一个RESTful应用程序,运行在Express.js服务器和PostgreSQL数据库中,以执行CURD操作。我们还将使用被称为Sequelize 的基于承诺的ORM依赖性来创建数据模型。

1.1.简介

RESTful API是指应用程序之间相互通信的标准网络服务接口。这种API符合REST的架构风格和约束。它是可扩展的、无状态的、可缓存的,并且有一个统一的接口。它利用HTTP请求,四个最常见的HTTP方法是POST、PUT、GET和DELETE。另一方面,Express.js是最流行的Node.js网络框架,为开发网络和移动应用提供了一套强大的功能。它提供的功能包括---

  • 设置中间件来响应HTTP请求
  • 定义路由表,根据HTTP方法执行不同的行动
  • 允许动态地渲染HTML页面

1.1 设置Node.js

要在Windows上设置Node.js,你需要从这个链接下载安装程序。点击你的平台的安装程序(也包括NPM包管理器),运行安装程序,开始Node.js设置向导。按照向导的步骤操作,完成后点击 "完成"。如果一切顺利,你可以导航到命令提示符来验证安装是否成功,如图1所示。

ORM in Node.js - npm installation

图 1: 验证 node 和 npm 的安装

1.2 设置PostgreSQL服务器

在教程的开始,我希望你已经在你的本地主机环境中启动并运行了PostgreSQL。为了方便设置,我把服务器设置在docker环境中运行。你可以执行下面的命令,在几分钟内让容器在docker上运行。请注意postgresql服务器docker命令 -

  • 将包含postgres 用户密码
  • 容器成功启动后将自动创建fakedatabase

Docker命令

-- run the postgresql container –
docker run -d -p 5433:5432 -e POSTGRES_PASSWORD=password -e POSTGRES_DB=fakedatabase --name postgres postgres

如果一切顺利,容器将成功启动,如图2所示。你可以使用docker ps -a 命令来确认该状态。关于docker基础知识的进一步信息,你可以浏览这个教程

ORM in Node.js - server on docker

图 2: Docker上的PostgreSQL服务器

2.在Node.js应用程序中序化ORM

在这一点上,我们已经成功创建了我们的应用程序所需的初始数据库。为了设置Node.js应用程序、Express.js服务器和Sequelize ORM模型,我们将需要导航到我们项目所在的路径。对于编程的东西,我正在使用Visual Studio Code作为我的首选IDE。你可以自由选择你喜欢的IDE。

2.1 设置依赖性

导航到项目目录,运行npm init -y ,创建一个package.json 文件。这个文件保存着与项目有关的元数据,用于管理项目的依赖性、脚本、版本等。在该文件中添加以下代码,我们将指定所需的依赖性。

package.json

{
  "name": "sequelizeorm-express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "pg": "^8.6.0",
    "pg-hstore": "^2.3.3",
    "sequelize": "^6.6.2",
    "underscore": "^1.13.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

要下载依赖项,请导航到包含该文件的目录路径,并使用npm install 命令。如果一切顺利,依赖项将被加载到node_modules 文件夹中,你就可以进行下一步了。

2.2 创建一个配置文件

config 文件夹中创建一个db种子文件,该文件将用于在Sequelize依赖项的帮助下创建一个与数据库的连接。你可以根据你的应用程序或数据库配置设置自由地改变这些细节。

数据库.js

const {Sequelize} = require('sequelize');

// TODO
// 1. export the Database variables from a config file
// 2. create a new user. in the production environment never use the default user

module.exports = new Sequelize('INIT_DB', 'DB_USER', 'DB_PWD', {
    host: 'localhost',
    port: 5433,
    dialect: 'postgres',
    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }
});

2.3 创建一个模型文件

models 文件夹中创建一个模型文件,该文件将用于在应用程序启动时借助Sequelize依赖关系在数据库(fakedatabase )中创建表(playlists )和列(id,name, 和deleted )。你可以根据你的要求自由改变这些细节。

playlists.js

const Sequelize = require('sequelize');
const db = require('../config/database');

const Playlists = db.define('playlists',
    {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: Sequelize.STRING
        },
        deleted: {
            type: Sequelize.BOOLEAN,
            allowNull: false
        }
    },
    {
        timestamps: false   // Disable timestamp attributes (createdAt, updatedAt)
    });

module.exports = Playlists;

2.4 创建控制器文件

routes 文件夹中创建一个控制器文件。这个文件将暴露端点,这些端点将负责在模型对象(Playlist )的帮助下执行CRUD操作。

api.js

const express = require('express');
const router = express.Router();
const Playlist = require('../models/playlists');
const _ = require('underscore');

// create and save a new playlist
// http://localhost:4001/create
// note - provide the json request body
/*
{
    "name": "golden sounds",
    "deleted": "true"
}
 */
router.post('/create', (req, res) => {
    if (_.isEmpty(req.body.name)) {
        res.status(400).json({info: 'Name cannot be null'});
    }

    const obj = {
        name: req.body.name,
        deleted: req.body.deleted || false
    };

    // save in db
    Playlist.create(obj)
        .then(data => {
            // console.log(data);
            res.status(201).json({info: `Entity ${data.id} created successfully`});
        })
        .catch((err) => console.log('Error: ' + err));      // TODO - Replace with a error response
});

// get all playlists | [where condition]
// http://localhost:4001/findAll
// or
// http://localhost:4001/findAll&deleted=false
router.get('/findAll', (req, res) => {
    const condition = _.isEmpty(req.query.deleted) ? {} : {where: {deleted: req.query.deleted}};
    Playlist.findAll(condition)
        .then(data => {
            // console.log(data);
            res.status(200).json({info: data});
        })
        .catch((err) => console.log('Error: ' + err));      // TODO - Replace with a error response
});

// get a single playlist
// http://localhost:4001/findById&id=1
router.get('/findById', (req, res) => {
    const playlistId = req.query.id;
    if (_.isEmpty(playlistId)) {
        res.status(400).json({info: 'Id cannot be null'});
    }

    Playlist.findByPk(playlistId)
        .then(data => {
            // console.log(data);
            res.status(200).json({info: data});
        })
        .catch((err) => console.log('Error: ' + err));      // TODO - Replace with a error response
});

// other HTTP methods like PUT, DELETE are skipped for brevity.
// you can add them on your own.

module.exports = router;

同样,你也可以为应用程序的健康检查端点创建另一个控制器文件(如health.js )。

2.5 创建一个索引文件

创建一个索引文件,它将作为我们服务器的入口。该文件将包含代码--

  • 在应用程序启动时测试数据库的连接性
  • 在模型对象sync 方法的帮助下,在应用程序启动时设置表和列
  • 定义通往应用程序端点的路由

index.js

// Database
const db = require('./config/database');
// DAO model
const Playlist = require('./models/playlists');

// Test DB connection
db.authenticate()
    .then(() => console.log('Database is connected'))
    .catch((err) => console.log('Error: ' + err));

// Automatically creating table on application startup
Playlist.sync({force: true}).then(() => {
    console.log("Drop and re-sync table");
});

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// Parse requests of Content-Type - application/json
app.use(bodyParser.json());
// Application routes
app.use('/', require('./routes/health'));
app.use('/api', require('./routes/api'));

const PORT = process.env.port || 4001;
app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

3.运行应用程序

要运行该应用程序,请导航到项目目录,并输入以下命令,如图4所示。如果一切顺利,应用程序将在端口号4001 上成功启动,Sequelize依赖将自动创建表和列。

ORM in Node.js - starting the app

图 3: 启动应用程序

4.项目演示

当应用程序启动后,打开Postman工具来打应用程序的端点。你可以自由地选择任何你喜欢的工具。

应用程序端点

// To determine application health status
HTTP GET url - http://localhost:4001/

// CRUD endpoints

// create a new playlist
HTTP POST url - http://localhost:4001/create
// note - provide the json request body
// {
//    "name": "golden sounds",
//    "deleted": "true"
// }

// get all playlists
HTTP GET url - http://localhost:4001/findAll

// get all playlists based on the deleted flag
HTTP GET url - http://localhost:4001/findAll&deleted=false

// get a single playlist
HTTP GET url - http://localhost:4001/findById&id=1

同样地,你也可以创建其他的端点。本教程就讲到这里,我希望这篇文章能为你提供你想要的东西。学习愉快,别忘了分享

5.总结

在本教程中,我们学到了。

  • RESTful API和Express.js的介绍
  • 设置Node.js和使用Docker启动PostgreSQL服务器的步骤
  • 通过Express.js和Sequelize依赖关系,使用RESTful端点执行CRUD操作的编程样本内容

你可以从下载部分下载本教程的源代码。

6.下载项目

这是一个关于Sequelize ORM在node.js应用程序中的编程教程。