abandon global var and use import yapi method

This commit is contained in:
suxiaoxin 2017-07-04 16:43:07 +08:00
parent 9d64f0cd36
commit 7964c4424b
17 changed files with 472 additions and 182 deletions

View File

@ -1,3 +1,3 @@
{
"watch": ["lib/"]
"watch": ["server_dist/"]
}

View File

@ -1,22 +1,38 @@
import yapi from './yapi.js';
import commons from './utils/commons';
yapi.commons = commons;
import dbModule from './utils/db.js';
import Koa from 'koa'
import convert from 'koa-convert'
import koaStatic from 'koa-static'
import bodyParser from 'koa-bodyparser'
import router from './router.js'
const app = new Koa()
app.use(bodyParser())
app.use(router.routes())
app.use(router.allowedMethods())
app.use(koaStatic(
yapi.path.join(yapi.WEBROOT, 'static')
))
app.listen(yapi.WEBCONFIG.port)
commons.log(`the server is start at port ${yapi.WEBCONFIG.port}`)
yapi.fs.ensureDirSync(yapi.WEBROOT_RUNTIME);
yapi.fs.ensureDirSync(yapi.WEBROOT_LOG);
dbModule.connect()
import path from 'path'
import init from'./init.js'
import fs from 'fs-extra'
import prdConfig from './config.json'
import devConfig from './config.dev.json'
let args = process.argv.splice(2);
let isDev = args[0] === 'dev' ? true : false;
const config = isDev ? devConfig : prdConfig;
global.WEBROOT = path.resolve(__dirname, '..');
global.WEBROOT_SERVER = __dirname;
global.WEBROOT_RUNTIME = path.join(WEBROOT, 'runtime');
global.WEBROOT_LOG = path.join(WEBROOT_RUNTIME, 'log');
global.WEBCONFIG = config;
init();

View File

@ -0,0 +1,43 @@
import groupModel from '../models/group.js'
import yapi from '../yapi.js'
module.exports = {
async add(ctx) {
let params = ctx.request.body;
if(!params.group_name){
return ctx.body = yapi.commons.resReturn(null, 400, 'Group不能为空');
}
var checkRepeat = await groupModel.checkRepeat(params.group_name);
// if(checkRepeat > 0){
// return ctx.body = yapi.commons.resReturn(null, 401, 'group已存在');
// }
let data = {
group_name: params.group_name,
group_desc: params.group_desc,
uid: '0',
add_time: yapi.commons.time(),
up_time: yapi.commons.time()
}
try{
let result = await groupModel.save(data);
result = yapi.commons.fieldSelect(result, ['_id', 'group_name', 'group_desc', 'uid'])
ctx.body = yapi.commons.resReturn(result)
}catch(e){
ctx.body = yapi.commons.resReturn(null, 402, e.message)
}
},
async list(ctx) {
console.log(yapi)
ctx.body = 1;
},
async del(ctx){
},
async up(ctx){
}
}

View File

@ -1,37 +0,0 @@
import path from 'path'
import commons from './utils/commons.js'
import fs from 'fs-extra'
import mongoose from 'mongoose'
import db from './utils/db.js'
import Koa from 'koa'
import convert from 'koa-convert'
import koaStatic from 'koa-static'
import bodyParser from 'koa-bodyparser'
import router from './router.js'
function runSever(){
const app = new Koa()
app.use(bodyParser())
app.use(koaStatic(
path.join(WEBROOT,'static')
))
app.use(router.routes())
app.use(router.allowedMethods())
app.listen( WEBCONFIG.port )
commons.log(`the server is start at port ${WEBCONFIG.port}`)
}
module.exports = ()=>{
global.yapi = {
db: mongoose,
commons: commons,
fs: fs,
path: path
}
fs.ensureDirSync(WEBROOT_RUNTIME);
fs.ensureDirSync(WEBROOT_LOG);
db();
runSever();
}

33
server/models/group.js Normal file
View File

@ -0,0 +1,33 @@
import yapi from '../yapi.js'
const groupSchema = ({
uid: String,
group_name: String,
group_desc: String,
add_time: Number,
up_time: Number
})
var groupModel = yapi.db('group', groupSchema);
function save(data){
let m = new groupModel(data);
return m.save();
}
function checkRepeat(name){
return groupModel.count({
group_name: name
})
}
function list(){
return groupModel.list().exec()
}
module.exports = {
save: save,
checkRepeat: checkRepeat,
list: list
}

