fix: 添加eslint并修复部分格式问题

This commit is contained in:
祝鑫奔 2017-07-26 22:03:18 +08:00
parent 25f774c7c1
commit f58b2fa794
30 changed files with 572 additions and 473 deletions

42
.eslintrc.js Normal file
View File

@ -0,0 +1,42 @@
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parser": "babel-eslint",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [
"error",
4,
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"strict": 0
}
};

View File

@ -1,22 +1,22 @@
import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Route, HashRouter, Redirect, Switch } from 'react-router-dom'
import { Home, ProjectGroups, Interface, News, AddInterface } from './containers/index'
import User from './containers/User/User.js'
import Header from './components/Header/Header'
import Footer from './components/Footer/Footer'
import Loading from './components/Loading/Loading'
import { checkLoginState } from './actions/login'
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Route, HashRouter, Redirect, Switch } from 'react-router-dom';
import { Home, ProjectGroups, Interface, News, AddInterface } from './containers/index';
import User from './containers/User/User.js';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import Loading from './components/Loading/Loading';
import { checkLoginState } from './actions/login';
import { requireAuthentication } from './components/AuthenticatedComponent';
const LOADING_STATUS = 0;
@connect(
state => {
return{
loginState:state.login.loginState
}
return {
loginState: state.login.loginState
};
},
{
checkLoginState
@ -27,20 +27,22 @@ export default class App extends Component {
super(props);
this.state = {
login: LOADING_STATUS
}
};
}
static propTypes = {
checkLoginState:PropTypes.func,
loginState:PropTypes.number
}
checkLoginState: PropTypes.func,
loginState: PropTypes.number
};
componentDidMount() {
this.props.checkLoginState();
}
route = (status) => {
let r;
if (status === LOADING_STATUS) {
return <Loading visible/>
return <Loading visible />;
} else {
r = (
<HashRouter>
@ -50,20 +52,21 @@ export default class App extends Component {
<Route path="/" component={Home} exact />
<Switch>
<Redirect exact from='/group' to='/group/1' />
<Route exact path="/group/:groupName" component={ requireAuthentication(ProjectGroups) } />
<Route exact path="/group/:groupName" component={requireAuthentication(ProjectGroups)} />
</Switch>
<Route path="/Interface" component={requireAuthentication(Interface)} />
<Route path="/user" component={requireAuthentication(User)} />
<Route path="/News" component={requireAuthentication(News)} />
<Route path="/AddInterface" component={ requireAuthentication(AddInterface) } />
<Route path="/AddInterface" component={requireAuthentication(AddInterface)} />
</div>
<Footer/>
<Footer />
</div>
</HashRouter>
)
}
return r
return r;
}
render() {
return this.route(this.props.loginState);
}

View File

@ -130,7 +130,7 @@ gulp.task('build', () => {
};
let ykitOutput = '';
spinner = ora('请稍等...').start();
spinner = ora('正在编译,请稍等...').start();
gulp.src(SRC)
.pipe(generateBabel(status))

View File

@ -6,7 +6,7 @@
"scripts": {
"build-server": "babel server -d server_dist",
"dev-server": "nodemon server_dist/app.js -L",
"install-server" : "node server_dist/install.js",
"install-server": "node server_dist/install.js",
"dev": "gulp --silent",
"build": "gulp build --silent",
"only-watch": "gulp watchNode"
@ -68,7 +68,7 @@
"babel": "^6.5.2",
"babel-cli": "^6.24.1",
"babel-core": "^6.8.0",
"babel-eslint": "^6.0.4",
"babel-eslint": "^7.2.3",
"babel-loader": "^6.2.4",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-object-rest-spread": "^6.8.0",

View File

@ -2,35 +2,22 @@ import yapi from './yapi.js';
import commons from './utils/commons';
yapi.commons = commons;
import dbModule from './utils/db.js';
import mockServer from './middleware/mockServer.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'
import mockServer from './middleware/mockServer.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';
yapi.connect = dbModule.connect()
const app = new Koa()
app.use(mockServer)
app.use(bodyParser())
app.use(router.routes())
app.use(router.allowedMethods())
yapi.connect = dbModule.connect();
const app = new Koa();
app.use(mockServer);
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}`)
));
app.listen(yapi.WEBCONFIG.port);
commons.log(`the server is start at port ${yapi.WEBCONFIG.port}`);

View File

@ -1,18 +1,18 @@
module.exports = {
"port": "3000",
"webhost": "yapi.local.qunar.com",
"adminAccount": "admin@admin.com",
"db": {
"servername": "127.0.0.1",
"DATABASE": "yapi",
"port": 27017
},
"mail": {
"host": "smtp.mail.com",
"port": 4652,
"auth": {
"user": "****@mail.com",
"pass": "**********"
'port': '3000',
'webhost': 'yapi.local.qunar.com',
'adminAccount': 'admin@admin.com',
'db': {
'servername': '127.0.0.1',
'DATABASE': 'yapi',
'port': 27017
},
'mail': {
'host': 'smtp.mail.com',
'port': 4652,
'auth': {
'user': '****@mail.com',
'pass': '**********'
}
}
}
}
};

View File

@ -98,7 +98,7 @@ class userController extends baseController {
})
})
},
tokenField: 'token',
tokenField: 'token'
}
}

View File

@ -1,27 +1,26 @@
import fs from 'fs-extra'
import path from 'path'
import initConfig from './utils/initConfig.js'
import fs from 'fs-extra';
import yapi from './yapi.js';
import commons from './utils/commons';
import dbModule from './utils/db.js';
import userModel from './models/user.js'
import userModel from './models/user.js';
yapi.commons = commons;
yapi.connect = dbModule.connect()
yapi.connect = dbModule.connect();
function install(){
let exist = yapi.commons.fileExist(yapi.path.join(yapi.WEBROOT_RUNTIME, 'init.lock'))
if(exist){
return yapi.commons.log('runtime/init.lock文件已存在请确认您是否已安装。如果需要重新安装请删掉runtime/init.lock文件');
process.exit(1);
function install() {
let exist = yapi.commons.fileExist(yapi.path.join(yapi.WEBROOT_RUNTIME, 'init.lock'));
if (exist) {
yapi.commons.log('runtime/init.lock文件已存在请确认您是否已安装。如果需要重新安装请删掉runtime/init.lock文件');
process.exit(0);
}
setupSql();
}
function setupSql(){
let userInst = yapi.getInst(userModel);
function setupSql() {
let userInst = yapi.getInst(userModel);
let passsalt = yapi.commons.randStr();
let result = userInst.save({
username: yapi.WEBCONFIG.adminAccount.substr(0, yapi.WEBCONFIG.adminAccount.indexOf('@')),
@ -31,15 +30,16 @@ function setupSql(){
role: 'admin',
add_time: yapi.commons.time(),
up_time: yapi.commons.time()
})
result.then(function(success){
});
result.then(function () {
fs.ensureFileSync(yapi.path.join(yapi.WEBROOT_RUNTIME, 'init.lock'));
console.log(`初始化管理员账号 "${yapi.WEBCONFIG.adminAccount}" 成功`);
yapi.fs.ensureFileSync(yapi.path.join(yapi.WEBROOT_RUNTIME, 'init.lock'));
process.exit(1)
}, function(err){
process.exit(0);
}, function (err) {
console.log(`初始化管理员账号 "${yapi.WEBCONFIG.adminAccount}" 失败, ${err.message}`);
process.exit(1)
})
process.exit(0);
});
}
install()
install();

View File

@ -1,24 +1,23 @@
import yapi from '../yapi.js'
import mongoose from 'mongoose'
import autoIncrement from 'mongoose-auto-increment'
import yapi from '../yapi.js';
import mongoose from 'mongoose';
import autoIncrement from 'mongoose-auto-increment';
/**
* 所有的model都需要继承baseModel, 且需要 getSchema和getName方法不然会报错
*/
class baseModel{
constructor(){
this.schema = new mongoose.Schema(this.getSchema())
this.name = this.getName()
this.schema = new mongoose.Schema(this.getSchema());
this.name = this.getName();
if(this.isNeedAutoIncrement() === true){
this.schema.plugin(autoIncrement.plugin, {
model: this.name,
field: this.getPrimaryKey(),
startAt: 101,
incrementBy: yapi.commons.rand(1, 100)
})
});
}
this.model = yapi.db(this.name, this.schema);
@ -32,22 +31,19 @@ class baseModel{
* 可通过覆盖此方法生成其他自增字段
*/
getPrimaryKey(){
return '_id'
return '_id';
}
/**
* 获取collection的schema结构
*/
getSchema(){
yapi.commons.log('Model Class need getSchema function', 'error')
yapi.commons.log('Model Class need getSchema function', 'error');
}
getName(){
yapi.commons.log('Model Class need name', 'error')
yapi.commons.log('Model Class need name', 'error');
}
}
module.exports = baseModel;

View File

@ -1,57 +1,61 @@
import yapi from '../yapi.js'
import mongoose from 'mongoose'
import baseModel from './base.js'
import yapi from '../yapi.js';
import mongoose from 'mongoose';
import baseModel from './base.js';
class groupModel extends baseModel{
getName(){
return 'group'
class groupModel extends baseModel {
getName() {
return 'group';
}
getSchema(){
getSchema() {
return {
uid: Number,
group_name: String,
group_desc: String,
add_time: Number,
up_time: Number
}
};
}
save(data) {
let m = new this.model(data);
return m.save();
}
checkRepeat(name) {
checkRepeat(name) {
return this.model.count({
group_name: name
})
});
}
list(){
return this.model.find().select("group_name _id group_desc add_time up_time").exec()
list() {
return this.model.find().select("group_name _id group_desc add_time up_time").exec();
}
del (id) {
del(id) {
return this.model.deleteOne({
_id: id
})
});
}
up (id, data) {
return this.model.update({
_id: id,
}, {
group_name: data.group_name,
group_desc: data.group_desc,
up_time: yapi.commons.time()
})
up(id, data) {
return this.model.update(
{
_id: id
}, {
group_name: data.group_name,
group_desc: data.group_desc,
up_time: yapi.commons.time()
}
);
}
search(keyword) {
return this.model.find({
group_name: new RegExp(keyword, 'i')
})
.limit(10)
.limit(10);
}
}
module.exports= groupModel
module.exports = groupModel;

View File

@ -1,38 +1,38 @@
import yapi from '../yapi.js'
import baseModel from './base.js'
import yapi from '../yapi.js';
import baseModel from './base.js';
class interfaceModel extends baseModel{
getName(){
return 'interface'
class interfaceModel extends baseModel {
getName() {
return 'interface';
}
getSchema(){
getSchema() {
return {
title: {type: String, required: true},
uid: {type: Number, required: true},
path: {type: String, required: true},
method: {type: String, required: true},
project_id: {type: Number, required: true},
title: { type: String, required: true },
uid: { type: Number, required: true },
path: { type: String, required: true },
method: { type: String, required: true },
project_id: { type: Number, required: true },
desc: String,
add_time: Number,
up_time: Number,
req_headers: [{
name: String, value: String, desc: String, required: Boolean
name: String, value: String, desc: String, required: Boolean
}],
req_params_type: {
type: String,
enum: ["form", "json", "text", "xml"]
enum: ['form', 'json', 'text', 'xml']
},
req_params_form: [{
name: String, value: String,value_type: {type: String, enum: ["text", "file"]}, desc: String, required: Boolean
name: String, value: String, value_type: { type: String, enum: ['text', 'file'] }, desc: String, required: Boolean
}],
req_params_other: String,
res_body_type: {
type: String,
enum: ["json", "text", "xml"]
enum: ['json', 'text', 'xml']
},
res_body: String
}
};
}
save(data) {
@ -40,50 +40,53 @@ class interfaceModel extends baseModel{
return m.save();
}
get(id){
get(id) {
return this.model.findOne({
_id: id
}).exec()
})
.exec();
}
getByPath(project_id, path){
getByPath(project_id, path) {
return this.model.find({
project_id: project_id,
path: path
}).exec()
})
.exec();
}
checkRepeat(id, path, method){
checkRepeat(id, path, method) {
return this.model.count({
project_id: id,
path: path,
method: method
})
});
}
countByProjectId(id){
countByProjectId(id) {
return this.model.count({
project_id: id
})
});
}
list (project_id){
list(project_id) {
return this.model.find({
project_id: project_id
}).sort({_id: -1}).exec()
})
.sort({ _id: -1 })
.exec();
}
del(id){
del(id) {
return this.model.deleteOne({
_id: id
})
});
}
up(id, data){
up(id, data) {
data.up_time = yapi.commons.time();
return this.model.update({
_id: id,
}, data, { runValidators: true })
}, data, { runValidators: true });
}
}

View File

@ -9,13 +9,13 @@ class logModel extends baseModel {
getSchema() {
return {
uid: {type: Number, required: true},
title: {type: String, required: true},
type: {type: String, enum:['user', 'group', 'interface', 'project', 'other'], required: true},
content: {type: String, required: true},
username: {type: String, required: true},
uid: { type: Number, required: true },
title: { type: String, required: true },
type: { type: String, enum: ['user', 'group', 'interface', 'project', 'other'], required: true },
content: { type: String, required: true },
username: { type: String, required: true },
add_time: Number
}
};
}
/**
@ -36,21 +36,27 @@ class logModel extends baseModel {
add_time: yapi.commons.time()
};
let log = new this.model(saveData);
return log.save();
}
list (uid){
list(uid) {
return this.model.find({
uid: uid
}).exec()
})
.exec();
}
listWithPaging(uid, page, limit) {
page = parseInt(page);
limit = parseInt(limit);
return this.model.find({
uid: uid
}).skip((page - 1) * limit).limit(limit).exec();
})
.skip((page - 1) * limit)
.limit(limit)
.exec();
}
listCount(uid) {

View File

@ -1,33 +1,34 @@
import yapi from '../yapi.js'
import baseModel from './base.js'
import yapi from '../yapi.js';
import baseModel from './base.js';
class projectModel extends baseModel{
getName(){
return 'project'
class projectModel extends baseModel {
getName() {
return 'project';
}
getSchema(){
getSchema() {
return {
uid: {type: Number, required: true},
name: {type: String, required: true},
basepath: {type: String, required: true, validate: {
validator: (v) => {
console.log('basepath: ', v)
return v && v[0] === '/'
},
message: 'basepath必须是/开头'
}},
uid: { type: Number, required: true },
name: { type: String, required: true },
basepath: {
type: String, required: true, validate: {
validator: (v) => {
return v && v[0] === '/';
},
message: 'basepath必须是/开头'
}
},
desc: String,
group_id: {type: Number, required: true},
members: Array,
protocol: {type: String, required: true},
prd_host: {type: String, required: true},
group_id: { type: Number, required: true },
members: Array,
protocol: { type: String, required: true },
prd_host: { type: String, required: true },
env: [
{name: String, domain: String}
{ name: String, domain: String }
],
add_time: Number,
up_time: Number
}
};
}
save(data) {
@ -35,37 +36,35 @@ class projectModel extends baseModel{
return m.save();
}
get(id){
get(id) {
return this.model.findOne({
_id: id
}).exec()
}).exec();
}
getByDomain(domain){
getByDomain(domain) {
return this.model.find({
prd_host: domain
}).exec()
}).exec();
}
checkNameRepeat(name){
checkNameRepeat(name) {
return this.model.count({
name: name
})
});
}
checkDomainRepeat(domain, basepath){
checkDomainRepeat(domain, basepath) {
return this.model.count({
prd_host: domain,
basepath: basepath
})
});
}
list (group_id){
list(group_id) {
return this.model.find({
group_id: group_id
}).sort({_id: -1}).exec()
}).sort({ _id: -1 }).exec();
}
listWithPaging(group_id, page, limit) {
@ -73,7 +72,7 @@ class projectModel extends baseModel{
limit = parseInt(limit);
return this.model.find({
group_id: group_id
}).sort({_id: -1}).skip((page - 1) * limit).limit(limit).exec();
}).sort({ _id: -1 }).skip((page - 1) * limit).limit(limit).exec();
}
listCount(group_id) {
@ -82,54 +81,58 @@ class projectModel extends baseModel{
});
}
countByGroupId(group_id){
countByGroupId(group_id) {
return this.model.count({
group_id: group_id
})
});
}
del(id){
del(id) {
return this.model.deleteOne({
_id: id
})
});
}
up(id, data){
up(id, data) {
data.up_time = yapi.commons.time();
return this.model.update({
_id: id,
}, data, { runValidators: true })
}, data, { runValidators: true });
}
addMember(id, uid){
return this.model.update({
_id: id
}, {
$push: {members: uid}
})
addMember(id, uid) {
return this.model.update(
{
_id: id
}, {
$push: { members: uid }
}
);
}
delMember(id, uid){
return this.model.update({
_id: id
}, {
$pull: {members: uid}
})
delMember(id, uid) {
return this.model.update(
{
_id: id
}, {
$pull: { members: uid }
}
);
}
checkMemberRepeat(id, uid){
checkMemberRepeat(id, uid) {
return this.model.count({
_id: id,
members:[uid]
})
members: [uid]
});
}
search(keyword) {
return this.model.find({
name: new RegExp(keyword, 'ig')
})
.limit(10)
.limit(10);
}
}
module.exports = projectModel;

View File

@ -1,87 +1,95 @@
import yapi from '../yapi.js'
import mongoose from 'mongoose'
import baseModel from './base.js'
import baseModel from './base.js';
class userModel extends baseModel{
getName(){
return 'user'
class userModel extends baseModel {
getName() {
return 'user';
}
getSchema(){
return{
username: {
getSchema() {
return {
username: {
type: String,
required: true
},
password:{
type:String,
required: true
},
email: {
type: String,
required: true
},
passsalt: String,
role: String,
add_time: Number,
up_time: Number
}
required: true
},
password: {
type: String,
required: true
},
email: {
type: String,
required: true
},
passsalt: String,
role: String,
add_time: Number,
up_time: Number
};
}
save(data){
save(data) {
let user = new this.model(data);
return user.save();
}
checkRepeat(email){
checkRepeat(email) {
return this.model.count({
email: email
})
});
}
list(){
return this.model.find().select("_id username email role add_time up_time").exec() //显示id name email role
list() {
return this.model.find().select('_id username email role add_time up_time').exec(); //显示id name email role
}
findByUids(uids){
findByUids(uids) {
return this.model.find({
_id: {$in: uids}
}).select("_id username email role add_time up_time").exec()
_id: { $in: uids }
}).select('_id username email role add_time up_time').exec();
}
listWithPaging(page, limit) {
page = parseInt(page);
limit = parseInt(limit);
return this.model.find().sort({_id: -1}).skip((page - 1) * limit).limit(limit).select("_id username email role add_time up_time").exec();
return this.model.find().sort({ _id: -1 }).skip((page - 1) * limit).limit(limit).select('_id username email role add_time up_time').exec();
}
listCount() {
return this.model.count();
}
findByEmail(email){
return this.model.findOne({email: email})
findByEmail(email) {
return this.model.findOne({ email: email });
}
findById(id){
findById(id) {
return this.model.findById({
_id: id
})
});
}
del (id) {
del(id) {
return this.model.deleteOne({
_id: id
})
_id: id
});
}
update(id,data){
update(id, data) {
return this.model.update({
_id: id
}, data)
}, data);
}
search(keyword) {
return this.model.find({
$or: [
{ email: new RegExp(keyword, 'i') },
{ username: new RegExp(keyword, 'i')}
{ username: new RegExp(keyword, 'i') }
]
}, {
passsalt: 0,
password: 0
}).limit(10)
}).limit(10);
}
}
module.exports = userModel
module.exports = userModel;

View File

@ -1,12 +1,11 @@
import koaRouter from 'koa-router'
import interfaceController from './controllers/interface.js'
import groupController from './controllers/group.js'
import userController from './controllers/user.js'
import yapi from './yapi.js'
import projectController from './controllers/project.js'
import logController from './controllers/log.js'
import koaRouter from 'koa-router';
import interfaceController from './controllers/interface.js';
import groupController from './controllers/group.js';
import userController from './controllers/user.js';
import yapi from './yapi.js';
import projectController from './controllers/project.js';
import logController from './controllers/log.js';
const router = koaRouter();
@ -34,47 +33,46 @@ const INTERFACE_CONFIG = {
};
//group
createAction('group', 'list', 'get', 'list')
createAction('group', 'add', 'post', 'add')
createAction('group', 'up', 'post', 'up')
createAction('group', 'del', 'post', 'del')
createAction('group', 'list', 'get', 'list');
createAction('group', 'add', 'post', 'add');
createAction('group', 'up', 'post', 'up');
createAction('group', 'del', 'post', 'del');
//user
createAction('user', 'login', 'post', 'login')
createAction('user', 'reg', 'post', 'reg')
createAction('user', 'list', 'get', 'list')
createAction('user', 'find', 'get', 'findById')
createAction('user', 'update', 'post', 'update')
createAction('user', 'del', 'post', 'del')
createAction('user', 'status', 'get', 'getLoginStatus')
createAction('user', 'logout', 'get', 'logout')
createAction('user', 'login_by_token', 'post', 'loginByToken')
createAction('user', 'change_password', 'post', 'changePassword')
createAction('user', 'search', 'get', 'search')
createAction('user', 'login', 'post', 'login');
createAction('user', 'reg', 'post', 'reg');
createAction('user', 'list', 'get', 'list');
createAction('user', 'find', 'get', 'findById');
createAction('user', 'update', 'post', 'update');
createAction('user', 'del', 'post', 'del');
createAction('user', 'status', 'get', 'getLoginStatus');
createAction('user', 'logout', 'get', 'logout');
createAction('user', 'login_by_token', 'post', 'loginByToken');
createAction('user', 'change_password', 'post', 'changePassword');
createAction('user', 'search', 'get', 'search');
//project
createAction('project', 'add', 'post', 'add')
createAction('project', 'list', 'get', 'list')
createAction('project', 'get', 'get', 'get')
createAction('project', 'up', 'post', 'up')
createAction('project', 'del', 'post', 'del')
createAction('project', 'add_member', 'post', 'addMember')
createAction('project', 'del_member', 'post', 'delMember')
createAction('project', 'get_member_list', 'get', 'getMemberList')
createAction('project', 'search', 'get', 'search')
createAction('project', 'add', 'post', 'add');
createAction('project', 'list', 'get', 'list');
createAction('project', 'get', 'get', 'get');
createAction('project', 'up', 'post', 'up');
createAction('project', 'del', 'post', 'del');
createAction('project', 'add_member', 'post', 'addMember');
createAction('project', 'del_member', 'post', 'delMember');
createAction('project', 'get_member_list', 'get', 'getMemberList');
createAction('project', 'search', 'get', 'search');
//interface
createAction('interface', 'add', 'post', 'add')
createAction('interface', 'list', 'get', 'list')
createAction('interface', 'get', 'get', 'get')
createAction('interface', 'up', 'post', 'up')
createAction('interface', 'del', 'post', 'del')
createAction('interface', 'add', 'post', 'add');
createAction('interface', 'list', 'get', 'list');
createAction('interface', 'get', 'get', 'get');
createAction('interface', 'up', 'post', 'up');
createAction('interface', 'del', 'post', 'del');
//node
createAction('log', 'list', 'get', 'list');
/**
*
* @param {*} controller controller_name
@ -82,18 +80,20 @@ createAction('log', 'list', 'get', 'list');
* @param {*} method request_method , post get put delete ...
* @param {*} action controller_action_name
*/
function createAction(controller, path, method, action){
function createAction(controller, path, method, action) {
router[method](INTERFACE_CONFIG[controller].prefix + path, async (ctx) => {
let inst = new INTERFACE_CONFIG[controller].controller(ctx);
await inst.init(ctx);
if(inst.$auth === true){
if (inst.$auth === true) {
await inst[action].call(inst, ctx);
}else{
} else {
ctx.body = yapi.commons.resReturn(null, 400, 'Without Permission.');
}
})
});
}
module.exports = router
module.exports = router;

View File

@ -1,35 +1,36 @@
import fs from 'fs-extra'
import path from 'path'
import yapi from '../yapi.js'
import sha1 from 'sha1'
import fs from 'fs-extra';
import path from 'path';
import yapi from '../yapi.js';
import sha1 from 'sha1';
exports.resReturn = (data, num, errmsg) => {
num = num || 0;
return {
errcode: num,
errmsg: errmsg || 'success',
data: data
}
}
const MSGTYPE = {
'log': 'Log',
'warn': 'warning',
'error': 'Error'
}
};
};
exports.log = (msg, type) => {
if (!msg) return;
if (!msg) {
return;
}
type = type || 'log';
let f;
switch (type) {
case 'log': f = console.log; break;
case 'warn': f = console.warn; break;
case 'error': f = console.error; break;
default: f = console.log; break;
}
f(type + ':', msg);
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
@ -40,14 +41,13 @@ exports.log = (msg, type) => {
if (msg instanceof Error) msg = msg.message;
else msg = JSON.stringify(msg);
}
let data = (new Date).toLocaleTimeString() + "\t|\t" + type + "\t|\t" + msg;
let data = (new Date).toLocaleTimeString() + '\t|\t' + type + '\t|\t' + msg;
fs.writeFileSync(logfile, data, {
flag: 'w+'
});
}
};
exports.fileExist = (filePath) => {
try {
@ -55,80 +55,88 @@ exports.fileExist = (filePath) => {
} catch (err) {
return false;
}
}
};
exports.time = () => {
return Date.parse(new Date()) / 1000;
}
};
exports.fieldSelect = (data, field) => {
if (!data || !field || !Array.isArray(field)) return null;
if (!data || !field || !Array.isArray(field)) {
return null;
}
var arr = {};
field.forEach((f) => {
data[f] && (arr[f] = data[f]);
})
});
return arr;
}
};
exports.rand = (min, max) => {
return Math.floor(Math.random() * (max - min) + min);
}
};
exports.json_parse = (json) => {
try {
return JSON.parse(json);
} catch (e) {
return json
return json;
}
}
};
exports.randStr = () => {
return Math.random().toString(36).substr(2)
}
return Math.random().toString(36).substr(2);
};
exports.generatePassword = (password, passsalt) => {
return sha1(password + sha1(passsalt));
}
};
exports.expireDate = (day) => {
let date = new Date();
date.setTime(date.getTime() + day * 86400000);
return date;
}
};
exports.sendMail = (options, cb) => {
if (!yapi.mail) return false;
options.subject = options.subject ? options.subject + '-yapi平台' : 'ypai平台';
cb = cb || function (err, info) {
cb = cb || function (err) {
if (err) {
yapi.commons.log('send mail ' + options.to + ' error,' + err.message, 'error');
} else {
yapi.commons.log('send mail ' + options.to + ' success');
}
};
}
try {
yapi.mail.sendMail({
from: yapi.WEBCONFIG.mail.auth.user,
to: options.to,
subject: 'yapi平台',
html: options.contents
}, cb)
}, cb);
} catch (e) {
console.error(e.message)
console.error(e.message);
}
}
};
exports.validateSearchKeyword = keyword => {
if (/^\*|\?|\+|\$|\^|\\|\.$/.test(keyword)) {
return false;
}
return true;
}
};
exports.filterRes = (list, rules) => {
return list.map(item => {
let filteredRes = {};
rules.forEach(rule => {
if (typeof rule == 'string') {
filteredRes[rule] = item[rule];
@ -136,38 +144,51 @@ exports.filterRes = (list, rules) => {
filteredRes[rule.alias] = item[rule.key];
}
});
return filteredRes;
})
}
});
};
exports.verifyPath = (path) => {
if (/^\/[a-zA-Z0-9\-\/_:\.]+$/.test(path)) {
if (path[path.length - 1] === '/') {
return false;
} else {
return true
return true;
}
} else {
return false;
}
}
};
function trim(str) {
if (!str) return str;
if (!str) {
return str;
}
str = str + '';
return str.replace(/(^\s*)|(\s*$)/g, "");
return str.replace(/(^\s*)|(\s*$)/g, '');
}
function ltrim(str) {
if (!str) return str;
if (!str) {
return str;
}
str = str + '';
return str.replace(/(^\s*)/g, "");
return str.replace(/(^\s*)/g, '');
}
function rtrim(str) {
if (!str) return str;
if (!str) {
return str;
}
str = str + '';
return str.replace(/(\s*$)/g, "");
return str.replace(/(\s*$)/g, '');
}
exports.trim = trim;
@ -175,7 +196,10 @@ exports.ltrim = ltrim;
exports.rtrim = rtrim;
exports.handleParams = (params, keys) => {
if (!params || typeof params !== 'object' || !keys || typeof keys !== 'object') return false;
if (!params || typeof params !== 'object' || !keys || typeof keys !== 'object') {
return false;
}
for (var key in keys) {
var filter = keys[key];
if (params[key]) {
@ -186,5 +210,6 @@ exports.handleParams = (params, keys) => {
}
}
}
return params;
}
};

View File

@ -1,31 +1,35 @@
import mongoose from 'mongoose'
import yapi from '../yapi.js'
import autoIncrement from 'mongoose-auto-increment'
import mongoose from 'mongoose';
import yapi from '../yapi.js';
import autoIncrement from 'mongoose-auto-increment';
function model(model, schema){
if(schema instanceof mongoose.Schema === false){
schema = new mongoose.Schema(schema);
}
schema.set('autoIndex', false);
return yapi.connect.model(model, schema, model)
return yapi.connect.model(model, schema, model);
}
function connect(){
mongoose.Promise = global.Promise;
let config = yapi.WEBCONFIG;
let options = {};
if(config.user){
options.user = config.db.user,
options.pass = config.db.pass
options.pass = config.db.pass;
}
let db = mongoose.connect(`mongodb://${config.db.servername}:${config.db.port}/${config.db.DATABASE}`, options);
db.then(function (res) {
yapi.commons.log('mongodb load success...')
yapi.commons.log('mongodb load success...');
}, function (err) {
yapi.commons.log(err, 'Mongo connect error');
})
});
autoIncrement.initialize(db);
return db;
@ -33,12 +37,7 @@ function connect(){
yapi.db = model;
module.exports = {
model: model,
connect: connect
};
};

