Source address stamp here

Ps: GitHub above the source directly linked to my own cloud database, can temporarily provide partners debugging and use.

For details about how to install mongodb on a MAC, see the following section: MAC Install mongdb-chendong_ blog – CSDN blog



1. Use KOA-Generator to generate koA2 projects

1.1 Installing the KOA-Generator globally

npm install -g koa-generatorCopy the code
1.2 Using commands to generate the basic project directory

koa2 hello-koa2-mongodbCopy the code

1.3 After the project is successfully created, go to the project directory and install the dependency

cd hello-koa2-mongodb && npm installCopy the code

1.4 Run commands to preview

npm startCopy the code
Open your browser http://localhost:3000/

2. Directory structure

Because today’s projects are almost always separated from the front and back ends, I only write frameworks with no templates. Then we need to modify the directory structure. The detailed code can be found here

Config: Some common configurations, such as the database address

Controller: indicates the controller layer

Mongo dbHelper: link

Error: implements unified exception handling

Middleware: Any of various pieces of middleware

Model: the entity class

Router: Router information (API interface address)

Utils: Various utility classes



3. Code implementation

Koa reference files in the project are to use the require, to get accustomed to using the import keyword friend can solve like this: in the project to introduce the Babel – plugin – add – the module – exports and Babel – register

npm install babel-plugin-add-module-exports babel-register --save-devCopy the code
Create a.babelrc file in the root directory

{
  "presets": ["es2015"."stage-3"]."plugins": ["add-module-exports"]}Copy the code
Require (‘babel-register’) in the entry file



3.1 Entry file: SRC /app.js


3.2 Settings such as connecting to mongodb: SRC /config/index.js


API address: SRC /router/index.js


3.4 Controller Controller

Class is used here, and function is used here as well



3.5 the model entity


You can configure Mongoose to automatically update createTime and updateTime

4 Unified exception handling

If you write Java, you know that uniform exception handling is very necessary



Apierrornames. js Defines the exception code


Apierror.js implements uniform exception handling

Note: Why not use class, because if you use Babel, class will compile to ES5, making instanceof uselessCopy the code


5 JWT validation

  1. Using jsonwebtoken library
NPM I jsonWebToken // a package that implements JWTCopy the code
Implement a JWT validation middleware yourself (you can also use KOA-JWT directly)


Add verify to any interface that needs to be verified



Ps: If you are careful, you may notice that there is no service layer. [smirk] [smirk]