Use koA + React + Sequelize to create a blog system. Support to add, delete, modify, check and other functions.

The code is posted on Github

Take a look at the system interface

Koa uses koA-generate scaffolding tools provided by Uncle Wolf.

Installation of koa – generate

    npm install -g koa-generator
Copy the code

Create the project and initialize it

    koa cms_blog 
    cd cms_blog
    npm install
Copy the code

After successful installation, the project directory is as follows:

Run and open 127.0.0.1:3000 in your browser

    npm run dev
Copy the code

Start project construction: Adopt MVC pattern

  • In the root directory to create controllers, modules, schema, the config folder
    • Controllers: Write the control logic part
    • Modules: Write the SQL part
    • Schema: Write the data table part
    • Config: writes the database configuration

Nodejs ORM database: Sequelize

  • Create db.js in the config directory and configure the database
    const Sequelize = require('sequelize')
    const sequelize = new Sequelize('koa'.'root'.'123456', {host:'localhost'.dialect:'mysql'.operatorsAliases:false.dialectOptions: {/ / character set
            charset:'utf8mb4'.collate:'utf8mb4_unicode_ci'.supportBigNumbers: true.bigNumberStrings: true
        },
        pool: {max: 5.min: 0.acquire: 30000.idle: 10000
        },
        timezone: '+ 08:00'  // Time zone 8 EAST
    })
    
    module.exports = {
        sequelize
    }
Copy the code
  • Create an article table
The name of the type The length of the A primary key
id int 11 true
title varchar 255 false
authore varchar 255 false
content varchar 255 false
createdAt datetime 0 false
updatedAt datetime 0 false
  • Create article.js in the schema folder
    const blog = (sequelize, DataTypes) = > {
    return sequelize.define('blog', {id: {type:DataTypes.INTEGER,
            primaryKey:true.allowNull:true.autoIncrement:true
        },
        title: {
            type: DataTypes.STRING,
            allowNull: false.field: 'title'
        },
        author: {
            type: DataTypes.STRING,
            allowNull: false.field: 'author'
        },
        content: {
            type: DataTypes.STRING,
            allowNull: false.field: 'content'
        },
        createdAt: {type:DataTypes.DATE
        },
        updatedAt: {type:DataTypes.DATE
        }
    },{
        /** * if true, the name of the table created by mysql is the same as that of model (user *)
        freezeTableName: false})}module.exports =  blog
Copy the code

After the database is configured, the interface is developed in restful API mode

Get request: data query

  • Create article. Js in the Routes directory
    const router = require('koa-router') ()// Use koa-router to specify the interface route
    const BlogControll = require('.. /controllers/blog') // Introduce the Control section
    
    // Use router.get to provide the GET request
    router.get('/blog', BlogControll.getAllBlog)
Copy the code
  • Create article. Js in the controllers directory
    const BlogModel = require('.. /modules/blog') / / introduction of the model
    
    static async getAllBlog(ctx) {
        const { query } = ctx.request; // Get the parameters from the front end
        try {
            let data = await BlogModel.getAllBlog(query) // Get the query data
            ctx.response.status = 200;
            ctx.body = {
                code: 200.msg: 'success',
                data,
                count: data.length
            }
        } catch (err) {
            ctx.response.status = 412;
            ctx.body = {
                code: 412.msg: 'error',
                err,
            }
        }
    }
Copy the code
  • Create article. Js in the modules directory
    const db = require('.. /config/db') // Import database configuration
    const Sequelize = db.sequelize; / / use sequelize
    const Blog = Sequelize.import('.. /schema/blog.js')
    Blog.sync({force: false})
    
    
    static async getAllBlog(query){
        Query data by using Sequelize's findAll
        // Implement the keyword query function according to the query parameter
        return await Blog.findAll({
            where: {
                ...query
            },
            order:[
                ["id"."DESC"]],})}Copy the code
  • At this point a get request interface to write good, run NPM run dev, open a browser running http://127.0.0.1:3000/api/v1/blog can see the data.

  • You can view it in the background system

Post request: Add data

  • In the routes/article. Js
    router.post('/blog', BlogControll.addBlog)
Copy the code
  • The controllers/article. Js
    static async addBlog(ctx) {
        let req = ctx.request.body;
        if (req.title && req.author && req.content) {
            try {
                let data = await BlogModel.addBlog(req)
                ctx.response.status = 200
                ctx.body = {
                    code: 200.msg: 'success',
                    data
                }
            } catch (err) {
                ctx.response.status = 412
                ctx.body = {
                    code: 412.msg: 'error',
                    err
                }
            }
        } else {
            ctx.response.status = 416
            ctx.body = {
                code: 416.msg: 'Parameter incomplete',}}}Copy the code
  • In the module/article. Js
    static async addBlog(data){
        return await Blog.create({
            title: data.title,
            author: data.author,
            content: data.content,
        })
    }
Copy the code
  • At this point add article interface is ready to write, you can add in the background system

Delete request: Delete the article

  • In the routes/article. Js
    router.delete('/blog/:id',BlogControll.deleteBlog)
Copy the code
  • The controllers/article. Js
    static async deleteBlog(ctx) {
        let id = ctx.params.id; // Delete by id
        if (id) {
            try {
                let data = await BlogModel.deleteBlogs(id)
                ctx.response.status = 200;
                ctx.body = {
                    code: 200.msg: 'success',}}catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 412.msg: 'err',
                    err
                }
            }
        } else {
            ctx.response.status = 416;
            ctx.body = {
                code: 416.msg: 'the lack of id',}}}Copy the code
  • In the module/article. Js
    static async deleteBlogs(id){
        return await Blog.destroy({
            where:{
                id
            }
        })
    }
Copy the code
  • So far delete the article interface is written, you can delete in the background system

Put request: Edit the article

  • In the routes/article. Js
    router.put('/blog', BlogControll.updateBlog)
Copy the code
  • The controllers/article. Js
    static async updateBlog(ctx) {
        let req = ctx.request.body;
        try {
            let data = await BlogModel.updateBlog(req)
            ctx.response.status = 200;
            ctx.body = {
                code: 200.msg: 'success',}}catch (err) {
            ctx.response.status = 412;
            ctx.body = {
                code: 412.msg: 'error',
                err
            }
        }
    }
Copy the code
  • In the module/article. Js
    static async updateBlog(data){
        const {id,title,author,content} = data;
        console.log('id',id)
        return await Blog.update(
            {
                title,
                author,
                content,
                id
            },
            {
                where:{
                    id
                }
            }
        )
    }
Copy the code
  • At this point, the update article interface is written and can be updated in the background system

Summary: KoA + Sequelize implements the add, delete, change and query interface. The code is on Github and can be downloaded and run directly. If this article has been helpful to you, thank Star