The Koa documentation is so minimal that, although every API is explained, it is hard to organize and apply it, making it unfriendly for beginners. Many people write all the interfaces, logic, configuration and so on in app.js for their first Koa project. Although it works perfectly, it has poor readability and maintainability, so a good directory structure is particularly important

Koa from zero to Api implementation – Project construction

What is Koa?

Koa is a new Web framework, built by the same people behind Express, that aims to be a smaller, more expressive, and more robust cornerstone of web application and API development. By making use of async functions, Koa helps you discard callback functions and greatly enhances error handling. Koa does not bundle any middleware, but rather provides an elegant way to help you write server-side applications quickly and happily.

Koa vs Express

Koa uses Promises and Async functions to get rid of the application of callback hell and simplify error handling. It exposes itself as ctx.request and CTx. Response objects rather than node req and RES objects. Express, on the other hand, extends node REq and RES objects with other properties and methods, and includes many other “framework” functions, such as routing and templates, that Koa does not have.

Therefore, if you want to get closer to Node.js and traditional Node.js style coding, you may want to stick with Connect/Express or a similar framework. If you want to get rid of callbacks, use Koa.

conclusion

Koa is a much leaner middleware framework than Express that uses node’s new features and is a much larger framework than Express was before

  • If you like diy and are trendy, consider Koa, which has plenty of extensions and middleware and is easy to write yourself
  • If you want to keep things simple and find a framework that does everything, start with Express

If you are interested in learning more about the differences, please visit Koa VS Express

Koa project construction

Note that this tutorial is intended for users with some experience with Koa. If you are not familiar with Koa, please look at the following document Koa Chinese document

The Koa documentation is so minimal that, although every API is explained, it is hard to organize and apply it, making it unfriendly for beginners.

In the author’s first Koa project, all the interfaces, logic and configuration were written in app.js. Although it ran perfectly, the readability and maintainability were very poor, so a good directory structure was particularly important

The directory to create

  • The config – configuration
  • Models – Database Model (ROM)
  • Controller – Controller
  • Middlewares – Middleware
  • Public – Static resource
  • Service – service
  • The router routing –
  • App.js – Startup file

Depend on the installation

Once the project directory is created we need to install some dependencies that we can use

  • Babel-core /babel-preset- PRESET – ES2015 – Presets nodeJs to support ES6 modules
  • koa – koa2
  • Koa-body-request body parsing
  • Koa-cache-control – Cache control
  • koa-compress – gzip
  • Koa – cors – cross domain
  • Koa – logger – log
  • Koa-onerror – Error handling
  • Koa – the router – routing
  • koa-session – session
  • Koa -static – Static resource service
  • Koa – helmet – security
  • Md5-md5 encryption
  • Mkdirp – Create directories recursively

You can choose according to your needs, but some dependencies must be installed

  • koa – koa2
  • Koa-body-request body parsing
  • Koa – the router – routing

The following sections explain what each plug-in does and how to use it.

Directory,

config

Config is our configuration file, for example:

  • Database (mysql, Oracle, Redis, etc.)
  • OSS
  • .

Practical application:

  • confirg
    • Database. Config. Js (new)

database.config.js


export default {
  database: ' '.username: ' '.password: ' '.dialect: ' '.host: ' '.port: 3306
}
Copy the code

Detailed configuration will be explained to you in detail.

models

The Models folder is mainly our database model (ORM) and stores database mapping files, eg:

  • models
    • Index.js – entry file
    • User.js – corresponds to the user table in the database

index.js

import Sequelize from 'sequelize'
import config from '.. /config/database.config'
const sequelize = new Sequelize(config)
export const user = sequelize.import(__dirname + '/user')
export default {
 user,
 sequelize
}
Copy the code

The following serial numbers represent line numbers:

  1. Introduce Sequelize, which is an ORM framework and its use will be explained in more detail later
  2. Import the database configuration file we created in config earlier
  3. Connect to the database using Sequelize
  4. Export the local database mapping file for our use

controller

Controller is the control layer that handles external requests. The service layer is called, and the content returned by the service is consolidated and returned to the caller

For example:

const user = require('.. /service/user')
const findAllUser = async (ctx) => {
  const data = ctx.request.body
  const result = await user.findAllUser(data)
  ctx.body =  send({data: result})
}
module.exports = {
  findAllUser
}
Copy the code

The following serial numbers represent line numbers:

  1. Get request body
  2. Call the service layer
  3. Returns the content returned by the Service to the caller (send is a custom data formatter)

service

As a service layer, service mainly does business logic processing, data processing, etc., and returns the results to the Controller layer

For example:

const db = require('.. /models/')
const findAllUser = async() = > {const result = await db.user.findAll()
  return result
}
module.exports = {
  findAllUser
}

Copy the code

The following serial numbers represent line numbers:

  1. Get the database mapping file because you want to manipulate the database
  2. Search all users from the database (db.user.findAll() is the query method provided in sequelize)
  3. Back to the controller

routers

Router manages our routes, which are the interface addresses

For example:

const user = require('.. /controller/user')
const koa_router = require('koa-router');
const router = koa_router();
router.post('/findAll', user.findAllUser)
module.exports = router
Copy the code

The following serial numbers represent line numbers:

  1. The introduction of the controller layer
  2. Define interface type, address, call method (POST, ‘/findAll’, findAllUser)

app.js

App.js is our entry file and main file, where we import the route configured in the router

const
  koaBody = require('koa-body')
  Koa = require('koa'),
  Router = require('koa-router')
  router = new Router()

const user = require('./routers/user');
router.use("/user",user.routes());
Copy the code

This gives us access to the: IP :port/user/findAll interface.