This commit is contained in:
2017-01-23 03:38:59 +08:00
parent 878d9b63f6
commit f5dfeaa123
18 changed files with 403 additions and 70 deletions

View File

@ -1,3 +1,57 @@
import Koa2 from 'koa'
import KoaBodyParser from 'koa-bodyparser'
import KoaSession from 'koa-session2'
import KoaStatic from 'koa-static2'
import { SystemConfig } from '../config/main.js'
import path from 'path'
console.log('ok')
console.log('aaa')
import MainRoutes from './routes/main-routes'
import ErrorRoutes from './routes/error-routes'
import PluginLoader from './tool/PluginLoader'
const app = new Koa2()
const BodyParser = new KoaBodyParser()
const env = process.env.NODE_ENV || 'development' // Current mode
app.use(BodyParser({
detectJSON: function (ctx) {
return /\.json$/i.test(ctx.path)
},
extendTypes: {
json: ['application/x-javascript'] // will parse application/x-javascript type body as a JSON string
},
onerror: function (err, ctx) {
ctx.throw('body parse error:' + err, 422)
}
})) // Processing request
.use(KoaStatic('assets', path.resolve(__dirname, '../assets'))) // Static resource
.use(KoaSession({key: 'RESTfulAPI'})) // Set Session 生产环境务必随机设置一个值
.use(PluginLoader(SystemConfig.System_plugin_path))
.use((ctx, next) => {
if (ctx.request.header.host.split(':')[0] === 'api.XXX.com' || ctx.request.header.host.split(':')[0] === '127.0.0.1') {
ctx.set('Access-Control-Allow-Origin', '*')
ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
ctx.set('Access-Control-Allow-Credentials', true) // 允许带上 cookie
}
return next()
})
.use(MainRoutes.routes())
.use(MainRoutes.allowedMethods())
.use(ErrorRoutes())
if (env === 'development') { // logger
app.use((ctx, next) => {
const start = new Date()
return next().then(() => {
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
})
}
app.listen(SystemConfig.HTTP_server_port)
console.log('Now start HTTP server on port ' + SystemConfig.HTTP_server_port + '...')
export default app

0
src/controllers/api.js Normal file
View File

2
src/controllers/index.js Normal file
View File

@ -0,0 +1,2 @@
let requireDirectory = require('require-directory')
module.exports = requireDirectory(module)

52
src/lib/mysql.js Normal file
View File

@ -0,0 +1,52 @@
import mysql from 'promise-mysql'
import { SystemConfig } from '../config.js'
import { SqlFormat } from '../tool/common_tool.js'
let pool = mysql.createPool({
// connectionLimit: 4, // 连接池最多可以创建的连接数
host: SystemConfig.mysql_host,
user: SystemConfig.mysql_user,
password: SystemConfig.mysql_password,
database: SystemConfig.mysql_database,
port: SystemConfig.mysql_port,
insecureAuth: true
})
// 执行一行SQL语句并返回结果
export let query = (sql) => {
return pool.query(SqlFormat(sql))
}
// 执行多行SQL语句并返回结果
export let querys = (sqls) => {
let keys = Object.keys(sqls)
let list = Object.values(sqls)
let promises = list.map(function (sql) {
return query(sql)
})
return Promise.all(promises).then(data => {
let result = {}
for (let index in data) {
result[keys[index]] = data[index]
}
return result
})
}
// 返回连接
export let getSqlConnection = () => {
return pool.getConnection().disposer(function (connection) {
pool.releaseConnection(connection)
})
}
// 连接使用方法
// var Promise = require("bluebird")
// Promise.using(getSqlConnection(), function(connection) {
// return connection.query('select `name` from hobbits').then(function(row) {
// return process(rows)
// }).catch(function(error) {
// console.log(error)
// })
// })

2
src/models/index.js Normal file
View File

@ -0,0 +1,2 @@
let requireDirectory = require('require-directory')
module.exports = requireDirectory(module)

View File

@ -0,0 +1,38 @@
import nodemailer from 'nodemailer'
// 发送Email目前使用的是阿里云SMTP发送邮件
// receivers 目标邮箱,可以用英文逗号分隔多个。(我没试过)
// subject 邮件标题
// text 文本版本的邮件内容
// html HTML版本的邮件内容
// 返回
// result 200是成功500是失败
// info 是返回的消息,可能是结果的文本,也可能是对象。(这个错误不要暴露给用户)
export let sendemail = (receivers, subject, text, html) => {
return new Promise(function (resolve) {
let transporter = nodemailer.createTransport('smtp://postmaster%40abcd.com:password@smtp.abcd.com')
// setup e-mail data with unicode symbols
let mailOptions = {
from: '"XX平台 👥" <postmaster@abcd.com>', // sender address
to: receivers,
subject: subject,
text: text || 'Hello world 🐴', // plaintext body
html: html || '<b>Hello world 🐴</b>' // html body
}
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
resolve({
result: 500,
info: error
})
} else {
resolve({
result: 200,
info: info.response
})
}
})
})
}

