Debian Codegraph @

memoizee/ext/max-age.js

raw
1 /* eslint consistent-this: 0 */
2
3 // Timeout cached values
4
5 "use strict";
6
7 var aFrom = require("es5-ext/array/from")
8 , forEach = require("es5-ext/object/for-each")
9 , nextTick = require("next-tick")
10 , isPromise = require("is-promise")
11 , timeout = require("timers-ext/valid-timeout")
12 , extensions = require("../lib/registered-extensions");
13
14 var noop = Function.prototype, max = Math.max, min = Math.min, create = Object.create;
15
16 extensions.maxAge = function (maxAge, conf, options) {
17 var timeouts, postfix, preFetchAge, preFetchTimeouts;
18
19 maxAge = timeout(maxAge);
20 if (!maxAge) return;
21
22 timeouts = create(null);
23 postfix =
24 (options.async && extensions.async) || (options.promise && extensions.promise)
25 ? "async"
26 : "";
27 conf.on("set" + postfix, function (id) {
28 timeouts[id] = setTimeout(function () { conf.delete(id); }, maxAge);
29 if (typeof timeouts[id].unref === "function") timeouts[id].unref();
30 if (!preFetchTimeouts) return;
31 if (preFetchTimeouts[id]) {
32 if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]);
33 }
34 preFetchTimeouts[id] = setTimeout(function () {
35 delete preFetchTimeouts[id];
36 }, preFetchAge);
37 if (typeof preFetchTimeouts[id].unref === "function") preFetchTimeouts[id].unref();
38 });
39 conf.on("delete" + postfix, function (id) {
40 clearTimeout(timeouts[id]);
41 delete timeouts[id];
42 if (!preFetchTimeouts) return;
43 if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]);
44 delete preFetchTimeouts[id];
45 });
46
47 if (options.preFetch) {
48 if (options.preFetch === true || isNaN(options.preFetch)) {
49 preFetchAge = 0.333;
50 } else {
51 preFetchAge = max(min(Number(options.preFetch), 1), 0);
52 }
53 if (preFetchAge) {
54 preFetchTimeouts = {};
55 preFetchAge = (1 - preFetchAge) * maxAge;
56 conf.on("get" + postfix, function (id, args, context) {
57 if (!preFetchTimeouts[id]) {
58 preFetchTimeouts[id] = "nextTick";
59 nextTick(function () {
60 var result;
61 if (preFetchTimeouts[id] !== "nextTick") return;
62 delete preFetchTimeouts[id];
63 conf.delete(id);
64 if (options.async) {
65 args = aFrom(args);
66 args.push(noop);
67 }
68 result = conf.memoized.apply(context, args);
69 if (options.promise) {
70 // Supress eventual error warnings
71 if (isPromise(result)) {
72 if (typeof result.done === "function") result.done(noop, noop);
73 else result.then(noop, noop);
74 }
75 }
76 });
77 }
78 });
79 }
80 }
81
82 conf.on("clear" + postfix, function () {
83 forEach(timeouts, function (id) { clearTimeout(id); });
84 timeouts = {};
85 if (preFetchTimeouts) {
86 forEach(preFetchTimeouts, function (id) { if (id !== "nextTick") clearTimeout(id); });
87 preFetchTimeouts = {};
88 }
89 });
90 };