SHH! A long word.

As a front-end development engineer, we usually contact with the back end of the most is the interface docking. So how do the back-end guys write an interface for our front-end guys to get database data and do some fancy stuff? We’re going to use it today
Koa2 & mySqlTo build a back-end server to achieve their own write
apiThe Chinese dream!


preface

For some front-end development partners, back-end development may be a strange field, after all, now the front-end work is heavy (I don’t have time to learn back-end development duck! . Thanks to Node.js, we can implement some back-end technology on top of our existing front-end skills, which lowers the barrier to entry for back-end development.

Today, DONG ai (XI) is a set of koA2 & mysql & PM2 basic templates that I extracted from a recent project (koA2 +mysql + PM2 as a back-end service). The purpose is to let our front-end partners can directly use it to develop interfaces, to achieve their dreams.

Code warehouse
Github.com/yigeyi/funn…

The tutorial is currently considering using PM2 to start the service in a Windows environment, and the dev environment has been tested


The target

Through this set of basic templates, rapid API development, front-end and back-end self-completion. In other words, after you clone the code, for learning purposes, you just need to start writing the API, I have configured some simple configuration, you just need to follow the steps below, you can write the API, docking interface, and then write your own.


The use of the technical

  • Koa2
  • MySql (please make sure your Windows is installedmysqlAnd can be started normallymysql)
  • PM2 (Make sure your Windows is installedPM2And can be started normallyPM2)



Software Installation Tutorial

  • MySql installation: blog.csdn.net/weixin_4343…
    • The installationwamporphpstudyThese two artifacts will automatically install it for youMySqlIf you are going to use it in a production environment, I believe your environment already has the required software
  • PM2 installation: juejin.cn/post/684490…
    • The abovePM2The tutorial is an article I wrote last time (it was kind of lame, I couldn’t read it anymore, haha, butpm2The installation is very easy, you can have a look, or you can also baidu to find the relevant complete tutorial)


The code structure




Environment configuration

Before using this set of Koa2 & MySQL & PM2 basic templates, you need to make sure you have Node, MySQL, and PM2 installed on your computer


Cloning code

Git address: https://github.com/yigeyi/funnyProject.git


Creating a database

Create a database named dev_db on your computer and execute the dev_db.sql file in the code file


The code is installed

// If NPM doesn't work, try CNPM ICopy the code


Start the service

Use pm2 start pm2.config.js –only dev to start the KOA2 project. When something like the screenshot below appears, your koA2 project has been started correctly.



At this point you can access the project using http://localhost:3200 (I’ll explain about port 3200 configuration below)



Configuration instructions

The main operation process of the project is as follows: Pass
pm2 start pm2.config.js --only dev/prod/testThis can also be used after starting the project
npm run dev/prod/test),
koa2Will be configured differently depending on the current startup environment
configParameters (
app.jsImport configuration files) to use different
portAs well as
mysqlParameter configuration (Configured in
configFolder, more on this below)


App.js configuration is imported

const Koa = require('koa')

const app = new Koa() 
const env = process.env.NODE_ENV;
const config = require('./config')
const router = require('./app/router').../* More configurations can be pulled to see the repository code */Copy the code


Boot Environment Configuration

PM2 configuration: pm2.config.js

let startFile = "./app.js"
module.exports = {
  apps: [{
    name: "prod",
    script: startFile,
    env: {
      "NODE_ENV": "production"}, {// Test environment name:"test",
    script: startFile,
    env: {
      "NODE_ENV": "test"}}, {// development environment name:"dev",
    script: startFile,
    env: {
      "NODE_ENV": "development"}}}]Copy the code

Environment parameters: /conf/config.*.js



/*conf.dev. Js */ const conf = {port: 3200, // Set base_URL according to your computer environment:' 'Mysql: {// mysql database host:'localhost',
    port: '3306',
    database: 'dev_db'// You can change the name of your database user:'root'// database login account you send to password:' '// Database login password I don't know your password charset:'UTF8mb4'
  }
}
module.exports = conf;

Copy the code

Js –only dev/prod/test, koA will determine the current operating environment based on the NODE_ENV we configured in pm2.config.js. And use different configuration ports and parameters in /config/index.js


Database Configuration

Configuration file path:
/db/mysql.js

const db = require("mysql");
const config = require('.. /config').mysql;
const client = function () {}
var pool = db.createPool({
  host: config.host,
  port: config.port,
  user: config.user,
  password: config.password,
  database: config.database,
  charset: 'UTF8mb4'
});
Copy the code


The routing configuration

Route configuration:
/router/index.js

/*router/index.js*/
const router = require('koa-router') ()let app = require('./v1.js'Router.use ()'/api/app', app.routes(), app.allowedMethods())
// vue historySet up the router. Get (The '*', async(ctx, next)=>{
  return await ctx.render('index', {})}) // returns the registered route module.exports = routerCopy the code


Database Model creation

ModelMainly to tell
sequelizeHow to map database tables,

