forked from teng2015/nodeMiddleWay
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7d105c4
commit b2c3689
Showing
23 changed files
with
634 additions
and
44 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,72 @@ | ||
import Koa from 'koa' | ||
const app = new Koa() | ||
import request from './request'; | ||
// response //用户信息存入cookie | ||
app.use(async (ctx) => { | ||
var res = await request(); | ||
ctx.body = res; | ||
}) | ||
|
||
app.listen(3000, () => console.log('server started 3000')) | ||
|
||
export default app | ||
const Koa = require('koa'); | ||
const app = new Koa(); | ||
const router = require('koa-router')(); | ||
const views = require('koa-views'); | ||
const co = require('co'); | ||
const convert = require('koa-convert'); | ||
const json = require('koa-json'); | ||
const onerror = require('koa-onerror'); | ||
const bodyparser = require('koa-bodyparser')(); | ||
const logger = require('koa-logger'); | ||
|
||
const index = require('./routes/index'); | ||
const users = require('./routes/users'); | ||
const api = require('./routes/api'); | ||
const response_formatter = require('./middlewares/response_formatter'); | ||
const request_proxy = require('./middlewares/request_proxy'); | ||
// middlewares | ||
app.use(convert(bodyparser)); | ||
app.use(convert(json())); | ||
app.use(convert(logger())); | ||
app.use(require('koa-static')(__dirname + '/public')); | ||
|
||
app.use(views(__dirname + '/views', { | ||
extension: 'jade' | ||
})); | ||
//log工具 | ||
const logUtil = require('./utils/log_util'); | ||
// logger | ||
app.use(async (ctx, next) => { | ||
//响应开始时间 | ||
const start = new Date(); | ||
//响应间隔时间 | ||
var ms; | ||
try { | ||
//开始进入到下一个中间件 | ||
await next(); | ||
ms = new Date() - start; | ||
//记录响应日志 | ||
logUtil.logResponse(ctx, ms); | ||
|
||
} catch (error) { | ||
ms = new Date() - start; | ||
//记录异常日志 | ||
logUtil.logError(ctx, error, ms); | ||
} | ||
}); | ||
// logger | ||
app.use(async (ctx, next) => { | ||
const start = new Date(); | ||
await next(); | ||
const ms = new Date() - start; | ||
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); | ||
}); | ||
//添加格式化处理响应结果的中间件,在添加路由之前调用 | ||
//仅对/api开头的url进行格式化处理 | ||
app.use(response_formatter('^/api')); | ||
//request 代理 | ||
app.use(request_proxy('^/rs-server-api/v1/')); | ||
router.use('/', index.routes(), index.allowedMethods()); | ||
router.use('/users', users.routes(), users.allowedMethods()); | ||
router.use('/api', api.routes(), api.allowedMethods()); | ||
|
||
app.use(router.routes(), router.allowedMethods()); | ||
// response | ||
|
||
app.on('error', function (err, ctx) { | ||
console.log(err) | ||
logger.error('server error', err, ctx); | ||
}); | ||
|
||
|
||
module.exports = app; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
const ApiError = require('../error/ApiError'); | ||
const ApiErrorNames = require('../error/ApiErrorNames'); | ||
const Service = require('../../services/index.js'); | ||
//获取用户 | ||
exports.getUser = async (ctx, next) => { | ||
//如果id != 1抛出API 异常 | ||
// if (ctx.query.id != 1) { | ||
// throw new ApiError(ApiErrorNames.USER_NOT_EXIST); | ||
// } | ||
var goodsList = await Service.fetchGoodsList().then((response) => { | ||
return response.data; | ||
}); | ||
ctx.body = { | ||
goodsList: goodsList, | ||
username: '阿,希爸', | ||
age: 30 | ||
} | ||
} | ||
//用户注册 | ||
exports.registerUser = async (ctx, next) => { | ||
console.log('registerUser', ctx.request.body); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
const ApiErrorNames = require('./ApiErrorNames'); | ||
|
||
/** | ||
* 自定义Api异常 | ||
*/ | ||
class ApiError extends Error{ | ||
//构造方法 | ||
constructor(error_name){ | ||
super(); | ||
|
||
var error_info = ApiErrorNames.getErrorInfo(error_name); | ||
|
||
this.name = error_name; | ||
this.code = error_info.code; | ||
this.message = error_info.message; | ||
} | ||
} | ||
|
||
module.exports = ApiError; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
/** | ||
* API错误名称 | ||
*/ | ||
var ApiErrorNames = {}; | ||
|
||
ApiErrorNames.UNKNOW_ERROR = "unknowError"; | ||
ApiErrorNames.USER_NOT_EXIST = "userNotExist"; | ||
|
||
/** | ||
* API错误名称对应的错误信息 | ||
*/ | ||
const error_map = new Map(); | ||
|
||
error_map.set(ApiErrorNames.UNKNOW_ERROR, { code: -1, message: '未知错误' }); | ||
error_map.set(ApiErrorNames.USER_NOT_EXIST, { code: 101, message: '用户不存在' }); | ||
|
||
//根据错误名称获取错误信息 | ||
ApiErrorNames.getErrorInfo = (error_name) => { | ||
|
||
var error_info; | ||
|
||
if (error_name) { | ||
error_info = error_map.get(error_name); | ||
} | ||
|
||
//如果没有对应的错误信息,默认'未知错误' | ||
if (!error_info) { | ||
error_name = UNKNOW_ERROR; | ||
error_info = error_map.get(error_name); | ||
} | ||
|
||
return error_info; | ||
} | ||
|
||
module.exports = ApiErrorNames; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
#!/usr/bin/env node | ||
|
||
var current_path = process.cwd(); | ||
|
||
require('runkoa')(current_path + '/bin/www' ) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
#!/usr/bin/env node | ||
// 创建日志文件START | ||
var fs = require('fs'); | ||
var logConfig = require('../config/log_config'); | ||
|
||
/** | ||
* 确定目录是否存在,如果不存在则创建目录 | ||
*/ | ||
var confirmPath = function (pathStr) { | ||
|
||
if (!fs.existsSync(pathStr)) { | ||
fs.mkdirSync(pathStr); | ||
console.log('createPath: ' + pathStr); | ||
} | ||
} | ||
|
||
/** | ||
* 初始化log相关目录 | ||
*/ | ||
var initLogPath = function () { | ||
//创建log的根目录'logs' | ||
if (logConfig.baseLogPath) { | ||
confirmPath(logConfig.baseLogPath) | ||
//根据不同的logType创建不同的文件目录 | ||
for (var i = 0, len = logConfig.appenders.length; i < len; i++) { | ||
if (logConfig.appenders[i].path) { | ||
confirmPath(logConfig.baseLogPath + logConfig.appenders[i].path); | ||
} | ||
} | ||
} | ||
} | ||
|
||
initLogPath(); | ||
// 创建日志文件END | ||
|
||
|
||
|
||
|
||
/** | ||
* Module dependencies. | ||
*/ | ||
|
||
var app = require('../app'); | ||
var debug = require('debug')('demo:server'); | ||
var http = require('http'); | ||
//引入配置文件 | ||
var config = require('../config'); | ||
|
||
/** | ||
* Get port from environment and store in Express. | ||
*/ | ||
|
||
// 将端口号设置为配置文件的端口号,默认值为3000 | ||
var port = normalizePort(config.port || '3000'); | ||
// 打印输出端口号 | ||
console.log('port = ' + config.port); | ||
// app.set('port', port); | ||
|
||
/** | ||
* Create HTTP server. | ||
*/ | ||
|
||
var server = http.createServer(app.callback()); | ||
|
||
/** | ||
* Listen on provided port, on all network interfaces. | ||
*/ | ||
|
||
server.listen(port); | ||
server.on('error', onError); | ||
server.on('listening', onListening); | ||
|
||
/** | ||
* Normalize a port into a number, string, or false. | ||
*/ | ||
|
||
function normalizePort(val) { | ||
var port = parseInt(val, 10); | ||
|
||
if (isNaN(port)) { | ||
// named pipe | ||
return val; | ||
} | ||
|
||
if (port >= 0) { | ||
// port number | ||
return port; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
/** | ||
* Event listener for HTTP server "error" event. | ||
*/ | ||
|
||
function onError(error) { | ||
if (error.syscall !== 'listen') { | ||
throw error; | ||
} | ||
|
||
var bind = typeof port === 'string' | ||
? 'Pipe ' + port | ||
: 'Port ' + port; | ||
|
||
// handle specific listen errors with friendly messages | ||
switch (error.code) { | ||
case 'EACCES': | ||
console.error(bind + ' requires elevated privileges'); | ||
process.exit(1); | ||
break; | ||
case 'EADDRINUSE': | ||
console.error(bind + ' is already in use'); | ||
process.exit(1); | ||
break; | ||
default: | ||
throw error; | ||
} | ||
} | ||
|
||
/** | ||
* Event listener for HTTP server "listening" event. | ||
*/ | ||
|
||
function onListening() { | ||
var addr = server.address(); | ||
var bind = typeof addr === 'string' | ||
? 'pipe ' + addr | ||
: 'port ' + addr.port; | ||
debug('Listening on ' + bind); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
/** | ||
* 开发环境的配置内容 | ||
*/ | ||
|
||
module.exports = { | ||
env: 'development', //环境名称 | ||
port: 3001, //服务端口号 | ||
mongodb_url: '', //数据库地址 | ||
redis_url: '', //redis地址 | ||
redis_port: '' //redis端口号 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
var development_env = require('./development'); | ||
var test_env = require('./test'); | ||
|
||
//根据不同的NODE_ENV,输出不同的配置对象,默认输出development的配置对象 | ||
module.exports = { | ||
development: development_env, | ||
test: test_env | ||
}[process.env.NODE_ENV || 'development'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
var path = require('path'); | ||
|
||
//日志根目录 | ||
var baseLogPath = path.resolve(__dirname, '../logs') | ||
|
||
//错误日志目录 | ||
var errorPath = "/error"; | ||
//错误日志文件名 | ||
var errorFileName = "error"; | ||
//错误日志输出完整路径 | ||
var errorLogPath = baseLogPath + errorPath + "/" + errorFileName; | ||
// var errorLogPath = path.resolve(__dirname, "../logs/error/error"); | ||
|
||
|
||
//响应日志目录 | ||
var responsePath = "/response"; | ||
//响应日志文件名 | ||
var responseFileName = "response"; | ||
//响应日志输出完整路径 | ||
var responseLogPath = baseLogPath + responsePath + "/" + responseFileName; | ||
// var responseLogPath = path.resolve(__dirname, "../logs/response/response"); | ||
|
||
module.exports = { | ||
"appenders": | ||
[ | ||
//错误日志 | ||
{ | ||
"category": "errorLogger", //logger名称 | ||
"type": "dateFile", //日志类型 | ||
"filename": errorLogPath, //日志输出位置 | ||
"alwaysIncludePattern": true, //是否总是有后缀名 | ||
"pattern": "-yyyy-MM-dd-hh.log", //后缀,每小时创建一个新的日志文件 | ||
"path": errorPath //自定义属性,错误日志的根目录 | ||
}, | ||
//响应日志 | ||
{ | ||
"category": "resLogger", | ||
"type": "dateFile", | ||
"filename": responseLogPath, | ||
"alwaysIncludePattern": true, | ||
"pattern": "-yyyy-MM-dd-hh.log", | ||
"path": responsePath | ||
} | ||
], | ||
"levels": //设置logger名称对应的的日志等级 | ||
{ | ||
"errorLogger": "ERROR", | ||
"resLogger": "ALL" | ||
}, | ||
"baseLogPath": baseLogPath //logs根目录 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
/** | ||
* 测试环境的配置内容 | ||
*/ | ||
|
||
module.exports = { | ||
env: 'test', //环境名称 | ||
port: 3002, //服务端口号 | ||
mongodb_url: '', //数据库地址 | ||
redis_url: '', //redis地址 | ||
redis_port: '' //redis端口号 | ||
} |
Oops, something went wrong.