zoukankan      html  css  js  c++  java
  • 用 Koa 提供 Restful service 和查询 MongoDB 的例子

    const path = require('path');
    
    const Koa = require('koa');
    const app = new Koa();
    const compose = require('koa-compose');
    const router = require('koa-router')();
    const bodyParser = require('koa-bodyparser');
    const static = require('koa-static');
    const static_root = static(path.join(__dirname + "/../client/dist")); // Point to the root of web app
    
    const MongoClient = require('mongodb').MongoClient;
    const DB_CONN_STR = 'mongodb://localhost:27017/sample';
    
    // Variable for storing query result
    var result = null;
    
    // ********************************** Koa part **********************************
    
    // Error handler
    const handler = async (ctx, next) => {
        try {
            await next();
        } catch (err) {
            ctx.response.status = err.statusCode || err.status || 500;
            ctx.response.type = 'html';
            ctx.response.body = '<h2>Something wrong, please contact administrator.</h2>';
            //    ctx.app.emit('error', err, ctx);
        }
    };
    
    // Logger
    const logger = async (ctx, next) => {
        console.log(`${ctx.request.method} ${ctx.request.url}`);
        await next();
    };
    
    const middlewares = compose([handler, bodyParser(), router.routes(), logger, static_root]);
    app.use(middlewares);
    
    // ********************************** DB part **********************************
    
    // Common function to connect mongoDB, and run the callback function
    var runDb = function (callback) {
        MongoClient.connect(DB_CONN_STR, function (err, db) {
            if (err) {
                console.log("Error: ", err);
                db.close();
                process.exit(1);
            } else {
                callback(db);
                db.close();
            }
        });
    }
    
    // Data for insert
    var data1 = [
        { "name": "AAA", "age": 1 },
        { "name": "BBB", "company": "Google Co." }
    ];
    
    // Insert function, just for testing
    var insertData = function (db) {
        db.collection("table1").insert(data1, function (err, result) {
            if (err) {
                console.log("Error: ", err);
                return;
            }
        });
    }
    
    // Query function
    var queryData = function (db) {
        db.collection("table1").find({}).toArray(function (err, docs) {
            if (err) {
                console.log("Error: ", err);
            } else {
                result = docs;
            }
        });
    }
    
    // Call the db to insert data
    runDb(insertData);
    
    // ********************************** Controller part **********************************
    
    // Redirect the root to Angular index.html
    router.get('/', async (ctx, next) => {
        ctx.response.redirect('/index.html');
    });
    
    // Just an api for testing
    router.get('/ui-api/hello/:name', async (ctx, next) => {
        // just for sample
        var name = ctx.params.name;
        ctx.response.body = `<h1>Hello, ${name}!</h1>`;
    });
    
    // Just an api for testing
    router.get('/ui-api/data', async (ctx, next) => {
        runDb(queryData);
        ctx.response.type = 'json';
        //    ctx.set("Access-Control-Allow-Origin", "*");    // Disable cross origin
        ctx.response.body = result;
    });
    
    // ********************************** Startup part **********************************
    
    let port = 80;
    app.listen(port);
    console.log('app started at port : ' + port);
  • 相关阅读:
    android原子
    android进程优先级
    Android 的cyclicBarrier
    android中运用CountDownLatch
    java网络编程长连接的问题
    https
    http 上传文件
    netty4 断线重连
    Linux下高并发socket最大连接数所受的各种限制
    Android Studio NDK及so文件开发
  • 原文地址:https://www.cnblogs.com/pekkle/p/7935942.html
Copyright © 2011-2022 走看看