sequelize.define(modelName, attributes, [options]) -> Modal
This instance method is used to define a newmodel(Model).modelEquivalent to a table in a database, this object cannot be instantiated through the constructor, but only through
sequelize.define()
or
sequelize.import()
Method to create

The second argument is to specify the column name and data type, which is more detailed if it is a primary key. The third parameter is the additional configuration

You can refer to the Chinese documentation for details about sequelize configuration

//eg:
/*models\sequelize-model\test.js*/
module.exports = function(sequelize, DataTypes) {
  return sequelize.define('test', {
    id: {
      type: DataTypes.INTEGER(11).UNSIGNED,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    nick_name: {
      type: DataTypes.INTEGER(11),
      allowNull: false
    },
  }, {
    tableName: 'test',
    timestamps: false
  });
};
Copy the code

If you create a new table or field in mysql, you need to update the corresponding field in the Model. There are plug-ins (middleware) that automatically map database table structures into the model, but the first time I used it I found some problems, so I didn’t use it.

/*mysql CREATE TABLE structure */ CREATE TABLE 'test` (
	`id` INT(11) NOT NULL AUTO_INCREMENT,
	`nick_name` VARCHAR(50) NULL DEFAULT ' ',
	PRIMARY KEY (`id`)
)
COLLATE='utf8mb4_general_ci'
ENGINE=MyISAM
AUTO_INCREMENT=5
;
Copy the code




Write interface!

The interface is written, and when we access the interface, it will be in

/router/v1To find the corresponding routing name, and then access our corresponding controller interface address, for business processing

router/v1Unified packaging interface mapping

/*router/v1 / const router = require('koa-router'// We can create different controllers according to different business modules. We can write the interfaces of the same module in the same controller and import them through this, for exampletest1
const test = require('.. /controller/test')
const test1 = require('.. /controller/test1') 
const test2 = require('.. /controller/test2') / / / / interface mapping interface to access the address http://localhost:port/api/app/test/// controller router.post(//controller router.post() //controller router.post() //controller router.post('/test',test.getTest)
router.post('/createData',test.createData)
//controller1
router.post('/test1'.test1. GetTest) // Controller and Service separate parts of router.post('/test2'.test2.getTest)
module.exports = router
Copy the code


Controller:
controller/*.js

/*controller/test.js*/
const models = require('.. /models')
const {
  joi,
  validateParams
} = require('.. /base/controller.js'Module.exports = {// Get database data async getTest(CTX){let data = {
      tip: 'If you install the database, you can open this comment.'
    }
    return ctx.output({data:data},'Obtain success',0)}, async createData(CTX){const schema = joi.object().keys({nick_name: joi.string().required() }) validateParams(ctx.input, schema)let nick_name = ctx.input.nick_name
    let parmas = {
      nick_name: nick_name
    }
    let res = await models.test.create(parmas)
    if(res){
      return ctx.output({},'Added successfully'} / /, 0)let data = {
    //   tip: 'If you install the database, you can open this comment.'/ / / /}return ctx.output({data:data},'Obtain success', 0)}}Copy the code


So far, after the above configuration and CV of the code, we can test the interface through Postman.


Controller The Controller and service layers are separated

When our business is more complex, we do not want to deal with the database logic together with our ordinary business logic, this time we can separate the database operation into one
serviceLayer, and then controller
controllerIt’s just processing our business logic

Specific operation: Create different service module files from the service folder, for example, ServiceTest2. js, and separate the test2 database operations from serviceTest2.js. This way we know exactly what our business layers are doing, and it’s easy to maintain.

/*app\controller\testConst serviceTest = require(const serviceTest = require();'.. /service/v1/serviceTest2.js'Module.exports = {// Get database data async getTest(CTX){let res = await serviceTest.getTest()
    return ctx.output({data:res},'Obtain success', 0)}}Copy the code

/*app\service\v1\serviceTest2.js*/
const models = require('.. /.. /models'Module.exports = {// Get database data async getTest(CTX){let res = await models.test.findOne({
      where: {
        id: 1
      }
    })
    let data = {
      name: res.dataValues.nick_name
    }
    // let data = {
    //   tip: 'Here's the thing that's pulled out of the controller to operate on the database, so if you have mysql installed, you can open the comments above'
    // }
    return data
  }
}

Copy the code

PM2 More operations

pm2 restart pm2.config.js --only dev/prop/test// Restart the PM2 servicelog// View log PM2kill// Kill the processCopy the code

The official document: https://pm2.keymetrics.io/docs/usage/quick-start/


Write in the last

  • The above article is the one I wrote in these two dayskoa2A set of code templates extracted from the project, as long as you clone the code and ensure that the required software has been installed on the computer, and can proceedkoa2Start the project and write the API.

  • This is an entry level simple sharing article, if there are mistakes, I hope you can help put forward correction, thank you very much.
  • If you think it is ok, I hope you can give me a star, thank you very much