I. Environment construction

Docker /docker-compose install the mongodb database for docker/docker-compose (do not install docker/docker-compose for later deployment).

Initialize the project

Refer to the official documentation for this step. The specific commands are as follows:

// Create the project directoryCD egg-mongo // initializeThe framework for the NPM install copy code project is now set up, so let’s start the project

$NPM run dev $NPM run dev $localhost:7001 127.0.0.1 localhost, please make sure your host is correct copy code hi, egg, then egg project is basically set up.

Third, directory structure

Here is the initial directory structure:

Take a look at these documents:

The app directory is the most core, including controller, which mainly stores the code related to processing business logic. Router.js is the place to configure the browser routing address.

The config directory is configuration-specific and now has only config.default.js and pluin.js files.

Config.default. js is the file used to store the default configuration.

Pluin.js is where the plug-in is introduced, and after being exported here, the app directory is accessible.

The test directory holds the test code.

4. Add interfaces

Let’s use localhost:7001/users as an example to get the list of users:

In the Controller directory, add the user.js file, create a class UserController and inherit the controller from the egg.

// controller -> user.js
const Controller = require('egg').Controller

class UserController extends Controller {
    /** * Get the user list */
    getUserList() {
        const { ctx } = this;
        // Pretend to read data from the database
        const mockUsers = [
            { name: 'user1'.age: 18.sex: 'girl'.job: 'student' },
            { name: 'user2'.age: 19.sex: 'girl'.job: 'student' },
            { name: 'user3'.age: 20.sex: 'boy'.job: 'no job' },
        ]

        ctx.body = {
            code: 0.message: 'success'.data: mockUsers
        }
    }
}

module.exports = UserController;
Copy the code

Why copy code to inherit Controller? Because we’re going to use the EGG-wrapped CTX.

What is CTX? The egg encapsulates the HTPP request and response from the Node into the CTX of the controller.

const http = require('http')...// Send the HTTP header
// HTTP status: 200: OK
// The content type is text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

    // Send response data "Hello World"
response.end('Hello World\n');
Copy the code

Copy code can look at the framework API and source code, here is not detailed redundant.

Step 2 map the routing table. In router.js, add the route and put the method in it.

// app -> router.js
module.exports = app= >{... router.get('/', controller.home.index)
  router.get('/users', controller.user.getUserList) // @add This is what we added
}
Copy the code

Copy the code to restart the service and access localhost:7001/ Users to see the mockUsers data.

The third step is to write the Service. Some complex business logic is generally maintained in the Service. In the actual application, the Controller calls the Service, the Service calls db, and the Service returns the result to the Controller.

Create a service folder in the app directory and create a user.js file.

// service -> user.js
const Service = require('egg').Service

class UserSevice extends Service {
    /** * query all user */
    find() {
        // Not yet queried from database
        const mockUsers = [
            { name: 'user1'.age: 18.sex: 'girl'.job: 'student' },
            { name: 'user2'.age: 19.sex: 'girl'.job: 'student' },
            { name: 'user3'.age: 20.sex: 'boy'.job: 'no job'},]return Object.assign({}, {
            pageNum: 1.pageSize: 10.list: mockUsers
        })
    }
}

module.exports = UserSevice
Copy the code

Copy the code and change the getUserList method of user.js in Controller:

getUserList() {
		const { ctx } = this;
  	// Pretend to read data from the database
		const users = service.user.find()

  	ctx.body = {
    		code: 0.message: 'success'.data: users
  	}
}
Copy the code

The third step is to connect to mongodb using the egg-Mongoose library, so you don’t need to write your own connection to the database. This is also the library created by Egg and his family. For details, please click here.

Since we use this library, let’s install it first.

$NPM install egg-mongoose –save Copy the code and put the installed plug-in in pluin.js.

// config -> pluin.js
exports.mongoose = {
		enable: true.// Start the plug-in
		package: 'egg-mongoose'
}
Copy the code

Add two files: config.local.js and config.prod.js to the config directory and write the following code:

// config -> config.local.js
exports.mongoose = {
    client: {
        url: 'mongo: / / 127.0.0.1:27017 / egg - mongo'.options: {}
    }
}

exports.baseUrl = 'http://127.0.0.1:7001';

// config.prod.js is not used in the production environmentBefore copying code without using the link library, we wrote like this:// This code comes from runoob.com
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/runoob";
 
MongoClient.connect(url, { useNewUrlParser: true }, (err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});
Copy the code

Copying code doesn’t look elegant at all, but does egg-Mongoose feel refreshing by comparison 😉

Ok, so let’s write the Schema. Create model folder in app directory and create user.js file with user Schema as follows:

// model -> user.js
module.exports = app= > {
    const mongoose = app.mongoose
    const Schema = mongoose.Schema;
    // According to the mock data, there are four fields: name/age/sex/job lastTime to mark the last change time
    const UserSchema = new Schema({
        name: {
            type: String
        },
        age: {
            type: Number
        },
        sex: {
            type: String
        },
        job: {
            type: String
        },
        lastTime: {
            type: Number}})// map to the users table of the egg-mongo db library (case insensitive)
    const User = mongoose.model('Users', UserSchema)
    
    // put the init method here
		initUserData(User)
  
    return User
}

function initUserData() {}
Copy the code

To see the effect of the database connection, add an initUserData method:

/** * Initialize a test User * @param {Object} User */
function initUserData(User) {
  	// Query the database
    User.find({}, (err, doc) => {
        if (err) {
            console.log(err)
            console.log('init user failed')}else if(! doc.length) {new User({
                name: 'UserInitName'.age: 23.sex: 'girl'.job: Program girl.lastTime: Date.now()
            }).save()
        } else {
            console.log('-------------init user successfully--------------')}}}Copy the code

Copy the code to start the local mongo, which I installed on brew, and open a new command line:

/ / installation/usr/local/mongodb/bin $sudo mongod

$NPM run dev copying code see the output * * — — — — — — — — — — — — — the init user successfully — — — — — — — — — — — — — – * * means that our database is ready.

5. Modify the user.js find method under Service to async await the database.

// Service -> user.js
/** * query all user */
async find() {
    // Query from database
    const users = await this.ctx.model.User.find({})

    return Object.assign({}, {
        pageNum: 1.pageSize: 10.list: users
    })
}
Copy the code

Change the method in the copy code Controller as well:

// Controller -> user.js
/** * Get the user list */
async getUserList() {
    const { ctx, service} = this // Get the service from this
    const users = await service.user.find() 

    ctx.body = {
        code: 0.message: 'success'.data: users
    }
}
Copy the code

Copy the code and type localhost:7001/users in the browser to see the user in our init!

{
  code: 0.message: "success".data: {
    pageNum: 1.pageSize: 10.list: [{_id: "5d5663f5129df2088e8c6783".name: "UserInitName".age: 23.sex: "girl".job: "Program girl.".lastTime: 1565942773485.__v: 0}}}]Copy the code

Copy the code and a simple interface is done.

Five, the other

The above implementation of the interface is quite simple, did not do login judgment, did not do authentication, also did not according to pageNum pageSize search conditions to query, it can be said that the leakage of all ah.

But this example is just a primer, not an in-depth understanding.

Code address: github.com/SUH11/egg-m… .

Egg website: eggjs.org/zh-cn/intro… .

Original address:Juejin. Cn/post / 684490…