Noejs implements restful API

Posted by stevenrhiggins on Sun, 09 Jun 2019 00:51:31 +0200

This paper focuses on the design and implementation of restful interface, using express and monogoose.
Click on the express tutorial
Click on the monogoose tutorial
ES6 Introduction Course - Ruan Yifeng's blog

Noe4.x support for ES6 is not perfect and a higher version of node is recommended.
In practical development, add'use strict'to the header of the file to declare that strict mode is used.
To help better understand later code, let's first learn about ES6 classes and inheritance

Classes and Inheritance of ES6

1. Definition and use

//Define a base class
class BaseService{
    add(){
        console.log('base add');// base add
    }
    remove(){
        console.log('base remove') // base remove
    }
}
//instantiation
var base = new BaseService();
base.add(); //Output'base add'

2. Inheritance

//Methods of overloaded base classes
//Adding private methods
class UserServie extends BaseService{
    add(){
    console.log('user add');// user add
    }
    findTop5(){
        console.log('1,2,3,4,5');// 1,2,3,4,5
    }
}

Module of node

Next, learn about the modules in node. If you want to use ES6 modules, you need to use babel extra.

1. Derived base classes
New baseService.js

class Service{
    add(){
        console.log('base add');// base add
    }
    remove(){
        console.log('base remove') // base remove
    }
}
exports.service = Service;

2. Reference to base classes in subclasses
New userService.js

var baseService = require('./baseService').service;
class Service extends baseService{
    findTop5(){
        console.log('1,2,3,4,5');// 1,2,3,4,5
    }
    add(){
        console.log('user add');// user add
    }
}
exports.service = Service;

Building Project Structure

Next, monogoose and express technologies will be used. If you don't understand them, you can see the link at the top of this article.
1. Add the models folder and services folder after initializing the project with express
Create a new userModel.js in the models folder

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var model = new Schema({
     name:String
});
exports.model = mongoose.model('userModel', model);

Create a new baseService.js in the services folder

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
class Service{
    constructor(){
    }
    add(obj, name,callback){
        var name = name || '';
        var result = {};    
        var instance = this.entity(obj);
        instance.save(function(err, item, numAffected) {
            if (err) {
                result = { 'ok': false, 'data': {}, 'message': 'Newly added' + name + 'fail' }
            } else {
                result = { 'ok': true, 'data': item, 'message': 'Newly added' + name + 'Success' }
            }
            callback(result);        
        });
    }
    delete(obj, name,callback){
        var result = {};
        var id = obj.id;    
        this.entity.remove({ '_id': id }, function(err) {
            if (err) {
                result = { 'ok': false, 'data': {}, 'message': 'delete' + name + 'fail' };
            } else {
                result = { 'ok': true, "data": {}, 'message': 'delete' + name + 'Success' };
            }
            callback(result);
        });   
    }
}
exports.service = Service;

Then create a new userService.js, refer to the corresponding model, and implement the inheritance of userService to baseService

var baseService = require('./baseService').service;
var mongoose     = require('mongoose');
var Schema        = mongoose.Schema;
var model         = require('../models/userModel').model;
class Service extends baseService{
    constructor(){
        super();
        this.entity = model;
    }        
}
exports.service = Service;

In userService.js, we can override the methods of base classes, or add our own private methods and attributes.
As mentioned above, let's get familiar with it again.
If you want to call this in a subclass, you need to call the super method first, otherwise you will report an error when you create a new instance. This is because the subclass does not have its own this object, but inherits the parent's this object and processes it. If you don't call the super method, the subclass won't get this object.

class Service extends baseService{
    constructor(){
        super();
        this.entity = model;
    }    
    add(){
        console.log('user add');
    }
    findTop5(){
        console.log('1,2,3,4,5');
    }
}

Next, create a new service. JS file to unify the export service. The following code is the code in the actual project, just for reference.

exports.userService               = require('./userService').service;
exports.emptyService              = require('./emptyService').service;
exports.themeService              = require('./themeService').service;
exports.documentService           = require('./documentService').service;
exports.chartTypeService          = require('./chartTypeService').service;
exports.mapTypeService            = require('./mapTypeService').service;
exports.pageService               = require('./pageService').service;
exports.cellService                = require('./cellService').service;
exports.defaultEchartTypeService = require('./defaultEchartTypeService').service;
exports.defaultMapTypeService    = require('./defaultMapTypeService').service;
exports.issueService             = require('./issueService').service;

Finally, we routed the new api.js file in the routes folder

var express  = require('express');
var router   = express.Router();
var Services = require('../services/services');
mongoose.connect('mongodb://localhost/test');
/* 
    listen all
    name    Name
    method  Method
    par     parameter
    entity  Entity examples
    service Service instances
    result  Return results
    obj     Request parameters
    Call empty when parameter is empty or error
    Preventing program crash
 */
router.post('/:name?/:method?/:par?',function(req,res,next){         
    var name    = req.params.name || 'empty';      
    var method  = req.params.method || 'empty'; 
    var par     = req.params.par || '';          
    var service = new Services[name+'Service']();          
    var obj     = req.body || {};                
    obj.par     = par;                
    if(!Services[name+'Service']){
        service = new Services.emptyService();
    }            
    service[method](obj,name,function(result){        
        res.json(result);   
    });        
    return; 
});
module.exports = router;

In the code, we refer to Services.
First, the corresponding service is instantiated through new Services[name+'Service']().
Then call the service[method] method.
Where: name?,: method?,: par?? is the placeholder
In the front-end page, we can use the typical method of $. post('/api/user/add',data,function(){}) to test whether the API works properly. The author prefers to put all the parameters in data.
If you have questions or doubts, you can send them to us by email. http_wenwen@163.com

Topics: Javascript Mongoose MongoDB JSON