-
Notifications
You must be signed in to change notification settings - Fork 24
/
app.js
76 lines (58 loc) · 1.54 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
'use strict'
const Koa = require('koa')
const fs = require('fs')
const mongoose = require('mongoose')
const Promise = require('bluebird')
const options = require('./options.json')
const { join } = require('path')
mongoose.Promise = Promise
const dbUrl = 'mongodb://localhost/imooc'
mongoose.connect(dbUrl)
// models loading
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path)
.filter(file => ~file.search(/^[^\.].*\.js$/))
.forEach(file => require(join(models_path, file)))
var menu = require('./wx/menu')
var wx = require('./wx')
var wechatApi = wx.getWechat()
wechatApi.deleteMenu().then(function() {
return wechatApi.createMenu(menu)
})
.then(function(msg) {
console.log('msg', msg)
})
var app = new Koa()
var Router = require('koa-router')
var session = require('koa-session')
var bodyParser = require('koa-bodyparser')
var router = new Router()
var User = mongoose.model('User')
var views = require('koa-views')
var moment = require('moment')
app.use(views(__dirname + '/app/views', {
extension: 'pug',
locals: {
moment: moment
}
}))
app.keys = ['imooc']
app.use(session(app))
app.use(bodyParser())
app.use(async (ctx, next) => {
var user = ctx.session.user
if (user && user._id) {
ctx.session.user = await User.findOne({_id: user._id}).exec()
ctx.state.user = ctx.session.user
}
else {
ctx.state.user = null
}
await next()
})
require('./config/routes')(router)
app
.use(router.routes())
.use(router.allowedMethods())
app.listen(options.port)
console.log('Listening: ' + options.port)