View File

@ -0,0 +1,10 @@
module.exports = function () {
return function (ctx, next) {
switch (ctx.status) {
case 404:
ctx.body = '没有找到内容 - 404'
break
}
return next()
}
}

15
src/routes/main-routes.js Normal file
View File

@ -0,0 +1,15 @@
import KoaRouter from 'koa-router'
// import controllers from '../controllers/index.js'
const router = new KoaRouter()
router
.get('/', function (ctx, next) {
ctx.body = '禁止访问!'
}) // HOME 路由
// .get('/api/:api_type/:name', controllers.api.api_get)
// .put('/api/:api_type/:name', controllers.api_put.api_put
// .post('/api/:api_type/:name', controllers.api.default)
// .delect('/api/:api_type/:name', controllers.api.default)
module.exports = router

1
src/services/.gitkeep Normal file
View File

@ -0,0 +1 @@
1

63
src/tool/Common.js Normal file
View File

@ -0,0 +1,63 @@
import {
SystemConfig
} from '../config/main.js'
// 截取字符串,多余的部分用...代替
export let setString = (str, len) => {
let StrLen = 0
let s = ''
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 128) {
StrLen += 2
} else {
StrLen++
}
s += str.charAt(i)
if (StrLen >= len) {
return s + '...'
}
}
return s
}
// 格式化设置
export let OptionFormat = (GetOptions) => {
let options = '{'
for (let n = 0; n < GetOptions.length; n++) {
options = options + '\'' + GetOptions[n].option_name + '\':\'' + GetOptions[n].option_value + '\''
if (n < GetOptions.length - 1) {
options = options + ','
}
}
return JSON.parse(options + '}')
}
// 替换SQL字符串中的前缀
export let SqlFormat = (str) => {
if (SystemConfig.mysql_prefix !== 'bm_') {
str = str.replace(/bm_/g, SystemConfig.mysql_prefix)
}
return str
}
// 数组去重
export let HovercUnique = (arr) => {
let n = {}
let r = []
for (var i = 0; i < arr.length; i++) {
if (!n[arr[i]]) {
n[arr[i]] = true
r.push(arr[i])
}
}
return r
}
// 获取json长度
export let getJsonLength = (jsonData) => {
var arr = []
for (var item in jsonData) {
arr.push(jsonData[item])
}
return arr.length
}

34
src/tool/PluginLoader.js Normal file
View File

@ -0,0 +1,34 @@
import fs from 'fs'
import path from 'path'
import compose from 'koa-compose'
function getDirs (srcpath) {
return fs.readdirSync(srcpath).filter(file => {
return fs.statSync(path.join(srcpath, file)).isDirectory()
})
}
module.exports = (srcpath, filename = 'index.js') => {
let plugins = {}
let dirs = getDirs(srcpath)
let list = []
for (let name of dirs) {
let fn = require(path.join(srcpath, name, filename))
if (typeof fn !== 'function' && typeof fn.default === 'function') {
fn = fn.default
} else {
throw (new Error('plugin must be a function!'))
}
plugins[name] = fn
list.push(function (ctx, next) {
return fn(ctx, next) || next()
})
}
return compose(list)
}