$ npm install koa-connection-limit
const koa = require('koa');
const koaConnectionLimit = require('koa-connection-limit');
const app = koa();
app.use(koaConnectionLimit({
mid: 5,
high: 10,
throwError: false,
pass: (ctx) => {
return false;
}
}, function (status) {
// status: low, mid, high
console.info(status);
}));
mid
mid connection limit counthigh
high connection limit countthrowError
whentrue
orundefined
, the connection count reach high limit count, it will throw errorpass
if the function return true, the request will be ingore of limiterr
the custom define error, optional
when status change, the function will be triggered
'use strict';
const Koa = require('koa');
const app = new Koa();
const koaConnectionLimit = require('koa-connection-limit');
// 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.use(koaConnectionLimit({
high: 2,
mid: 1,
throwError: false,
pass: (ctx) => {
return ctx.url === '/no-limit';
},
}, function changeStatus(status) {
console.info(status);
}));
app.use((ctx, next) => {
const delay = new Promise(function(resolve, reject) {
setTimeout(resolve, 3000);
});
return delay.then(next);
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
MIT