This article is a small demo of how to use Nodejs to write a list of additions, deletions, changes and searches. This article mainly introduces the use of NodeJS and common plug-in API. Hope it can be helpful to beginners of Node.

Attached is the project github address: github.com/fangcheng14…

Requirement Specification (API Specification)

  1. Query the list of tasks based on the different parameters (status/page number) passed by the client
  2. Implement the ability to add a task (name/deadline/content)
  3. Implement an edit function: edit (name/expiration date/content) based on the task object (existing data) passed by the client
  4. Delete a task (ID)
  5. Changing the status of the task (ID/ Status — To do/Completed)

I. Project construction and related API installation

1. Create projects and install dependencies

mkdir list_page_node // Create a folder named 'list_page_node'
npm init -y // Initialize the project to generate a default package.json file
git init Create a new Git repository
npm install express mysql2 sequelize sequelize-cli body-parser nodemon -S // Install dependencies
Copy the code

Express: The first generation of the most popular Web framework that encapsulates HTTP for Node.js. Mysql2: database used in node. Sequelize :Sequelize is a Promise-based ORM for Node.js and io.js. Sequelize -CLI :sequelize -CLI tool body-parser: middleware that receives PARAMETERS in the body of POST requests. Nodemon: a tool that can debug Node.js-based applications by restarting the application when it automatically detects file changes in the directory.

Why use mysql2 instead of the classic mysql library? Mainly based on the following reasons:

  • Higher performance!
  • Support PreparedStatement, multiple query performance is higher, write SQL is easier;
  • With Promise wrappers, you can use async/await syntax directly;
  • Most oF the apis are compatible with mysql libraries, which means that mysql documentation and online materials can also be used as a reference.

2. Look at what dependencies are installed

"Dependencies" : {" body - the parser ":" ^ 1.19.0 ", "express" : "^ 4.17.1", "lodash" : "^ 4.17.11", / / front end can be used in tool library "moment" : "^ 2.24.0," / / "mysql2" dedicated to the processing date: "^ 2.2.5", "sequelize" : "^ 6.6.2", "sequelize - cli" : "^ 6.2.0"},Copy the code

3. Configure boot options

Create the SRC directory and app.js entry file under the root directory

  "scripts": {
    "start": "nodemon src/app.js",
  },
Copy the code

Second, framework code writing

1. Express framework application writing

const express = require('express');
const app = express();

app.listen(3000.() = >{
    console.log('Server started successfully')})Copy the code

2. API framework writing

1. Error handling

// 1. All errors HTTP status == 500
app.use((err,req,res,next) = >{
    if(err) {
        res.status(500).json({
            "message": err.message
        })
    }
})
Copy the code

An error test

app.get('/list'.async (req,res,next)=>{
    next(new Error('Custom exception'))})Copy the code

2. Query the task list

app.get('/list/:status/:page'.async (req,res)=>{
    res.json({
        list: []})})Copy the code

3. Add a task

// Reference the body-parser middleware
const bodyParser = require('body-parser');

// specifically for handling Exoress JSON
app.use(express.json());

// Used to encode url parameters
// for parsing application/xwww-form-urlencoded
app.use(express.urlencoded());

// Used to encode the body argument
// for parsing application/xwww-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));


app.post('/create'.async (req,res)=>{
    let { name,deadline,content } = req.body;// Need to reference 'body-parser' middleware processing
    res.json({
        todo:[],
        name,
        deadline,
        content
    })
})
Copy the code

4. Modify the task

app.post('/update'.async (req,res)=>{
    let { name,deadline,content,id } = req.body; // Need to reference 'body-parser' middleware processing
    res.json({
        todo:[],
        name,
        deadline,
        content,
        id
    })
})
Copy the code

5. App.js code overview

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

// specifically for handling Exoress JSON
app.use(express.json());

// Used to encode url parameters
// for parsing application/xwww-form-urlencoded
app.use(express.urlencoded());

// Used to encode the body argument
// for parsing application/xwww-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// Query the task list
app.get('/list/:status/:page'.async (req,res)=>{
    res.json({
        list: []})})// Create a task
app.post('/create'.async (req,res)=>{
    let { name,deadline,content } = req.body; // Need to reference 'body-parser' middleware processing
    res.json({
        todo:[],
        name,
        deadline,
        content
    })
})

// Modify the task
app.post('/update'.async (req,res)=>{
    let { name,deadline,content,id } = req.body; // Need to reference 'body-parser' middleware processing
    res.json({
        todo:[],
        name,
        deadline,
        content,
        id
    })
})

// Modify the task and delete it
app.post('/update_status'.async (req,res)=>{
    let { id,status } = req.body; // Need to reference 'body-parser' middleware processing
    res.json({
        todo:[],
        id,
        status
    })
})


// 1. All errors HTTP status == 500
app.use((err,req,res,next) = >{
    if(err) {
        res.status(500).json({
            "message": err.message
        })
    }
})

app.listen(3000.() = >{
    console.log('Server started successfully')})Copy the code

Initialization of the database

1. Create a database

1. Install the database

