lora-project/server-api/app.js

83 lines
2.2 KiB
JavaScript
Raw Normal View History

2017-06-01 08:32:42 +00:00
const koa = require('koa');
const path = require('path');
const fs = require('fs');
2017-06-02 14:53:34 +00:00
const mongoose = require('mongoose');
2017-06-01 08:32:42 +00:00
2017-06-01 10:09:25 +00:00
// Load config
const config = require('./config.json');
// custom modules
const mysql = require('./libs/mysql_pool');
2017-06-02 10:07:25 +00:00
const so = require('./libs/storeObject');
2017-06-05 06:41:32 +00:00
const mem = require('./libs/memcache_lib');
2017-06-01 10:09:25 +00:00
2017-06-05 06:41:32 +00:00
mem.host = 'dyn.trj.tw';
mem.port = 24002;
mem.connect();
2017-06-03 13:20:34 +00:00
2017-06-01 10:09:25 +00:00
// init mysql connection pool
mysql.database = config.db.mysql.dbname;
mysql.host = config.db.mysql.host;
mysql.user = config.db.mysql.user;
mysql.password = config.db.mysql.pass;
mysql.port = config.db.mysql.port;
mysql.createPool();
2017-06-02 14:53:34 +00:00
// init mongodb connection
let mongoAuth = `${config.db.mongo.user.length > 0 && config.db.mongo.pass.length > 0 ? `${config.db.mongo.user}:${config.db.mongo.pass}@` : ''}`;
let mongoUrl = `mongodb://${mongoAuth}${config.db.mongo.host}:${config.db.mongo.port}/${config.db.mongo.dbname}${mongoAuth.length > 0 ? '?authSource=admin': ''}`;
mongoose.connect(mongoUrl);
2017-06-01 08:32:42 +00:00
// Koa Middleware
const session = require('koa-session');
const Router = require('koa-router');
const koaBody = require('koa-body');
const koaStatic = require('koa-static');
const cors = require('kcors');
2017-06-01 14:37:51 +00:00
const logger = require('koa-morgan');
2017-06-01 08:32:42 +00:00
// Koa Main Application
const app = new koa();
2017-06-03 13:20:34 +00:00
const server = app.listen(config.port, () => {
2017-06-01 08:32:42 +00:00
console.log(`Server start on port ${server.address().port}`);
});
// Root Router
const router = new Router();
2017-06-01 14:37:51 +00:00
// set app keys
app.keys = ['44b4fa5cb8a394294361'];
// enable logger
2017-06-04 13:38:14 +00:00
app.use(logger('dev'));
2017-06-01 08:32:42 +00:00
// enable body parser
2017-06-01 14:37:51 +00:00
// app.use(koaBody({
// multipart: true,
// // upload file size 10mb
// maxFieldSize: 10 * 1024 * 1024
// }));
2017-06-01 08:32:42 +00:00
// enable cors
app.use(cors());
// enable session
app.use(session({
key: 'koa:sess',
maxAge: 86400000,
overwrite: true,
httpOnly: true,
signed: true
}, app));
2017-06-01 14:37:51 +00:00
// enable static file
app.use(koaStatic(path.resolve(__dirname, 'public')));
// enable router
2017-06-01 08:32:42 +00:00
app.use(router.routes());
app.use(router.allowedMethods());
2017-06-01 10:09:25 +00:00
// load other route
const api_route = require('./route/api');
// set other route
router.use("/api", api_route.routes());
2017-06-01 08:32:42 +00:00
router.get('/', async(c, n) => {
c.body = 'Get root';
});