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);
  • 相关阅读:
    Hbase性能调优(一)
    文章标题
    JDBC的PreparedStatement启动事务使用批处理executeBatch()
    java.lang.OutOfMemoryError: PermGen space及其解决方法
    linux 关机命令总结
    oracle 启动关闭以及监听启动关闭命令
    bash: sqlplus: command not found 解决方法
    VMware 虚拟机 linux执行 ifconfig 命令 eth0没有IP地址(intet addr、Bcast、Mask) UP BROADCAST MULTICAST 问题
    Linux的文本编辑和文本内容查看命令
    RHEL6服务器网络配置 修改linux RHEL6系统下的ip方法
  • 原文地址:https://www.cnblogs.com/pekkle/p/7935942.html
Copyright © 2011-2022 走看看