View File

@ -1,17 +1,20 @@
import koaRouter from 'koa-router'
import interfaceController from './controllers/interface'
import koaRouter from 'koa-router'
import interfaceController from './controllers/interface.js'
import groupController from './controllers/group.js'
let router = koaRouter();
const router = koaRouter();
const interface_PREFIX = {
const INTERFACE_PREFIX = {
interface: '/interface/',
user: '/user/'
user: '/user/',
group: '/group/'
};
router.get ( interface_PREFIX.interface + 'add', interfaceController.add)
.get ( interface_PREFIX.interface + 'list', interfaceController.list)
router.post ( INTERFACE_PREFIX.interface + 'add', interfaceController.add)
.get ( INTERFACE_PREFIX.interface + 'list', interfaceController.list)
.get ( INTERFACE_PREFIX.group + 'list', groupController.list)
.post ( INTERFACE_PREFIX.group + 'add', groupController.add)
.post ( INTERFACE_PREFIX.group + 'up', groupController.up)
.post ( INTERFACE_PREFIX.group + 'del', groupController.del)
module.exports = router

View File

@ -1,6 +1,7 @@
import fs from 'fs-extra'
import path from 'path'
import yapi from '../yapi.js'
exports.resReturn = (data, num, errmsg)=> {
num = num || 0;
@ -32,7 +33,7 @@ exports.log = (msg, type) => {
let year = date.getFullYear();
let month = date.getMonth();
let logfile = path.join(WEBROOT_LOG, year + '-' + month + '.log');
let logfile = path.join(yapi.WEBROOT_LOG, year + '-' + month + '.log');
if(typeof msg === 'object'){
if(msg instanceof Error) msg = msg.message;
@ -55,3 +56,15 @@ exports.fileExist = (filePath) =>{
}
}
exports.time = () => {
return Date.parse(new Date())/1000;
}
exports.fieldSelect = (data, field)=>{
if(!data || !field || !Array.isArray(field)) return null;
var arr = {};
field.forEach( (f) => {
data[f] && (arr[f] = data[f]);
} )
return arr;
}

View File

@ -1,29 +1,42 @@
import path from 'path'
import mongoose from 'mongoose'
import {fileExist, log} from './commons.js'
import yapi from '../yapi.js'
function model(model, schema){
return mongoose.model(model, schema, model)
}
function init(){
function connect(){
mongoose.Promise = global.Promise;
let config = WEBCONFIG;
let config = yapi.WEBCONFIG;
let db = mongoose.connect(`mongodb://${config.db.servername}:${config.db.port}/${config.db.DATABASE}`);
db.then(function (res) {
log('mongodb load success...')
yapi.commons.log('mongodb load success...')
}, function (err) {
log(err, 'Mongo connect error');
yapi.commons.log(err, 'Mongo connect error');
})
checkDatabase();
return db;
}
function checkDatabase(){
let exist = fileExist(path.join(WEBROOT_RUNTIME, 'init.lock'))
let exist = yapi.commons.fileExist(yapi.path.join(yapi.WEBROOT_RUNTIME, 'init.lock'))
if(!exist){
log('lock is not exist')
yapi.commons.log('lock is not exist')
}
}
export default init;
yapi.db = model;
module.exports = {
model: model,
connect: connect
};

23
server/yapi.js Normal file
View File

@ -0,0 +1,23 @@
import path from 'path'
import fs from 'fs-extra'
import prdConfig from './config.json'
import devConfig from './config.dev.json'
let args = process.argv.splice(2);
let isDev = args[0] === 'dev' ? true : false;
const config = isDev ? devConfig : prdConfig;
const WEBROOT = path.resolve(__dirname, '..');
const WEBROOT_SERVER = __dirname;
const WEBROOT_RUNTIME = path.join(WEBROOT, 'runtime');
const WEBROOT_LOG = path.join(WEBROOT_RUNTIME, 'log');
const WEBCONFIG = config;
module.exports = {
fs: fs,
path: path,
WEBROOT: WEBROOT,
WEBROOT_SERVER: WEBROOT_SERVER,
WEBROOT_RUNTIME: WEBROOT_RUNTIME,
WEBROOT_LOG: WEBROOT_LOG,
WEBCONFIG: WEBCONFIG,
}

View File

@ -1,35 +1,49 @@
'use strict';
var _path = require('path');
var _yapi = require('./yapi.js');
var _path2 = _interopRequireDefault(_path);
var _yapi2 = _interopRequireDefault(_yapi);
var _init = require('./init.js');
var _commons = require('./utils/commons');
var _init2 = _interopRequireDefault(_init);
var _commons2 = _interopRequireDefault(_commons);
var _fsExtra = require('fs-extra');
var _db = require('./utils/db.js');
var _fsExtra2 = _interopRequireDefault(_fsExtra);
var _db2 = _interopRequireDefault(_db);
var _config = require('./config.json');
var _koa = require('koa');
var _config2 = _interopRequireDefault(_config);
var _koa2 = _interopRequireDefault(_koa);
var _configDev = require('./config.dev.json');
var _koaConvert = require('koa-convert');
var _configDev2 = _interopRequireDefault(_configDev);
var _koaConvert2 = _interopRequireDefault(_koaConvert);
var _koaStatic = require('koa-static');
var _koaStatic2 = _interopRequireDefault(_koaStatic);
var _koaBodyparser = require('koa-bodyparser');
var _koaBodyparser2 = _interopRequireDefault(_koaBodyparser);
var _router = require('./router.js');
var _router2 = _interopRequireDefault(_router);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var args = process.argv.splice(2);
var isDev = args[0] === 'dev' ? true : false;
var config = isDev ? _configDev2.default : _config2.default;
_yapi2.default.commons = _commons2.default;
global.WEBROOT = _path2.default.resolve(__dirname, '..');
global.WEBROOT_SERVER = __dirname;
global.WEBROOT_RUNTIME = _path2.default.join(WEBROOT, 'runtime');
global.WEBROOT_LOG = _path2.default.join(WEBROOT_RUNTIME, 'log');
global.WEBCONFIG = config;
var app = new _koa2.default();
app.use((0, _koaBodyparser2.default)());
app.use(_router2.default.routes());
app.use(_router2.default.allowedMethods());
app.use((0, _koaStatic2.default)(_yapi2.default.path.join(_yapi2.default.WEBROOT, 'static')));
app.listen(_yapi2.default.WEBCONFIG.port);
_commons2.default.log('the server is start at port ' + _yapi2.default.WEBCONFIG.port);
(0, _init2.default)();
_yapi2.default.fs.ensureDirSync(_yapi2.default.WEBROOT_RUNTIME);
_yapi2.default.fs.ensureDirSync(_yapi2.default.WEBROOT_LOG);
_db2.default.connect();

View File

@ -0,0 +1,132 @@
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _group = require('../models/group.js');
var _group2 = _interopRequireDefault(_group);
var _yapi = require('../yapi.js');
var _yapi2 = _interopRequireDefault(_yapi);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = {
add: function add(ctx) {
var _this = this;
return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {
var params, checkRepeat, data, result;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
params = ctx.request.body;
if (params.group_name) {
_context.next = 3;
break;
}
return _context.abrupt('return', ctx.body = _yapi2.default.commons.resReturn(null, 400, 'Group不能为空'));
case 3:
_context.next = 5;
return _group2.default.checkRepeat(params.group_name);
case 5:
checkRepeat = _context.sent;
// if(checkRepeat > 0){
// return ctx.body = yapi.commons.resReturn(null, 401, 'group已存在');
// }
data = {
group_name: params.group_name,
group_desc: params.group_desc,
uid: '0',
add_time: _yapi2.default.commons.time(),
up_time: _yapi2.default.commons.time()
};
_context.prev = 7;
_context.next = 10;
return _group2.default.save(data);
case 10:
result = _context.sent;
result = _yapi2.default.commons.fieldSelect(result, ['_id', 'group_name', 'group_desc', 'uid']);
ctx.body = _yapi2.default.commons.resReturn(result);
_context.next = 18;
break;
case 15:
_context.prev = 15;
_context.t0 = _context['catch'](7);
ctx.body = _yapi2.default.commons.resReturn(null, 402, _context.t0.message);
case 18:
case 'end':
return _context.stop();
}
}
}, _callee, _this, [[7, 15]]);
}))();
},
list: function list(ctx) {
var _this2 = this;
return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2() {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
console.log(_yapi2.default);
ctx.body = 1;
case 2:
case 'end':
return _context2.stop();
}
}
}, _callee2, _this2);
}))();
},
del: function del(ctx) {
var _this3 = this;
return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee3() {
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
case 'end':
return _context3.stop();
}
}
}, _callee3, _this3);
}))();
},
up: function up(ctx) {
var _this4 = this;
return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee4() {
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
case 'end':
return _context4.stop();
}
}
}, _callee4, _this4);
}))();
}
};

