-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (89 loc) · 2.53 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
const Koa = require('koa');
const isPlainObject = require('lodash.isplainobject');
/**
* Set in context middleware for Koa 2 application.
*/
module.exports = function setInContextMiddleware(props, value) {
/**
* We have an array of objects.
* Check that the object have the correct form.
* With the properties "name and value".
* If any of the objects doesn't comply with the form,
* throw an error.
*/
if (Array.isArray(props) && !(props.every(isObjectAndHasCorrectForm))) {
throw new Error(`
When passing an array of objects they must in the form of:
[{
name: 'name-of-your-property',
value: 'your value'
}]
`);
}
/**
* If we only have an object, check that it has the correct form.
* "name and value". If not throw an error.
*/
if (isObjectAndHasCorrectForm(props)) {
throw new Error(`
When passing an object it must be in the form of:
{
name: 'name-of-your-property',
value: 'your value'
}
`);
}
/**
* Return the actual middleware.
*/
return function setInContext(ctx, next) {
setPropertiesIntoState(ctx.state, props, value);
return next();
};
};
/**
* setPropertiesIntoState: Actual function that normalizes the parameters
* that the user passes so we can work with easely.
*
* If a string is passed, create an array with only one object with the form
* 'key', 'value' => [{ name: 'key', value: 'value' }]
*
* If an object is given, just wrap it in an array.
* { name: 'key', value: 'value' } => [{ name: 'key', value: 'value' }]
*
* If an array of objects is given, just continue.
*
* @param Object state The "context.state" of the request.
* @param mixed props The key|value to set in the context.
* @param mixed value The value to set in the context, if "props" is a string.
* @return void
*/
function setPropertiesIntoState(state, props, value) {
let _props;
if (typeof props === 'string') {
_props = [{
name: props,
value: value
}];
} else if (isPlainObject(props)) {
_props = [props];
} else if (Array.isArray(props)) {
_props = props;
}
_props.forEach(prop => {
state[prop.name] = prop.value;
});
}
/**
* isObjectAndHasCorrectForm: Check whether "obj" is
* plain object with the form: { name: 'key', value: 'value' }.
*
* @param mixed obj The value to check.
* @return Boolean
*/
function isObjectAndHasCorrectForm(obj) {
return isPlainObject(obj) &&
obj.hasOwnProperty('name') &&
obj.hasOwnProperty('value');
}