1 | 'use strict';
|
2 |
|
3 | var async = require('async');
|
4 | var Quota = require('volos-quota-memory');
|
5 | var debug = require('debug')('gateway:quota');
|
6 |
|
7 | module.exports.init = function(config, logger, stats) {
|
8 | var quotas = {};
|
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;
|
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;
|
32 |
|
33 |
|
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 | };
|