MAC system: MAC system can be directly through the command line brew package installation (the prerequisite is to install brew on your MAC, installation process can be seen: macOS install Homebrew or MAC image quick install Homebrew tutorial

Brew services list // start mysql brew services start mysql // stop mysql brew services Stop mysql // Log in to mysql mysql -u root -pCopy the code

For more information about installing MySQL on Mac systems, see

Windows system: Windows system installation MySQL visible rookie tutorial introduction: MySQL installation

2. Create a database

Open Navicat and create a new database

So now we have a database.

2. Initialize the database configuration of the project

We can create a folder in the root directory of the file to store the database configuration file.

Mkdir db // Create a folder db CD db NPX sequelize initCopy the code

3. Generate model files

npx sequelize model:generate --name List --attributes name:string,dedaline:date,content:string
Copy the code

4. Persistence, model corresponding [database table]

npx sequelize db:migrate
Copy the code

You can see our new table and corresponding fields in Navicat.

5. Add new fields to the database table

Step 1: Find the object table file in DB/Models and add a new field under listData.init.

Step 2: Find the corresponding file in db/migrations and add a new field under createTable. In which, you can set the defaultValue of the field, defaultValue setting.

Step 3: Open Navicat, delete the SequelizeMeta table from the ListData table, and clear the SequelizeMeta table.

Step 4 run the NPX sequelize db:migrate command again in the bg folder

Iv. Specific IMPLEMENTATION of API (using ORM model)

1. Import the model

// Import the model
const models = require('.. /db/models');
// Models is an object that contains:
/ / {
// [modal:listdate]
// sequelize
// Sequelize
// }
Copy the code

2. Create task code

The create () method

// Create a task
app.post('/create'.async (req,res,next)=>{
    try {
        let { name,deadline,content } = req.body; // Need to reference 'body-parser' middleware processing
        // ListData is the name of the table in the database on which you want to operate
        // The create()API represents a new entry of data
        let data = await models.ListData.create({
            name,
            deadline,
            content
        })
        res.json({
            data,
            message: 'Created successfully'})}catch(error) { next(error); }})Copy the code

You may get an error

{
    "message": "Unknown column 'createdAt' in 'field list'"
}
Copy the code

Reason: Sequelize generated createdAt and updateAt by default when the database table was created. Solution: Find the corresponding table file in db/ Models and add ‘timestamps: false’

3. Modify the task code

FindOne (), update() methods

// Modify the task
app.post('/update'.async (req,res,next)=>{
    try {
        let { name,deadline,content,id } = req.body;
        // findOne()API means to find something
        let data = await models.ListData.findOne({
            where:{
                id
            }
        })
        // Check whether the data is found, then perform the update function
        if (data) {
            Update ()API
            data = await data.update({
                name,
                deadline,
                content
            })
        }
        res.json({
            data
        })
    } catch(error) { next(error); }})Copy the code

4. Modify the task status and delete the code

FindOne (), update() methods

// Modify the task status and delete it
app.post('/update_status'.async (req,res,next)=>{
    try {
        let { id,status } = req.body;
        // findOne()API means to find something
        let data = await models.ListData.findOne({
            where:{
                id
            }
        })
        // Determines that the data is found and fires when status changes
        if(data && status ! = data.status) {Update ()API
            data = await data.update({
                status
            })
        }
        res.json({
            data
        })
    } catch(error) { next(error); }})Copy the code

5. Query the code of the task list

FindAndCountAll () method

// Query the task list
app.get('/list/:status/:page'.async (req,res,next)=>{
    Status: 1: charge 2: complete 3: delete -1: all
    / / 2. Paging
    try {
        // Get the URL argument: req.params
        let { status,page } = req.params;
        let limit = 10; // Set the number of pages to display
        let offset = (page - 1) * limit; // The starting position of each page
        let where = {};
        if(status ! = -1) where.status = status; // If the value is -1, search all

        // findAndCountAll() API represents queries and aggregates totals
        let list = await models.ListData.findAndCountAll({
            where,
            limit,
            offset
        })
        res.json({
            list,
            message: 'List query successful'})}catch(error) { next(error); }})Copy the code

6. The API

  • Create (): adds a data item
  • FindOne (): indicates that one is found
  • Update (): Updates the function
  • FindAndCountAll (): represents queries and aggregates totals

V. Project release, operation and maintenance

1. pm2

Pm2: management tool in the NodeJS production environment.

// Install: NPM I pm2 -g // Initialize the project startup, o&M script: a configuration file (nerb.config.js) will be generated. pm2 initCopy the code

2. File.config. js configuration file

module.exports = {
  apps : [{
    name: 'list_page'./ / name
    script: 'src/app.js'.// Start the script file
    instances: 1./ / instance number
    autorestart: true.// Enable/disable automatic restart when the application crashes or exits
    watch: false.// Whether to enable monitoring mode. The default is false. If set to true, pM2 is automatically reloaded when the application changes. This is also where you can set the files you want to monitor.
    max_memory_restart: '1G'.// Maximum boot memory for a restart}]};Copy the code

3. Start the command

Pm2 start file.config. js // Displays the status of all processes pm2 list // Displays the logs of all processes pm2 logs // Restarts the specified process ecosystem.config.jsCopy the code

Pm2 You can use pM2 to manage Node processes

conclusion

Although the article is a little long, in fact, you will find that it contains little content, mainly a list of additions, deletions, changes and checks, introduces the use of Node and related plug-ins, using express framework can be more convenient to build the basic node architecture, database using mysql2, Sequelize (as ORM) is used to associate the project with the database, and provides some apis for the front-end to operate on the database. Finally, pM2, NodeJS generation environment management tools are introduced. Of course, this is just an introduction to Node, but a more thorough understanding of Node requires further learning. Finally, I hope this article can be helpful to those who are learning Node.