View File

@ -1,66 +0,0 @@
'use strict';
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _commons = require('./utils/commons.js');
var _commons2 = _interopRequireDefault(_commons);
var _fsExtra = require('fs-extra');
var _fsExtra2 = _interopRequireDefault(_fsExtra);
var _mongoose = require('mongoose');
var _mongoose2 = _interopRequireDefault(_mongoose);
var _db = require('./utils/db.js');
var _db2 = _interopRequireDefault(_db);
var _koa = require('koa');
var _koa2 = _interopRequireDefault(_koa);
var _koaConvert = require('koa-convert');
var _koaConvert2 = _interopRequireDefault(_koaConvert);
var _koaStatic = require('koa-static');
var _koaStatic2 = _interopRequireDefault(_koaStatic);
var _koaBodyparser = require('koa-bodyparser');
var _koaBodyparser2 = _interopRequireDefault(_koaBodyparser);
var _router = require('./router.js');
var _router2 = _interopRequireDefault(_router);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function runSever() {
var app = new _koa2.default();
app.use((0, _koaBodyparser2.default)());
app.use((0, _koaStatic2.default)(_path2.default.join(WEBROOT, 'static')));
app.use(_router2.default.routes());
app.use(_router2.default.allowedMethods());
app.listen(WEBCONFIG.port);
_commons2.default.log('the server is start at port ' + WEBCONFIG.port);
}
module.exports = function () {
global.yapi = {
db: _mongoose2.default,
commons: _commons2.default,
fs: _fsExtra2.default,
path: _path2.default
};
_fsExtra2.default.ensureDirSync(WEBROOT_RUNTIME);
_fsExtra2.default.ensureDirSync(WEBROOT_LOG);
(0, _db2.default)();
runSever();
};

