Construct node + KOA + mysql + Sequelize project note


Project address: github.com/tang-yue/si…

The first step

See the KOA official website to see Liao Xuefeng KOA tutorial

Perform the following steps: 1. NPM init

NPM install koa

NPM install koa-bodyParser // Get the body parameter. The koA-bodyParser must be registered with the app object before the router

NPM install koa-router // install koa-router

5. NPM install nodemon // Will be automatically updated after the modification is saved. Json file, change the start of scripts to “start”: “nodemon app.js”,

The app.js file becomes the following

const koa = require("koa")
const router = require('koa-router')()

const bodyParser = require('koa-bodyparser') const app = new koa() app.use(bodyParser()) const asyncFunc = async (CTX, next) => {ctx.body = '<h1>Hello, haha! </h1>` } router.get('/path', asyncFunc)

app.use(router.routes()).use(router.allowedMethods())

app.listen(8080)
Copy the code

The second step

See Getting Started in Sequelize’s Documentation

NPM install mysql2 –save 2. NPM install mysql2 –save 3. Create a SRC folder and set up a new folder under SRC. Controllers, models,.

Create a new config.js under Middlewares

The config.js file is as follows:

// In this file, you can get the remote backend configuration file, such as Apollo, and parse it to get the corresponding database information. When going online, you only need to replace the configuration file with the online one. const Sequelize = require('sequelize')

module.exports = () => {
  return async (ctx, next) => { 
    const options = {
        host: 'localhost',
        user: 'root',
        password: '12345678',
        port: '3306',
        database: 'RUNOOB'
    }

    const seq = new Sequelize('RUNOOB', options.user, options.password, {
      host: options.host,
      port: options.port,
      dialect: 'mysql', pool: {Max: 10,}}) ctx.sequelize = seqCopy the code

In the app. Js added

const middleConfig = require('./src/middleware/config.js')

app.use(middleConfig())
Copy the code

The third step

Operation database, write interface test

Create a test.js table under Models

Test.js contains the following contents

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

const user = function (seq) {
    const UserModal = seq.define('user', {
      id: {
        type: Sequelize.BIGINT,
        primaryKey: true,
      },
      name: Sequelize.STRING,
      age: Sequelize.BIGINT,
      sex: Sequelize.ENUM('male'.'female'),
    }, {
      timestamps: false,
      freezeTableName: true,})return UserModal
}

module.exports = user
Copy the code

2, Create test.js under controllers

The following

const { Sequelize } = require('sequelize');
const test = require('.. /models/test'); // Add const create =function (seq) {
  const UserModel = test(seq) // UserModel.sync(); Create table userModel.create ({name:' ',
    age: 1,
    sex: 'male',
  }).then(res => {
    console.log('create', JSON.parse(JSON.stringify(res))); })} // Delete const deleteItem =function (seq, ctx) {
    const id = ctx.params.id
    const UserModel = test(seq)
    UserModel.destroy({
      where: {
        id: id
      }
    }).then(() => {
      console.log('delete', `id: ${id}')})} // Get all information const getInfo =function (seq, ctx) {
  return new Promise((resolve, reject) => {
    const UserModel = test(seq)
    UserModel.findAll().then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}


module.exports = {
    create,
    deleteItem,
    getInfo,
}
Copy the code

Create test.js under handles

const userControllers = require('. /.. /controllers/test')

async function createUser(ctx) {
    await userControllers.create(ctx.sequelize)

    const data = {
        errCode: 0,
        errMsg: 'Database added successfully'
      }
      ctx.body = data;
}

async function deleteItem(ctx) {
    await userControllers.deleteItem(ctx.sequelize, ctx)
    const data = {
      errCode: 0,
      errMsg: 'Deleted successfully',
    }
    ctx.body = data
}

async function getInfo(ctx) {
    const info = await userControllers.getInfo(ctx.sequelize, ctx)
    console.log(info, 'info')
    const data = {
        errCode: 0,
        errMsg: 'success',
        data: info
      }
    ctx.body = data
}

module.exports = {
    create:createUser,
    deleteItem,
    getInfo,
}
Copy the code

4. Create test.js under the routers as follows

const router = require('koa-router')()
const userHandler = require('. /.. /handlers/test.js'Module.exports = (app, group) => {// prefix router. Prefix (group) router.'/addUser', userHandler.create)
  router.delete('/deleteItem/:id', userHandler.deleteItem)
  router.get('/allUserInfo', userHandler.getInfo)
  app.use(router.routes()).use(router.allowedMethods())
}
Copy the code

5. Add it to app.js

const userRouter = require('./src/routers/test')
userRouter(app, '/user')
Copy the code

The last

1, visit http://localhost:8080/user/allUserInfo can be used, the other can also use the same access

2. Configure esLint reference

3. Use mysql reference directly

4. Sequelize Chinese document reference