Background:

Provides HTTP/HTTPS interface services for small programs to store user data and log data.

Technology selection

resitify

A pure HTTP service that does not involve views

Typescript 2.1 +

Type verification, specification code

mock.js

Providing mock services

mongodb

Document structure, storing data

rollup

Js management

node

Back-end service management

pm2

Back-end Node process management

Environment set up

Install the node

Node is installed by default and version V10.16.3 is in use.

Initialization engineering

{"name": "restify-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "Copy the code

Install dependencies

NPM install --save mongodb restify mockjs pm2Copy the code
## Install NPM I --save-dev rollup rollup-plugin-buble ## Install NPM I --save-dev rollup rollup-plugin-buble ## Install NPM I --save-dev rollup NPM I --save-dev rollup-plugin-typescript tslib installs the rollup-plugin-uglify ## install the rollup.js plugin to compile Typescript codeCopy the code

After installation package. Json

{" name ":" restify - demo ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" dev ": "rollup -c rollup.config.js", "start":"node dist/app.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies" : {" mockjs ":" ^ 1.1.0, "" mongo" : "^ we do", "pm2" : "^ 4.1.2", "restify" : "^ 8.4.0"}, "devDependencies" : {" rollup ":" ^ 1.27.2 ", "a rollup - plugin - buble" : "^ 0.19.8", "a rollup - plugin - typescript" : "^" 1.0.1, "rollup plugin - uglify" : "^ 6.0.3", "tslib" : "^ 1.10.0", "typescript" : "^ 3.7.2"}}Copy the code

Configure a rollup

touch rollup.config.js 

const path = require('path');
const buble = require('rollup-plugin-buble'); 
const typescript = require('rollup-plugin-typescript');

const resolveFile = function(filePath) {
  return path.join(__dirname, filePath)
}

module.exports = [
  {
    input: resolveFile('src/main.ts'),
    output: {
      file: resolveFile('dist/app.js'),
      format: 'cjs',
      name: 'restify-demo',
    }, 
    plugins: [
      typescript(),
      buble(),
    ],
  },
]Copy the code

Install the mongo

Download the mongo

# enter CD/usr/local/usr/local # download sudo curl - O https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-4.0.9.tgz # extract Sudo tar -zxvf mongodb-osx-ssl-x86_64-4.0.9. TGZ # rename mongodb to sudo mv mongodb-osx-x86_64-4.0.9/ mongodb export PATH=/usr/local/mongodb/bin:$PATHCopy the code

Add the mongo. Conf

# # log systemLog: log for the destination file: a file # file location path: / usr/local/var/log/mongo/mongo. Log # whether additional logAppend: Fork: true storage: dbPath: /usr/local/var/mongodb net: BindIp: 127.0.0.1 # port: 27017Copy the code

Running mongod

mongod --config /usr/local/etc/mongo.confCopy the code

Check mongo

> mongo mongo shell version v4.0.9 connecting to: mongo: / / 127.0.0.1:27017 /? gssapiServiceName=mongodb Implicit session: session { "id" : UUID(" 07aaf4A0-c188-4D50-9412-96a2b0625e8a ")} MongoDB server version: 4.0.9 Server has startup warnings: 2019-11-27T17:31:59.406+0800 I CONTROL [initandListen] 2019-11-27t17:31:59.407 +0800 I CONTROL [initandListen] ** WARNING: Access control is not enabled for the databa.2019-11-27T17:31:59.408 +0800 I control [initandListen] **Copy the code

hello-world

import restify from "restify";
import { Server } from "restify/lib/server";

function respond(req, res, next) {
  res.send('hello ' + req.params.name);
  next();
}

const server:Server = restify.createServer();
server.get('/hello/:name', respond);
server.head('/hello/:name', respond);

server.listen(8090, function() {
  console.log('%s listening at %s', server.name, server.url);
});Copy the code

Hello – world request

curl -is http://localhost:8090/hello/world -H 'accept: text/plain'Copy the code
HTTP/1.1 200 OK Server: restify content-type: text/plain content-length: 11 Date: Wed, 20 Nov 2019 05:35:12 GMT Connection: keep-alive hello worldCopy the code

Business practices

Depend on the introduction of

import restify from "restify";
import { Server } from "restify/lib/server";
import Mock from 'mockjs'
import { dbConnect } from "./utils";
const mongodb = require('mongodb');
const log4js = require('log4js');

const logger = log4js.getLogger();
const server:Server = restify.createServer();
//before route choose 
server.pre(restify.plugins.pre.userAgentConnection());
//after router choose ,before handler
server.use(restify.plugins.acceptParser(server.acceptable));
server.use(restify.plugins.queryParser({ mapParams: false }));
server.use(restify.plugins.bodyParser());Copy the code

Restify routing configuration

//set route server.post('/add', async function(req, res, next) { const desc = req.body.desc; let result = await create(desc); req.desc = {desc:'success',data:{ desc:result, numbrer:Mock.mock({ "number|1-100": 100 }) }}; return next(); }, function(req, res, next) { res.send(req.desc); return next(); }); server.get( '/all', async function(req, res, next) { let result = await fetchAll(); req.desc = result; return next(); }, function(req, res, next) { res.send(req.desc); return next(); })Copy the code

API Version support

function sendV1(req, res, next) { const mockNumber = Mock.mock({ "number|1-100": 100 }); res.send(`version number:${mockNumber} with param ${req.params.name}`); return next(); } function sendV2(req, res, next) { const mockNumber = Mock.mock({ "number|1-100": 100 }); res.send({ param: req.params.name,version: mockNumber}); return next(); } server. Get ('/version / : name, restify. Plugins. ConditionalHandler ([{version: '1.1.3', handler: sendV1}, {version: [' 2.0.0 ', '2.1.0', '2.2.0], handler: sendV2}]));Copy the code

