-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (67 loc) · 2.03 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';
var isValid = require('is-valid-app');
var stashObject = require('stash-object');
module.exports = function(config) {
return function(app) {
if (!isValid(app, 'base-stash', ['base'])) {
return;
}
var cache = {};
var stack = {};
/**
* Stash an object property from the app with an optional "name".
*
* ```js
* app.stash('options');
* ```
* @name .stash
* @param {String} `prop` Property to stash (e.g. `options` or `cache`);
* @param {String} `name` Name to use to "tag" the stash to restore from later.
* @api public
*/
this.define('stash', function(prop, name) {
var stash = getStash(prop);
name = name || 'default';
pushStack(prop, name);
stash.stash(name);
return this;
});
/**
* Restore a previously stashed object. Optionally restore from a specific "name" that was used with `.stash`.
* When a "name" is not specified, the last stashed object is used.
*
* ```js
* app.restore('options');
* ```
* @name .restore
* @param {String} `prop` Property to restore (e.g. `options` or `cache`);
* @param {String} `name` Name used when stashing to restore directly to that spot.
* @api public
*/
this.define('restore', function(prop, name) {
var stash = getStash(prop);
name = popStack(prop, name);
app[prop] = stash.restore(name);
return this;
});
function getStash(prop) {
if (typeof app[prop] !== 'object') {
throw new TypeError(`expected "app.${prop}" to be an object`);
}
return cache[prop] = (cache[prop] || stashObject(app[prop]));
}
function pushStack(prop, name) {
stack[prop] = stack[prop] || [];
stack[prop].push(name);
}
function popStack(prop, name) {
stack[prop] = stack[prop] || [];
if (!name) {
name = stack[prop].pop();
} else if (name === stack[prop][stack[prop].length - 1]) {
stack[prop].pop();
}
return name;
}
};
};