UNPKG

1.21 kBJavaScriptView Raw
1
2'use strict';
3
4module.exports = function (config) {
5 return {
6 filters: [],
7
8 getBase: function (data, key) {
9 if (data && data.article && data.article[key]) {
10 return data.article;
11 }
12 if (data && data[key]) {
13 return data;
14 }
15 return null;
16 },
17
18 add: function (filter) {
19 this.filters.push(filter);
20 },
21
22 run: function (req, res, data, callback) {
23 var self = this;
24
25 var runner = function (filters, data) {
26 var remain;
27 var filter;
28 var arity;
29 var cb;
30
31 if (filters.length > 0) {
32 filter = filters[0];
33 remain = filters.slice(1);
34 cb = function (data) {
35 runner(remain, data);
36 };
37 arity = filter.length;
38
39 if (arity === 1) {
40 runner(remain, filter.call(self, data));
41 } else if (arity === 2) {
42 filter.call(self, data, cb);
43 } else if (arity === 3) {
44 filter.call(self, config, data, cb);
45 } else if (arity === 5) {
46 filter.call(self, config, req, res, data, cb);
47 } else {
48 config.log.error('Input filters must accept 1, 2, 3 or 5 arguments ' + arity + ' found');
49 runner(remain, data);
50 }
51 } else {
52 callback(data);
53 }
54 };
55 runner(this.filters, data);
56 }
57 };
58};