View File

@ -1,10 +1,10 @@
import path from 'path'
import fs from 'fs-extra'
import config from '../config.js'
import path from 'path';
import fs from 'fs-extra';
import config from '../config.js';
let configPath = path.join(path.resolve(__dirname, '../../'), 'runtime', 'config.json')
let configPath = path.join(path.resolve(__dirname, '../../'), 'runtime', 'config.json');
fs.writeFileSync(configPath,
JSON.stringify(config, null, "\t"),
{encoding: 'utf8'}
)
JSON.stringify(config, null, '\t'),
{ encoding: 'utf8' }
);

View File

@ -1,24 +1,22 @@
import path from 'path'
import fs from 'fs-extra'
import path from 'path';
import fs from 'fs-extra';
import nodemailer from 'nodemailer';
import config from '../runtime/config.json'
import config from '../runtime/config.json';
var insts = new Map();
let insts = new Map();
let mail;
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;
const WEBCONFIG = config;
fs.ensureDirSync(WEBROOT_RUNTIME);
fs.ensureDirSync(WEBROOT_LOG);
if(WEBCONFIG.mail){
mail = nodemailer.createTransport(WEBCONFIG.mail)
if (WEBCONFIG.mail) {
mail = nodemailer.createTransport(WEBCONFIG.mail);
}
/**
@ -27,18 +25,18 @@ if(WEBCONFIG.mail){
* @example
* yapi.getInst(groupModel, arg1, arg2)
*/
function getInst(m, ...args){
if(!insts.get(m)){
insts.set(m, new m(args))
function getInst(m, ...args) {
if (!insts.get(m)) {
insts.set(m, new m(args));
}
return insts.get(m)
return insts.get(m);
}
function delInst(m){
try{
insts.delete(m)
}catch(err){
console.error(err)
function delInst(m) {
try {
insts.delete(m);
} catch (err) {
console.error(err);
}
}
@ -53,6 +51,6 @@ let r = {
getInst: getInst,
delInst: delInst,
getInsts: insts
}
if(mail) r.mail = mail;
};
if (mail) r.mail = mail;
module.exports = r;

View File

@ -43,6 +43,7 @@ _yapi2.default.commons = _commons2.default;
_yapi2.default.connect = _db2.default.connect();
var app = new _koa2.default();
app.use(_mockServer2.default);
app.use((0, _koaBodyparser2.default)());
app.use(_router2.default.routes());

View File

@ -1,20 +1,20 @@
"use strict";
'use strict';
module.exports = {
"port": "3000",
"webhost": "yapi.local.qunar.com",
"adminAccount": "admin@admin.com",
"db": {
"servername": "127.0.0.1",
"DATABASE": "yapi",
"port": 27017
},
"mail": {
"host": "smtp.mail.com",
"port": 4652,
"auth": {
"user": "****@mail.com",
"pass": "**********"
'port': '3000',
'webhost': 'yapi.local.qunar.com',
'adminAccount': 'admin@admin.com',
'db': {
'servername': '127.0.0.1',
'DATABASE': 'yapi',
'port': 27017
},
'mail': {
'host': 'smtp.mail.com',
'port': 4652,
'auth': {
'user': '****@mail.com',
'pass': '**********'
}
}
}
};

View File

@ -4,14 +4,6 @@ var _fsExtra = require('fs-extra');
var _fsExtra2 = _interopRequireDefault(_fsExtra);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _initConfig = require('./utils/initConfig.js');
var _initConfig2 = _interopRequireDefault(_initConfig);
var _yapi = require('./yapi.js');
var _yapi2 = _interopRequireDefault(_yapi);
@ -35,10 +27,12 @@ _yapi2.default.connect = _db2.default.connect();
function install() {
var exist = _yapi2.default.commons.fileExist(_yapi2.default.path.join(_yapi2.default.WEBROOT_RUNTIME, 'init.lock'));
if (exist) {
return _yapi2.default.commons.log('runtime/init.lock文件已存在请确认您是否已安装。如果需要重新安装请删掉runtime/init.lock文件');
process.exit(1);
_yapi2.default.commons.log('runtime/init.lock文件已存在请确认您是否已安装。如果需要重新安装请删掉runtime/init.lock文件');
process.exit(0);
}
setupSql();
}
@ -54,13 +48,14 @@ function setupSql() {
add_time: _yapi2.default.commons.time(),
up_time: _yapi2.default.commons.time()
});
result.then(function (success) {
result.then(function () {
_fsExtra2.default.ensureFileSync(_yapi2.default.path.join(_yapi2.default.WEBROOT_RUNTIME, 'init.lock'));
console.log('\u521D\u59CB\u5316\u7BA1\u7406\u5458\u8D26\u53F7 "' + _yapi2.default.WEBCONFIG.adminAccount + '" \u6210\u529F');
_yapi2.default.fs.ensureFileSync(_yapi2.default.path.join(_yapi2.default.WEBROOT_RUNTIME, 'init.lock'));
process.exit(1);
process.exit(0);
}, function (err) {
console.log('\u521D\u59CB\u5316\u7BA1\u7406\u5458\u8D26\u53F7 "' + _yapi2.default.WEBCONFIG.adminAccount + '" \u5931\u8D25, ' + err.message);
process.exit(1);
process.exit(0);
});
}

View File

@ -32,6 +32,7 @@ var baseModel = function () {
this.schema = new _mongoose2.default.Schema(this.getSchema());
this.name = this.getName();
if (this.isNeedAutoIncrement() === true) {
this.schema.plugin(_mongooseAutoIncrement2.default.plugin, {
model: this.name,

View File

@ -60,15 +60,15 @@ var interfaceModel = function (_baseModel) {
}],
req_params_type: {
type: String,
enum: ["form", "json", "text", "xml"]
enum: ['form', 'json', 'text', 'xml']
},
req_params_form: [{
name: String, value: String, value_type: { type: String, enum: ["text", "file"] }, desc: String, required: Boolean
name: String, value: String, value_type: { type: String, enum: ['text', 'file'] }, desc: String, required: Boolean
}],
req_params_other: String,
res_body_type: {
type: String,
enum: ["json", "text", "xml"]
enum: ['json', 'text', 'xml']
},
res_body: String
};

View File

@ -127,6 +127,7 @@ var logModel = function (_baseModel) {
value: function listWithPaging(uid, page, limit) {
page = parseInt(page);
limit = parseInt(limit);
return this.model.find({
uid: uid
}).skip((page - 1) * limit).limit(limit).exec();

View File

@ -49,13 +49,14 @@ var projectModel = function (_baseModel) {
return {
uid: { type: Number, required: true },
name: { type: String, required: true },
basepath: { type: String, required: true, validate: {
basepath: {
type: String, required: true, validate: {
validator: function validator(v) {
console.log('basepath: ', v);
return v && v[0] === '/';
},
message: 'basepath必须是/开头'
} },
}
},
desc: String,
group_id: { type: Number, required: true },
members: Array,

View File

@ -20,14 +20,6 @@ var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _yapi = require('../yapi.js');
var _yapi2 = _interopRequireDefault(_yapi);
var _mongoose = require('mongoose');
var _mongoose2 = _interopRequireDefault(_mongoose);
var _base = require('./base.js');
var _base2 = _interopRequireDefault(_base);
@ -85,21 +77,21 @@ var userModel = function (_baseModel) {
}, {
key: 'list',
value: function list() {
return this.model.find().select("_id username email role add_time up_time").exec(); //显示id name email role
return this.model.find().select('_id username email role add_time up_time').exec(); //显示id name email role
}
}, {
key: 'findByUids',
value: function findByUids(uids) {
return this.model.find({
_id: { $in: uids }
}).select("_id username email role add_time up_time").exec();
}).select('_id username email role add_time up_time').exec();
}
}, {
key: 'listWithPaging',
value: function listWithPaging(page, limit) {
page = parseInt(page);
limit = parseInt(limit);
return this.model.find().sort({ _id: -1 }).skip((page - 1) * limit).limit(limit).select("_id username email role add_time up_time").exec();
return this.model.find().sort({ _id: -1 }).skip((page - 1) * limit).limit(limit).select('_id username email role add_time up_time').exec();
}
}, {
key: 'listCount',

View File

@ -28,6 +28,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
exports.resReturn = function (data, num, errmsg) {
num = num || 0;
return {
errcode: num,
errmsg: errmsg || 'success',
@ -35,16 +36,15 @@ exports.resReturn = function (data, num, errmsg) {
};
};
var MSGTYPE = {
'log': 'Log',
'warn': 'warning',
'error': 'Error'
};
exports.log = function (msg, type) {
if (!msg) return;
if (!msg) {
return;
}
type = type || 'log';
var f = void 0;
switch (type) {
case 'log':
f = console.log;break;
@ -55,7 +55,9 @@ exports.log = function (msg, type) {
default:
f = console.log;break;
}
f(type + ':', msg);
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
@ -65,7 +67,9 @@ exports.log = function (msg, type) {
if ((typeof msg === 'undefined' ? 'undefined' : (0, _typeof3.default)(msg)) === 'object') {
if (msg instanceof Error) msg = msg.message;else msg = (0, _stringify2.default)(msg);
}
var data = new Date().toLocaleTimeString() + "\t|\t" + type + "\t|\t" + msg;
var data = new Date().toLocaleTimeString() + '\t|\t' + type + '\t|\t' + msg;
_fsExtra2.default.writeFileSync(logfile, data, {
flag: 'w+'
});
@ -84,11 +88,16 @@ exports.time = function () {
};
exports.fieldSelect = function (data, field) {
if (!data || !field || !Array.isArray(field)) return null;
if (!data || !field || !Array.isArray(field)) {
return null;
}
var arr = {};
field.forEach(function (f) {
data[f] && (arr[f] = data[f]);
});
return arr;
};
@ -121,13 +130,15 @@ exports.expireDate = function (day) {
exports.sendMail = function (options, cb) {
if (!_yapi2.default.mail) return false;
options.subject = options.subject ? options.subject + '-yapi平台' : 'ypai平台';
cb = cb || function (err, info) {
cb = cb || function (err) {
if (err) {
_yapi2.default.commons.log('send mail ' + options.to + ' error,' + err.message, 'error');
} else {
_yapi2.default.commons.log('send mail ' + options.to + ' success');
}
};
try {
_yapi2.default.mail.sendMail({
from: _yapi2.default.WEBCONFIG.mail.auth.user,
@ -144,12 +155,14 @@ exports.validateSearchKeyword = function (keyword) {
if (/^\*|\?|\+|\$|\^|\\|\.$/.test(keyword)) {
return false;
}
return true;
};
exports.filterRes = function (list, rules) {
return list.map(function (item) {
var filteredRes = {};
rules.forEach(function (rule) {
if (typeof rule == 'string') {
filteredRes[rule] = item[rule];
@ -157,6 +170,7 @@ exports.filterRes = function (list, rules) {
filteredRes[rule.alias] = item[rule.key];
}
});
return filteredRes;
});
};
@ -174,21 +188,33 @@ exports.verifyPath = function (path) {
};
function trim(str) {
if (!str) return str;
if (!str) {
return str;
}
str = str + '';
return str.replace(/(^\s*)|(\s*$)/g, "");
return str.replace(/(^\s*)|(\s*$)/g, '');
}
function ltrim(str) {
if (!str) return str;
if (!str) {
return str;
}
str = str + '';
return str.replace(/(^\s*)/g, "");
return str.replace(/(^\s*)/g, '');
}
function rtrim(str) {
if (!str) return str;
if (!str) {
return str;
}
str = str + '';
return str.replace(/(\s*$)/g, "");
return str.replace(/(\s*$)/g, '');
}
exports.trim = trim;
@ -196,7 +222,10 @@ exports.ltrim = ltrim;
exports.rtrim = rtrim;
exports.handleParams = function (params, keys) {
if (!params || (typeof params === 'undefined' ? 'undefined' : (0, _typeof3.default)(params)) !== 'object' || !keys || (typeof keys === 'undefined' ? 'undefined' : (0, _typeof3.default)(keys)) !== 'object') return false;
if (!params || (typeof params === 'undefined' ? 'undefined' : (0, _typeof3.default)(params)) !== 'object' || !keys || (typeof keys === 'undefined' ? 'undefined' : (0, _typeof3.default)(keys)) !== 'object') {
return false;
}
for (var key in keys) {
var filter = keys[key];
if (params[key]) {
@ -210,5 +239,6 @@ exports.handleParams = function (params, keys) {
}
}
}
return params;
};

View File

@ -18,14 +18,18 @@ function model(model, schema) {
if (schema instanceof _mongoose2.default.Schema === false) {
schema = new _mongoose2.default.Schema(schema);
}
schema.set('autoIndex', false);
return _yapi2.default.connect.model(model, schema, model);
}
function connect() {
_mongoose2.default.Promise = global.Promise;
var config = _yapi2.default.WEBCONFIG;
var options = {};
if (config.user) {
options.user = config.db.user, options.pass = config.db.pass;
}

View File

@ -20,4 +20,4 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
var configPath = _path2.default.join(_path2.default.resolve(__dirname, '../../'), 'runtime', 'config.json');
_fsExtra2.default.writeFileSync(configPath, (0, _stringify2.default)(_config2.default, null, "\t"), { encoding: 'utf8' });
_fsExtra2.default.writeFileSync(configPath, (0, _stringify2.default)(_config2.default, null, '\t'), { encoding: 'utf8' });