Mongo operation

let db; // Get a DB connection when this module is loaded (function getDbConnection() { dbConnect().then((database) => { db = database; }).catch((err) => { logger.error('Error while initializing DB: ' + err.message, 'lists-dao-mongogb.getDbConnection()'); }); }) (); function create(description) { return new Promise((resolve, reject) => { let lists = db.collection('shoppingLists'); let listId = mongodb.ObjectId(); let whenCreated = Date.now(); let item = { _id: listId, id: listId, description: description, whenCreated: whenCreated, whenUpdated: null }; lists.insertOne(item, (err, result) => { if (err) { logger.error('Error occurred: ' + err.message, 'create()'); reject(err); } else { resolve({ data: { createdId: result.insertedId }, statusCode: 201 }); }}); }); } function fetchAll() { return new Promise((resolve, reject) => { let lists = db.collection('shoppingLists'); lists.find({}).toArray((err, documents) => { if (err) { logger.error('Error occurred: ' + err.message, 'fetchAll()'); reject(err); } else { logger.debug('Raw data: ' + JSON.stringify(documents), 'fetchAll()'); resolve({ data: JSON.stringify(documents), statusCode: (documents.length > 0) ? 200:404}); }}); }); }Copy the code

Db connection

const mongodb = require('mongodb'); const log4js = require('log4js'); const logger = log4js.getLogger(); // logger.level = 'debug'; let mongodbClient; let db; Const appSettings = {mongodb_url: 'mongo: / / 127.0.0.1:27017 /? gssapiServiceName=mongodb', mongodb_db_name:'mongoDemo', } function dbClose() { if (mongodbClient && mongodbClient.isConnected()) { mongodbClient.close(); } } export function dbConnect() { return new Promise((resolve, reject) => { if (db) { resolve(db); } else { mongodb.MongoClient.connect(appSettings.mongodb_url, function(err, client) { if (err) { logger.error('Error connecting to the MongoDB URL: ' + appSettings.mongodb_url); reject(err); } mongodbClient = client; db = mongodbClient.db(appSettings.mongodb_db_name); // Make sure connection closes when Node exits process.on('exit', (code) => { dbClose(); }) resolve(db); }); }}); }Copy the code

reference

restify

mongodb

rollup

mockJs

typescript plugin

typescript

Mongodb installation tutorial

Configuration mongo

By CheongHu, Chief Front-end Experiencer

Contact email: [email protected]