//api.js
const Koa = require('koa');
const router = require('koa-router')(); //路由
const bodyParser = require('koa-bodyparser'); //解析原始request请求
const fs = require('fs'); //文件读取
const cors = require('koa2-cors'); //设置cors头
const app = new Koa;
/**
* 数据库连接
*/
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/admin', {'useNewUrlParser': true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('数据库连接成功')
/**
* Schema 用来定义存储在document 中的属性,并且赋予他们校验的规则,和默认值
*/
var kittySchema = new mongoose.Schema({
name: String
});
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: "I don't have a name";
console.log(greeting);
}
/**
* 定义模型
*/
var Kitten = mongoose.model('Kitten', kittySchema);
/**
* 模型实例
*/
var silence = new Kitten({ name: 'Silence' });
console.log(silence.name); // 'Silence'
silence.save(); //插库
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
fluffy.speak();
});
});
app.use(bodyParser());
app.use(cors({
origin: function (ctx) {
return '*';
}
}));
let files = fs.readdirSync(__dirname + '/controllers');
let js_files = files.filter((f)=>{
return f.endsWith('.js');
});
for( let f of js_files ){
console.log(`process conteoller : ${f} ...`);
let mapping = require(__dirname + '/controllers/' + f );
for ( let url in mapping ){
if( url.startsWith('GET ')){
//如果url类似'GET xxx'
let path = url.substring(4);
router.get(path,mapping[url]);
}else if( url.startsWith('POST ') ){
//如果url类似'POST xxx'
let path = url.substring(5);
console.log('请求方式是:',path);
router.post(path,mapping[url]);
}
}
}
app.use(router.routes());
app.listen(8888);
console.log('app started at port 8888...');