UNPKG

1.57 kBJavaScriptView Raw
1'use strict';
2
3var async = require('async');
4var Quota = require('volos-quota-memory');
5var debug = require('debug')('gateway:quota');
6
7module.exports.init = function(config, logger, stats) {
8 var quotas = {}; // productName -> connectMiddleware
9
10 var options = {
11 key: function(req) { return req.token.application_name; }
12 };
13
14 Object.keys(config).forEach(function(productName) {
15 var product = config[productName];
16 if (!product.uri && !product.key && !product.secret && !product.allow && !product.interval) {
17 return; // skip non-quota config
18 }
19
20 var quota = Quota.create(config[productName]);
21 quotas[productName] = quota.connectMiddleware().apply(options);
22 debug('created quota for', productName);
23 });
24
25 var middleware = function(req, res, next) {
26
27 if (!req.token || !req.token.api_product_list || !req.token.api_product_list.length) { return next(); }
28
29 debug('quota checking products', req.token.api_product_list);
30
31 req.originalUrl = req.originalUrl || req.url; // emulate connect
32
33 // this is arbitrary, but not sure there's a better way?
34 async.eachSeries(req.token.api_product_list,
35 function(productName, cb) {
36 var connectMiddleware = quotas[productName];
37 debug('applying quota for', productName);
38 connectMiddleware ? connectMiddleware(req, res, cb) : cb();
39 },
40 function(err) {
41 next(err);
42 }
43 );
44 }
45
46 return {
47
48 testprobe: function() { return quotas },
49
50 onrequest: function(req, res, next) {
51 middleware(req, res, next);
52 }
53
54 }
55};