View File

@ -0,0 +1,38 @@
'use strict';
var _yapi = require('../yapi.js');
var _yapi2 = _interopRequireDefault(_yapi);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var groupSchema = {
uid: String,
group_name: String,
group_desc: String,
add_time: Number,
up_time: Number
};
var groupModel = _yapi2.default.db('group', groupSchema);
function save(data) {
var m = new groupModel(data);
return m.save();
}
function checkRepeat(name) {
return groupModel.count({
group_name: name
});
}
function list() {
return groupModel.list().exec();
}
module.exports = {
save: save,
checkRepeat: checkRepeat,
list: list
};

View File

@ -4,19 +4,24 @@ var _koaRouter = require('koa-router');
var _koaRouter2 = _interopRequireDefault(_koaRouter);
var _interface = require('./controllers/interface');
var _interface = require('./controllers/interface.js');
var _interface2 = _interopRequireDefault(_interface);
var _group = require('./controllers/group.js');
var _group2 = _interopRequireDefault(_group);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var router = (0, _koaRouter2.default)();
var interface_PREFIX = {
interface: '/interface/',
user: '/user/'
var INTERFACE_PREFIX = {
interface: '/interface/',
user: '/user/',
group: '/group/'
};
router.get(interface_PREFIX.interface + 'add', _interface2.default.add).get(interface_PREFIX.interface + 'list', _interface2.default.list);
router.post(INTERFACE_PREFIX.interface + 'add', _interface2.default.add).get(INTERFACE_PREFIX.interface + 'list', _interface2.default.list).get(INTERFACE_PREFIX.group + 'list', _group2.default.list).post(INTERFACE_PREFIX.group + 'add', _group2.default.add).post(INTERFACE_PREFIX.group + 'up', _group2.default.up).post(INTERFACE_PREFIX.group + 'del', _group2.default.del);
module.exports = router;

View File

@ -16,6 +16,10 @@ var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _yapi = require('../yapi.js');
var _yapi2 = _interopRequireDefault(_yapi);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.resReturn = function (data, num, errmsg) {
@ -52,7 +56,7 @@ exports.log = function (msg, type) {
var year = date.getFullYear();
var month = date.getMonth();
var logfile = _path2.default.join(WEBROOT_LOG, year + '-' + month + '.log');
var logfile = _path2.default.join(_yapi2.default.WEBROOT_LOG, year + '-' + month + '.log');
if ((typeof msg === 'undefined' ? 'undefined' : (0, _typeof3.default)(msg)) === 'object') {
if (msg instanceof Error) msg = msg.message;else msg = (0, _stringify2.default)(msg);
@ -69,4 +73,17 @@ exports.fileExist = function (filePath) {
} catch (err) {
return false;
}
};
exports.time = function () {
return Date.parse(new Date()) / 1000;
};
exports.fieldSelect = function (data, field) {
if (!data || !field || !Array.isArray(field)) return null;
var arr = {};
field.forEach(function (f) {
data[f] && (arr[f] = data[f]);
});
return arr;
};

View File

@ -1,30 +1,29 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _mongoose = require('mongoose');
var _mongoose2 = _interopRequireDefault(_mongoose);
var _commons = require('./commons.js');
var _yapi = require('../yapi.js');
var _yapi2 = _interopRequireDefault(_yapi);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function init() {
function model(model, schema) {
return _mongoose2.default.model(model, schema, model);
}
function connect() {
_mongoose2.default.Promise = global.Promise;
var config = WEBCONFIG;
var config = _yapi2.default.WEBCONFIG;
var db = _mongoose2.default.connect('mongodb://' + config.db.servername + ':' + config.db.port + '/' + config.db.DATABASE);
db.then(function (res) {
(0, _commons.log)('mongodb load success...');
_yapi2.default.commons.log('mongodb load success...');
}, function (err) {
(0, _commons.log)(err, 'Mongo connect error');
_yapi2.default.commons.log(err, 'Mongo connect error');
});
checkDatabase();
@ -32,10 +31,15 @@ function init() {
}
function checkDatabase() {
var exist = (0, _commons.fileExist)(_path2.default.join(WEBROOT_RUNTIME, 'init.lock'));
var exist = _yapi2.default.commons.fileExist(_yapi2.default.path.join(_yapi2.default.WEBROOT_RUNTIME, 'init.lock'));
if (!exist) {
(0, _commons.log)('lock is not exist');
_yapi2.default.commons.log('lock is not exist');
}
}
exports.default = init;
_yapi2.default.db = model;
module.exports = {
model: model,
connect: connect
};

39
server_dist/yapi.js Normal file
View File

@ -0,0 +1,39 @@
'use strict';
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _fsExtra = require('fs-extra');
var _fsExtra2 = _interopRequireDefault(_fsExtra);
var _config = require('./config.json');
var _config2 = _interopRequireDefault(_config);
var _configDev = require('./config.dev.json');
var _configDev2 = _interopRequireDefault(_configDev);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var args = process.argv.splice(2);
var isDev = args[0] === 'dev' ? true : false;
var config = isDev ? _configDev2.default : _config2.default;
var WEBROOT = _path2.default.resolve(__dirname, '..');
var WEBROOT_SERVER = __dirname;
var WEBROOT_RUNTIME = _path2.default.join(WEBROOT, 'runtime');
var WEBROOT_LOG = _path2.default.join(WEBROOT_RUNTIME, 'log');
var WEBCONFIG = config;
module.exports = {
fs: _fsExtra2.default,
path: _path2.default,
WEBROOT: WEBROOT,
WEBROOT_SERVER: WEBROOT_SERVER,
WEBROOT_RUNTIME: WEBROOT_RUNTIME,
WEBROOT_LOG: WEBROOT_LOG,
WEBCONFIG: WEBCONFIG
};