UNPKG

1.88 kBJavaScriptView Raw
1/**
2 * Imports
3 */
4
5'use strict';
6
7Object.defineProperty(exports, '__esModule', {
8 value: true
9});
10
11function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
12
13var _componentCookie = require('component-cookie');
14
15var _componentCookie2 = _interopRequireDefault(_componentCookie);
16
17/**
18 * Action types
19 */
20
21var GET_COOKIE = 'EFFECT_GET_COOKIE';
22var SET_COOKIE = 'EFFECT_SET_COOKIE';
23
24/**
25 * Cookie middleware
26 */
27
28function cookieMiddleware(cookieMap) {
29 var cookie = cookieMap ? map(cookieMap) : _componentCookie2['default'];
30
31 return function (_ref) {
32 var dispatch = _ref.dispatch;
33 var getState = _ref.getState;
34 return function (next) {
35 return function (action) {
36 return action.type === GET_COOKIE || action.type === SET_COOKIE ? Promise.resolve(handle(cookie, action)) : next(action);
37 };
38 };
39 };
40}
41
42/**
43 * Handle a cookie effect
44 */
45
46function handle(cookie, action) {
47 var _action$payload = action.payload;
48 var name = _action$payload.name;
49 var value = _action$payload.value;
50 var opts = _action$payload.opts;
51
52 switch (action.type) {
53 case SET_COOKIE:
54 return cookie(name, value, opts);
55 case GET_COOKIE:
56 return cookie(name);
57 }
58}
59
60/**
61 * Use a plain object as the source of cookie data
62 * (e.g. if we're on the server)
63 */
64
65function map(cookieMap) {
66 return function (name, value) {
67 if (arguments.length > 1) {
68 cookieMap[name] = value;
69 }
70
71 return cookieMap[name];
72 };
73}
74
75/**
76 * Action creator
77 */
78
79function cookie(name, value) {
80 var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
81
82 return arguments.length > 1 ? { type: SET_COOKIE, payload: { name: name, value: value, opts: opts } } : { type: GET_COOKIE, payload: { name: name } };
83}
84
85/**
86 * Exports
87 */
88
89exports['default'] = cookieMiddleware;
90exports.cookie = cookie;
\No newline at end of file