├── .babelrc ├── .eslintrc ├── .gitignore ├── .npmignore ├── LICENSE ├── Makefile ├── README.md ├── api.js ├── index.js ├── package.json ├── scripts ├── mocha_runner.js └── prepublish.sh ├── src ├── __tests__ │ ├── index.js │ ├── lib │ │ ├── apiClient.spec.js │ │ ├── constants.spec.js │ │ ├── createApiActions.spec.js │ │ ├── createApiHandler.spec.js │ │ ├── createApiMiddleware.spec.js │ │ ├── createReducer.spec.js │ │ ├── createRootReducer.spec.js │ │ └── utils.spec.js │ └── spec_helpers.js ├── api.js ├── index.js └── lib │ ├── actions.js │ ├── apiClient.js │ ├── bindActionCreatorsToStore.js │ ├── constants.js │ ├── createApiActions.js │ ├── createApiHandler.js │ ├── createApiMiddleware.js │ ├── createReducer.js │ ├── createRootReducer.js │ └── utils.js ├── webpack.config.js └── www ├── Container.js ├── global.styles.css ├── index.js ├── readme.js └── styles.module.css /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["es2015", "react", "stage-0"], 3 | "env": { 4 | "development": { 5 | "presets": ["react-hmre"] 6 | }, 7 | "test": { 8 | "presets": [] 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "env": { 4 | "browser": true, 5 | "node": true, 6 | "es6": true 7 | }, 8 | "ecmaFeatures": { 9 | "modules": true 10 | }, 11 | "rules": { 12 | "no-bitwise": 2, 13 | "no-else-return": 2, 14 | "no-eq-null": 2, 15 | "no-extra-parens": 0, 16 | "no-floating-decimal": 2, 17 | "no-inner-declarations": [2, "both"], 18 | "no-lonely-if": 2, 19 | "no-multiple-empty-lines": [2, {"max": 3}], 20 | "no-self-compare": 2, 21 | "no-underscore-dangle": 0, 22 | "no-use-before-define": 0, 23 | "no-unused-expressions": 0, 24 | "no-void": 2, 25 | "brace-style": [2, "1tbs"], 26 | "camelcase": [1, {"properties": "never"}], 27 | "consistent-return": 0, 28 | "comma-style": [2, "last"], 29 | "complexity": [1, 12], 30 | "func-names": 0, 31 | "guard-for-in": 2, 32 | "max-len": [0, 120, 4], 33 | "new-cap": [2, {"newIsCap": true, "capIsNew": false}], 34 | "quotes": [2, "single"], 35 | "keyword-spacing": [2, {"before": true, "after": true}], 36 | "space-before-blocks": [2, "always"], 37 | "array-bracket-spacing": [2, "never"], 38 | "space-in-parens": [2, "never"], 39 | "strict": [0], 40 | "valid-jsdoc": 2, 41 | "wrap-iife": [2, "any"], 42 | "yoda": [1, "never"] 43 | }, 44 | "plugins": [ 45 | "react" 46 | ], 47 | "globals": { 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *~ 3 | *.iml 4 | .*.haste_cache.* 5 | .DS_Store 6 | .idea 7 | npm-debug.log 8 | node_modules 9 | .env 10 | public/ 11 | dist/ 12 | .DS_Store 13 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *~ 3 | *.iml 4 | .*.haste_cache.* 5 | .DS_Store 6 | .idea 7 | .babelrc 8 | .eslintrc 9 | npm-debug.log 10 | src/ 11 | examples/ 12 | public/ 13 | scripts/ 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Julian Ćwirko 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: publish dev test example 2 | 3 | dev: 4 | npm run dev 5 | 6 | build: 7 | npm run prepublish 8 | 9 | publish: 10 | npm version patch 11 | npm publish . 12 | 13 | test: 14 | npm run test 15 | 16 | testwatch: 17 | npm run test-watch 18 | 19 | example: 20 | npm run build 21 | 22 | publish_pages: example 23 | gh-pages -d ./public 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Redux modules 2 | 3 | The `redux-modules` package offers a different method of handling [redux](http://redux.js.org/) module packaging. 4 | 5 | The overall idea behind `redux-modules` is to build all of the corresponding redux functionality, constants, reducers, actions in a common location that makes it easy to understand the entire workflow common to a component of an application. 6 | 7 | Redux modules is essentially a collection of helpers that provide functionality for common tasks related to using Redux. 8 | 9 | ## Quick take 10 | 11 | A redux module enables us to build our redux modules in a simple manner. A redux module can be as simple as: 12 | 13 | ```javascript 14 | /** 15 | * Creates a `types` object 16 | * with the hash of constants 17 | **/ 18 | const types = createConstants({ 19 | prefix: 'TODO' 20 | })( 21 | 'CREATE', 22 | 'MARK_DONE', 23 | 'FETCH_ALL': {api: true} 24 | ); 25 | 26 | /** 27 | * The root reducer that handles only create 28 | **/ 29 | const reducer = createReducer({ 30 | [types.CREATE]: (state, {payload}) => ({ 31 | ...state, 32 | todos: state.todos.concat(payload) 33 | }), 34 | 35 | // decorator form 36 | @apiHandler(types.FETCH_ALL, (apiTypes) => { 37 | // optional overrides 38 | [apiTypes.FETCH_ALL_LOADING]: (state, action) => ({...state, loading: true}) 39 | }) 40 | handleFetchAll: (state, action) => ({...state, todos: action.payload}) 41 | 42 | // or non-decorator form: 43 | handleFetchAll: createApiHandler(types.FETCH_ALL)((state, action) => { 44 | return {...state, todos: action.payload}; 45 | }) 46 | }) 47 | 48 | /** 49 | * Actions 50 | **/ 51 | const actions = createActions({ 52 | createTodo: (text) => (dispatch) => dispatch({ 53 | type: types.CREATE, 54 | payload: {text: text, done: false} 55 | }), 56 | 57 | // decorator form 58 | @api(types.FETCH_ALL) 59 | fetchAll: (client, opts) => client.get({path: '/todos'}) 60 | 61 | // or non-decorator form 62 | fetchAll: createApiAction(types.FETCH_ALL)((client, opts) => { 63 | return () => (dispatch, getState) => client.get('/todos') 64 | }) 65 | }) 66 | ``` 67 | 68 | In our app, our entire todo handler, reducer, and actions are all in one place in a single file. Incorporating the handler, reducer, and actions in our redux app is up to you. See [Usage in Redux](#usage-with-react-redux) for information. 69 | 70 | ## Installation 71 | 72 | ```bash 73 | npm install --save redux-module-builder 74 | ``` 75 | 76 | ## Example 77 | 78 | For example, let's take the idea of writing a TODO application. We'll need a few actions: 79 | 80 | * Create 81 | * Mark done 82 | * Fetch All 83 | 84 | Using `redux-modules`, we can create an object that carries a unique _type_ string for each of the actions in namespace path on a type object using the `createConstants()` exported method. For instance: 85 | 86 | ```javascript 87 | const types = createConstants('TODO')({ 88 | 'CREATE': true, // value is ignored 89 | 'FETCH_ALL': {api: true} 90 | }) 91 | ``` 92 | 93 |
94 | 95 | If you prefer not to use any of the api helpers included with `redux-modules`, the `createConstants()` function accepts a simple list of types instead: 96 | 97 | ```javascript 98 | const types = createConstants('TODO')( 99 | 'CREATE', 'MARK_DONE', 'DELETE' 100 | ) 101 | ``` 102 | 103 | ## createReducer 104 | 105 | The `createReducer()` exported function is a simple reduce handler. It accepts a single object and is responsible for passing action handling down through defined functions on a per-action basis. 106 | 107 | The first argument object is the list of handlers, by their type with a function to be called on the dispatch of the action. For instance, from our TODO example, this object might look like: 108 | 109 | ```javascript 110 | const reducer = createReducer({ 111 | [types.CREATE]: (state, {payload}) => ({ 112 | ...state, 113 | todos: state.todos.concat(payload) 114 | }) 115 | }); 116 | ``` 117 | 118 | The previous object defines a handler for the `types.CREATE` action type, but does not define one for the `types.FETCH_ALL`. When the `types.CREATE` type is dispatched, the function above runs and is considered the reducer for the action. In this example, when the `types.FETCH_ALL` action is dispatched, the default handler: `(state, action) => state` is called (aka the original state). 119 | 120 | To add handlers, we only need to define the key and value function. 121 | 122 | ## API handling 123 | 124 | The power of `redux-modules` really comes into play when dealing with async code. The common pattern of handling async API calls, which generates multiple states. 125 | 126 | Notice in our above example we can mark types as `api: true` within a type object and notice that it created 4 action key/values in the object which correspond to different states of an api call (loading, success, error, and the type itself). We can use this pattern to provide simple api handling to any action/reducer. 127 | 128 | ### apiMiddleware 129 | 130 | In order to set this up, we need to add a middleware to our redux stack. This middleware helps us define defaults for handling API requests. For instance. In addition, `redux-modules` depends upon [redux-thunk](https://github.com/gaearon/redux-thunk) being available as a middleware _after_ the apiMiddleware. 131 | 132 | For instance: 133 | 134 | ```javascript 135 | // ... 136 | let todoApp = combineReducers(reducers) 137 | let apiMiddleware = createApiMiddleware({ 138 | baseUrl: `https://fullstackreact.com`, 139 | headers: {} 140 | }); 141 | let store = createStore(reducers, 142 | applyMiddleware(apiMiddleware, thunk)); 143 | // ... 144 | ``` 145 | 146 | The object the `createApiMiddleware()` accepts is the default configuration for all API requests. For instance, this is a good spot to add custom headers, a `baseUrl` (required), etc. Whatever we pass in here is accessible across every api client. 147 | 148 | For more _dynamic_ requests, we can pass a function into any one of these options and it will be called with the state so we can dynamically respond. An instance where we might want to pass a function would be with our headers, which might respond with a token for every request. Another might be a case for A/B testing where we can dynamically assign the `baseUrl` on a per-user basis. 149 | 150 | ```javascript 151 | // dynamically adding headers for _every_ request: 152 | let apiMiddleware = createApiMiddleware({ 153 | baseUrl: `https://fullstackreact.com`, 154 | headers: (state) => ({ 155 | 'X-Auth-Token': state.user.token 156 | }) 157 | }); 158 | ``` 159 | 160 | The `apiMiddleware` above currently decorates an actions `meta` object. For instance: 161 | 162 | ```javascript 163 | { 164 | type: 'API_FETCH_ALL', 165 | payload: {}, 166 | meta: {isApi: true} 167 | } 168 | // passes to the `thunk` middleware the resulting action: 169 | { 170 | type: 'API_FETCH_ALL', 171 | payload: {}, 172 | meta: { 173 | isApi: true, 174 | baseUrl: BASE_URL, 175 | headers: {} 176 | } 177 | } 178 | ``` 179 | 180 | ### apiActions 181 | 182 | The easiest way to take advantage of this api infrastructure is to decorate the actions with the `@api` decorator (or the non-decorator form `createApiAction()`). When calling an api action created with the `@api/createApiAction`, `redux-modules` will dispatch two actions, the loading action and the handler. 183 | 184 | The `loading` action is fired with the type `[NAMESPACE]_loading`. The second action it dispatches is the handler function. The method that it is decorated with is expected to return a promise (although `redux-modules` will convert the response to a promise if it's not already one) which is expected to resolve in the case of success and error otherwise. 185 | 186 | More conveniently, `redux-modules` provides a client instance of [ApiClient](https://github.com/fullstackreact/redux-modules/blob/master/src/lib/apiClient.js) for every request (which is a thin wrapper around `fetch`). 187 | 188 | ```javascript 189 | // actions 190 | @api(types.FETCH_ALL) 191 | fetchAll: (client, opts) => { 192 | return client.get({ 193 | path: '/news' 194 | }).then((json) => { 195 | return json; 196 | }); 197 | } 198 | ``` 199 | 200 | The `apiClient` includes handling for request transformations, status checking, and response transformations. We'll look at those in a minute. The `apiClient` instance includes the HTTP methods: 201 | 202 | * GET 203 | * POST 204 | * PUT 205 | * PATCH 206 | * DELETE 207 | * HEAD 208 | 209 | These methods can be called on the client itself: 210 | 211 | ```javascript 212 | client.get({}) 213 | client.post({}) 214 | client.put({}) 215 | ``` 216 | 217 | When they are called, they will be passed a list of options, which includes the base options (passed by the middleware) combined with custom options passed to the client (as the first argument). 218 | 219 | #### api client options 220 | 221 | The `apiClient` methods accept an argument of options for a per-api request customization. The following options are available and each can be either an atomic value or a function which gets called with the api request options within the client itself _or_ in the `baseOpts` of the middleware. 222 | 223 | When defining these options in the middleware, keep in mind that they will be available for every request passed by the `client` instance. 224 | 225 | 1. path 226 | 227 | If a `path` option is found, `apiClient` will append the path to the `baseUrl`. If the `client` is called with a single _string_ argument, then it is considered the `path`. For instance: 228 | 229 | ```javascript 230 | // the following are equivalent 231 | client.get('/foo') 232 | client.get({path: '/foo'}) 233 | // each results in a GET request to [baseUrl]/foo 234 | ``` 235 | 236 | 2. url 237 | 238 | To completely ignore the `baseUrl` for a request, we can pass the `url` option which is used for the request. 239 | 240 | ```javascript 241 | client.get({url: 'http://google.com/?q=fullstackreact'}) 242 | ``` 243 | 244 | 3. appendPath 245 | 246 | For dynamic calls, sometimes it's convenient to add a component to the path. For instance, we might want to append the url with a custom session key. 247 | 248 | ```javascript 249 | client.get({appendPath: 'abc123'}) 250 | ``` 251 | 252 | 4. appendExt 253 | 254 | The `appendExt` is primarily useful for padding extensions on a url. For instance, to make all requests to the url with the `.json` extension, we can pass the `appendExt` to json: 255 | 256 | ```javascript 257 | client.get({appendExt: 'json'}) 258 | ``` 259 | 260 | 5. params 261 | 262 | The `params` option is a query-string list of parameters that will be passed as query-string options. 263 | 264 | ```javascript 265 | client.get({params: {q: 'fullstackreact'}}) 266 | ``` 267 | 268 | 6. headers 269 | 270 | Every request can define their own headers (or globally with the middleware) by using the `headers` option: 271 | 272 | ```javascript 273 | client.get({headers: {'X-Token': 'bearer someTokenThing'}}) 274 | ``` 275 | 276 | #### transforms 277 | 278 | The request and response transforms provide a way to manipulate requests as they go out and and they return. These are functions that are called with the `state` as well as the current request options. 279 | 280 | #### requestTransforms 281 | 282 | Request transforms are functions that can be defined to create a dynamic way to manipulate headers, body, etc. For instance, if we want to create a protected route, we can use a requestTransform to append a custom header. 283 | 284 | ```javascript 285 | client.get({ 286 | requestTransforms: [(state, opts) => req => { 287 | req.headers['X-Name'] = 'Ari'; 288 | return req; 289 | }] 290 | }) 291 | ``` 292 | 293 | #### responseTransforms 294 | 295 | A response transform handles the resulting request response and gives us an opportunity to transform the data to another format on the way in. The default response transform is to respond with the response body into json. To handle the actual response, we can assign a responseTransform to overwrite the default json parsing and get a handle on the actual fetch response. 296 | 297 | ```javascript 298 | let timeTransform = (state, opts) => res => { 299 | res.headers.set('X-Response-Time', time); 300 | return res; 301 | } 302 | let jsonTransform = (state, opts) => (res) => { 303 | let time = res.headers.get('X-Response-Time'); 304 | return res.json().then(json => ({...json, time})) 305 | } 306 | client.get({ 307 | responseTransforms: [timeTransform, jsonTransform] 308 | }) 309 | ``` 310 | 311 | For apis that do not respond with json, the `responseTransforms` are a good spot to handle conversion to another format, such as xml. 312 | 313 | ### apiHandlers 314 | 315 | To handle api responses in a reducer, `redux-modules` provides the `apiHandler` decorator (and it's non-decorator form: `createApiHandler()`). This decorator provides a common interface for handling the different states of an api request (i.e. `loading`, `success`, and `error` states). 316 | 317 | ```javascript 318 | @apiHandler(types.FETCH_ALL) 319 | handleFetchAll: (state, {payload}) => {...state, ...payload} 320 | ``` 321 | 322 | The decorated function is considered the _success_ function handler and will be called upon a success status code returned from the request. 323 | 324 | To handle custom loading states, we can "hook" into them with a second argument. The second argument is a function that's called with the dynamic states provided by the argument it's called with. For instance, to handle custom handling of an error state: 325 | 326 | ```javascript 327 | @apiHandler(types.FETCH_ALL, (apiTypes) => ({ 328 | [apiTypes.ERROR]: (state, {payload}) => ({ 329 | ...state, 330 | error: payload.body.message, 331 | loading: false 332 | }) 333 | })) 334 | handleFetchAll: (state, {payload}) => {...state, ...payload} 335 | ``` 336 | 337 | ## Usage with react-redux 338 | 339 | There are multiple methods for combining `redux-modules` with react and this is our opinion about how to use the two together. 340 | 341 | First, our directory structure generally sets all of our modules in their own directory: 342 | 343 | ```bash 344 | index.js 345 | /redux 346 | /modules/ 347 | todo.js 348 | users.js 349 | configureStore.js 350 | rootReducer.js 351 | index.js 352 | ``` 353 | 354 | Configuring the store for our app is straight-forward. First, we'll apply the `createApiMiddleware()` before we create the final store. In a `configureStore.js` file, we like to handle creating a store in a single spot. We'll export a function to configure the store: 355 | 356 | ```javascript 357 | import {rootReducer, actions} from './rootReducer' 358 | 359 | export const configureStore = ({initialState = {}}) => { 360 | let middleware = [ 361 | createApiMiddleware({ 362 | baseUrl: BASE_URL 363 | }), 364 | thunkMiddleware 365 | ] 366 | // ... 367 | const finalCreateStore = 368 | compose(applyMiddleware(...middleware))(createStore); 369 | 370 | const store = finalCreateStore(rootReducer, initialState); 371 | // ... 372 | } 373 | ``` 374 | 375 | This creates the middleware for us. Next, we like to combine our actions into a single actions object that we'll pass along down through our components. We'll use the `bindActionCreatorsToStore()` export to build our action creators and bind them to the store. 376 | 377 | We'll need to bind our actions to the store, so that when we call dispatch it will use our store's dispatch (see [react-redux](https://github.com/reactjs/react-redux)). Just after we create the store, we'll: 378 | 379 | ```javascript 380 | let actions = bindActionCreatorsToStore(actions, store); 381 | ``` 382 | 383 | From here, we just return the store and actions from the function: 384 | 385 | ```javascript 386 | export const configureStore = ({initialState = {}}) => { 387 | // ... 388 | const store = finalCreateStore(rootReducer, initialState); 389 | // ... 390 | let actions = bindActionCreatorsToStore(actions, store); 391 | 392 | return {store, actions}; 393 | } 394 | ``` 395 | 396 | Now that the heavy-lifting is done, the `rootReducer.js` file is pretty simple. We export all the actions and reducers pretty simply: 397 | 398 | ```javascript 399 | const containers = ['users', 'todos']; 400 | 401 | export const reducers = {} 402 | export const actions = {}; 403 | 404 | containers.forEach(k => { 405 | let val = require(`./modules/${v}`); 406 | reducers[k] = val.reducer; 407 | actions[k] = val.actions || {}; 408 | }); 409 | 410 | export const rootReducer = combineReducers(reducers); 411 | ``` 412 | 413 | From here, our main container can pass the store and actions as props to our components: 414 | 415 | ```javascript 416 | const {store, actions} = configureStore({initialState}); 417 | // ... 418 | ReactDOM.render( 419 | , 420 | node); 421 | ``` 422 | 423 | Now, anywhere in our code, we can refer to the actions we export in our modules by their namespace. For instance, to call the `createTodo()` function, we can reference it by the prop namespace: 424 | 425 | ```javascript 426 | class Container extends React.Component { 427 | 428 | createTodo() { 429 | const {actions} = this.props; 430 | // form: actions.[namespace].[actionName](); 431 | actions.todos.createTodo("Finish this text"); 432 | } 433 | 434 | render() { 435 | return ( 436 |
437 | Create todo 438 |
439 | ) 440 | } 441 | } 442 | ``` 443 | 444 | ## Combining usage with `ducks-modular-redux` 445 | 446 | `redux-modules` plays nicely with other redux packages as well. For instance, the `ducks-modular-redux` package defines a specific method of handling actions, reducers, and types. 447 | 448 | To create types in the same way, we can use the `separator` and `prefix` options in `createConstants()`. For instance, to create the constants defined by `ducks-modular-redux`'s README': 449 | 450 | ```javascript 451 | const LOAD = 'my-app/widgets/LOAD'; 452 | const CREATE = 'my-app/widgets/CREATE'; 453 | const UPDATE = 'my-app/widgets/UPDATE'; 454 | const REMOVE = 'my-app/widgets/REMOVE'; 455 | // In redux-modules: 456 | const types = createConstants({ 457 | prefix: ['my-app', 'widgets'], 458 | separator: '/' 459 | })('LOAD', 'CREATE', 'UPDATE', 'REMOVE') 460 | ``` 461 | 462 | Handling the reducer function is similarly easy as well: 463 | 464 | ```javascript 465 | export default function reducer(state = {}, action = {}) { 466 | switch (action.type) { 467 | // do reducer stuff 468 | default: return state; 469 | } 470 | } 471 | const reducer = createReducer({ 472 | [types.LOAD]: (state, {payload}) => ({ 473 | ...state, 474 | todos: state.todos.concat(payload) 475 | }), 476 | // ... 477 | }); 478 | ``` 479 | 480 | Finally, exporting functions individually from the file is directly supported. The `createActions()` and `createApiAction()` helpers can be used directly on created functions. 481 | 482 | ## All exports 483 | 484 | The `redux-modules` comprises the following exports: 485 | 486 | ### createConstants 487 | 488 | `createConstants()` creates an object to handle creating an object of type constants. It allows for multiple types to be dynamically created with their own custom prefixing, created on a single object. 489 | 490 | ```javascript 491 | const types = createConstants({})('DOG', 'CAT'); 492 | ``` 493 | 494 | Options: 495 | 496 | * prefix (string/array, default: '') 497 | 498 | The `prefix` option creates each type with a predefined prefix. 499 | 500 | ```javascript 501 | const types = createConstants({ 502 | prefix: 'animals' 503 | })('DOG', 'CAT') 504 | expect(types.DOG).to.eql('ANIMALS_DOG'); 505 | expect(types.CAT).to.eql('ANIMALS_CAT'); 506 | 507 | const types = createConstants({ 508 | prefix: ['test', 'animals'] 509 | })('DOG', 'CAT') 510 | expect(types.DOG).to.eql('TEST_ANIMALS_DOG'); 511 | expect(types.CAT).to.eql('TEST_ANIMALS_CAT'); 512 | ``` 513 | 514 | * separator (string, default: `_`) 515 | 516 | The separator option allows us to change the way prefixes are concatenated. To change the separator to use a `/`, add the separator option: 517 | 518 | ```javascript 519 | const types = createConstants({ 520 | separator: '/', 521 | prefix: ['test', 'animals'] 522 | })('DOG', 'CAT') 523 | expect(types.DOG).to.eql('TEST/ANIMALS/DOG'); 524 | expect(types.CAT).to.eql('TEST/ANIMALS/CAT'); 525 | ``` 526 | 527 | * initialObject (object, default: `{}`) 528 | 529 | For the case where you want to define types on an existing object, `createConstants()` accepts an `initialObject` to add the types. This allows us to create a single global object (for instance) to define all of our types. 530 | 531 | ```javascript 532 | const types = createConstants({ 533 | initialObject: types 534 | })('OTHER', 'CONSTANTS'); 535 | ``` 536 | 537 | ### createReducer 538 | 539 | The `createReducer()` function returns a function that acts similar to the switch-case functionality of redux where we'll define the types and the reducers that handle the types. 540 | 541 | ```javascript 542 | const reducer = createReducer({ 543 | [types.CREATE]: (state, {payload}) => ({ 544 | ...state, 545 | todos: state.todos.concat(payload) 546 | }) 547 | }); 548 | ``` 549 | 550 | ### bindActionCreatorsToStore 551 | 552 | The `bindActionCreatorsToStore()` function accepts two arguments, the action handler object and the store object. It takes each action, binds the function to the `store` object (so `this` refers to the `store`) and then calls the `bindActionCreators()` redux function to the store object. Use the returned value as the reducer object. 553 | 554 | ```javascript 555 | let actions = bindActionCreatorsToStore(actions, store); 556 | ``` 557 | 558 | ### createApiMiddleware 559 | 560 | In order to set global options for every api request, we have to include a middleware in our stack. Creating the middleware for our redux stack uses `createApiMiddleware()` and essentially looks for any api action (with `meta.isApi` set to true) and merges global options into the `meta` key of the action. 561 | 562 | We _must_ set the `baseUrl` in the middleware, which is used as the default url to make a request against. Without the `baseUrl`, all requests will be sent without an http component (unless set otherwise in the `apiClient`): 563 | 564 | ```javascript 565 | let apiMiddleware = createApiMiddleware({ 566 | baseUrl: `https://fullstackreact.com`, 567 | headers: { 568 | 'Accept': 'application/json' 569 | } 570 | }); 571 | ``` 572 | 573 | ### apiClient 574 | 575 | The `apiClient` is a loose wrapper around the native html5 `fetch()` function (built around `isomorphic-fetch`, which makes testing easier). When an action is marked as an API action, it will be called with an instance of the `apiClient` as well as the options `fetch()` will be called with. This gives us an easy, flexible way to make API requests. 576 | 577 | The `apiClient` instance creates methods for each HTTP method, which accepts custom parameters to make the requests. It handles building the request, the options, putting together the url, packaging the body, request and response transformations, and more. 578 | 579 | Using the `apiClient` instance inside of an api action request looks like: 580 | 581 | ```javascript 582 | @api(types.FETCH_ALL) 583 | fetchAll: (client, opts) => client.get({path: '/todos'}) 584 | // or non-decorator version 585 | let decoratedFetchall = createApiAction(types.FETCH_ALL)(function(client, opts) { 586 | return client.get({path: '/todos'}) 587 | }); 588 | ``` 589 | 590 | By default, the request is assumed to be in json format, but this is flexible and can be manipulated on a global/per-request level. 591 | 592 | Every option that the `apiMiddleware` and `apiClient.[method]` accepts can be either an atomic value or it can be a function. If a function is passed, it will be called at runtime with the current options and state to allow for dynamic responses based upon the state. 593 | 594 | The available options for _both_ apiMiddleware and client method requests are [here](#api-client-options). 595 | 596 | ### createApiAction/@api 597 | 598 | To create an api action creator, we can decorate it with the `@api` decorator (when defined inline in an object) or using the `createApiAction()` function. Using this decorator, the function itself will be used to fetch an api. 599 | 600 | The decorated function is expected to use the `client`, although it is not required. It is expected that the decorated function returns a value, either a promise or an atomic value. 601 | 602 | ```javascript 603 | { 604 | actions: { 605 | @api(types.FETCH_ALL) 606 | fetchAll: (client, opts) => client.get({path: '/todos'}) 607 | } 608 | } 609 | // OR non-decorator version 610 | const fetchAll = createApiAction(types.FETCH_ALL)( 611 | (client, opts) => client.get('/todos')); 612 | ``` 613 | 614 | Using the decorator will dispatch actions according to their response status, first dispatching the `loading` type (i.e. `{type: 'API_FETCH_ALL_LOADING', opts}`), then it calls the handler. Once the handler returns, the corresponding action `_SUCCESS` or `_ERROR` action types are dispatched. 615 | 616 | ### createApiHandler/@apiHandler 617 | 618 | In order to handle the response from an api request, we need to create a reducer. The `api` decorator fires the status values for the state of the api request. Using the `createApiHandler()/@apiHandler` decorator sets up default handlers for dealing with these responses. 619 | 620 | ```javascript 621 | { 622 | reducers: { 623 | @apiHandler(types.FETCH_ALL) 624 | handleFetchAll: (state, action) => ({...state, ...action.payload}); 625 | } 626 | } 627 | // or non-decorator version 628 | const handlers = createApiHandler(types.FETCH_ALL) => {})((state, action) => { 629 | return { 630 | ...state, 631 | ...action.payload 632 | } 633 | }); 634 | ``` 635 | 636 | The default actions will set the `loading` flag to true when the `_LOADING` action type is called, while the `loading` flag (in the state) will be set to false for the `_ERROR` and `_SUCCESS` types. 637 | 638 | For the case where we want to handle the states in a custom way, we can pass a second argument as a function which is called with the api states object where we can set custom handlers. For instance, to handle loading and errors in our previous example: 639 | 640 | ```javascript 641 | { 642 | reducers: { 643 | @apiHandler(types.FETCH_ALL, (apiStates) => { 644 | [apiStates.loading]: (state, action) => ({...state, loading: true}), 645 | [apiStates.error]: (state, action) => { 646 | return ({ 647 | ...state, 648 | error: action.payload 649 | }) 650 | } 651 | }) 652 | handleFetchAll: (state, action) => ({...state, ...action.payload}); 653 | } 654 | } 655 | ``` 656 | 657 | The decorated function is considered the success handler. 658 | 659 | ## TODOS: 660 | 661 | * [x] Use the custom type creator in `createConstants()` for defining apis 662 | * [] Add docs for `createRootReducer()` 663 | 664 | ## Contributing 665 | 666 | ```shell 667 | git clone https://github.com/fullstackreact/redux-modules.git 668 | cd redux-modules 669 | npm install 670 | make dev 671 | ``` 672 | 673 | To run the tests (please ensure the tests pass when creating a pull request): 674 | 675 | ```shell 676 | make test # or npm run test 677 | ``` 678 | 679 | ___ 680 | 681 | # Fullstack React Book 682 | 683 | 684 | Fullstack React Book 685 | 686 | 687 | This repo was written and is maintained by the [Fullstack React](https://fullstackreact.com) team. In the book we cover many more projects like this. We walk through each line of code, explain why it's there and how it works. 688 | 689 | This app is only one of several apps we have in the book. If you're looking to learn React, there's no faster way than by spending a few hours with the Fullstack React book. 690 | 691 |
692 | 693 | ## License 694 | [MIT](/LICENSE) 695 | -------------------------------------------------------------------------------- /api.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./dist/api'); 2 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./dist/index'); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "redux-module-builder", 3 | "version": "0.3.2", 4 | "description": "Redux modules", 5 | "author": "Fullstack.io ", 6 | "license": "MIT", 7 | "options": { 8 | "mocha": "--require scripts/mocha_runner -t rewireify src/**/__tests__/**/*.js" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/fullstackreact/redux-modules.git" 13 | }, 14 | "main": "dist/index.js", 15 | "scripts": { 16 | "prepublish": ". ./scripts/prepublish.sh", 17 | "dev": "NODE_ENV=development ./node_modules/hjs-webpack/bin/hjs-dev-server.js", 18 | "build": "NODE_ENV=production webpack", 19 | "publish_pages": "gh-pages -d public/", 20 | "lint": "eslint ./src", 21 | "lintfix": "eslint ./src --fix", 22 | "testonly": "NODE_ENV=test mocha $npm_package_options_mocha", 23 | "test": "npm run lint && npm run testonly", 24 | "test:watch": "npm run testonly -- --watch --watch-extensions js" 25 | }, 26 | "devDependencies": { 27 | "autoprefixer": "^6.3.7", 28 | "babel-cli": "^6.11.4", 29 | "babel-core": "^6.11.4", 30 | "babel-eslint": "^6.1.2", 31 | "babel-loader": "^6.2.4", 32 | "babel-plugin-transform-es2015-modules-umd": "^6.8.0", 33 | "babel-polyfill": "^6.9.1", 34 | "babel-preset-es2015": "^6.9.0", 35 | "babel-preset-react": "^6.11.1", 36 | "babel-preset-react-hmre": "^1.1.1", 37 | "babel-preset-stage-0": "^6.5.0", 38 | "babel-preset-stage-2": "^6.11.0", 39 | "babel-runtime": "^6.9.2", 40 | "chai": "^3.5.0", 41 | "chai-spies": "^0.7.1", 42 | "css-loader": "^0.23.1", 43 | "cssnano": "^3.7.3", 44 | "dotenv": "^2.0.0", 45 | "enzyme": "^2.4.1", 46 | "eslint": "^3.1.1", 47 | "eslint-plugin-babel": "^3.3.0", 48 | "eslint-plugin-react": "^5.2.2", 49 | "fetch-mock": "^5.0.3", 50 | "file-loader": "^0.9.0", 51 | "gh-pages": "^0.11.0", 52 | "highlight.js": "^9.5.0", 53 | "hjs-webpack": "^8.3.0", 54 | "html-loader": "^0.4.3", 55 | "install": "^0.8.1", 56 | "invariant": "^2.2.1", 57 | "jsdom": "^9.4.1", 58 | "markdown-loader": "^0.1.7", 59 | "markdown-with-front-matter-loader": "^0.1.0", 60 | "marked": "^0.3.5", 61 | "mocha": "^2.5.3", 62 | "mockery": "^1.7.0", 63 | "nodemon": "^1.9.2", 64 | "npm": "^3.10.5", 65 | "npm-font-open-sans": "0.0.3", 66 | "postcss-loader": "^0.9.1", 67 | "precss": "^1.4.0", 68 | "raw-loader": "^0.5.1", 69 | "react": "^15.2.1", 70 | "react-addons-test-utils": "^15.2.1", 71 | "react-dom": "^15.2.1", 72 | "react-github-fork-ribbon": "^0.4.4", 73 | "react-router": "^2.6.0", 74 | "redux-mock-store": "^1.1.2", 75 | "redux-thunk": "^2.1.0", 76 | "sinon": "^1.17.4", 77 | "sinon-chai": "^2.8.0", 78 | "style-loader": "^0.13.1", 79 | "url-loader": "^0.5.7", 80 | "webpack": "^1.13.1" 81 | }, 82 | "peerDependencies": { 83 | "react": "~0.14.8 || ^15.0.0" 84 | }, 85 | "dependencies": { 86 | "invariant": "^2.2.1", 87 | "query-string": "^4.2.2", 88 | "react-github-fork-ribbon": "^0.4.4", 89 | "react-inspector": "^1.1.0", 90 | "redux": "^3.5.2", 91 | "redux-actions": "^0.10.1", 92 | "whatwg-fetch": "^1.0.0" 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /scripts/mocha_runner.js: -------------------------------------------------------------------------------- 1 | require('babel-core/register'); 2 | require('babel-polyfill'); 3 | 4 | var jsdom = require('jsdom').jsdom; 5 | var chai = require('chai'), 6 | spies = require('chai-spies'); 7 | var sinon = require('sinon'); 8 | 9 | var exposedProperties = ['window', 'navigator', 'document']; 10 | 11 | global.document = jsdom(''); 12 | global.window = document.defaultView; 13 | Object.keys(document.defaultView).forEach((property) => { 14 | if (typeof global[property] === 'undefined') { 15 | exposedProperties.push(property); 16 | global[property] = document.defaultView[property]; 17 | } 18 | }); 19 | 20 | global.navigator = { 21 | userAgent: 'node.js' 22 | }; 23 | 24 | chai.use(spies); 25 | 26 | const google = { 27 | maps: { 28 | LatLng: function(lat, lng) { 29 | return { 30 | latitude: parseFloat(lat), 31 | longitude: parseFloat(lng), 32 | 33 | lat: function() { 34 | return this.latitude; 35 | }, 36 | lng: function() { 37 | return this.longitude; 38 | } 39 | }; 40 | }, 41 | LatLngBounds: function(ne, sw) { 42 | return { 43 | getSouthWest: function() { 44 | return sw; 45 | }, 46 | getNorthEast: function() { 47 | return ne; 48 | } 49 | }; 50 | }, 51 | OverlayView: function() { 52 | return {}; 53 | }, 54 | InfoWindow: function() { 55 | return {}; 56 | }, 57 | Marker: function() { 58 | return { 59 | addListener: function() {} 60 | }; 61 | }, 62 | MarkerImage: function() { 63 | return {}; 64 | }, 65 | Map: function() { 66 | return { 67 | addListener: function() {}, 68 | trigger: function() {} 69 | }; 70 | }, 71 | Point: function() { 72 | return {}; 73 | }, 74 | Size: function() { 75 | return {}; 76 | }, 77 | event: { 78 | trigger: function() {} 79 | } 80 | } 81 | }; 82 | 83 | global.google = google; 84 | 85 | documentRef = document; 86 | -------------------------------------------------------------------------------- /scripts/prepublish.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "=> Transpiling..." 4 | echo "" 5 | export NODE_ENV=production 6 | rm -rf ./dist 7 | ./node_modules/.bin/babel \ 8 | --plugins 'transform-es2015-modules-umd' \ 9 | --presets 'stage-0,react' \ 10 | --ignore __tests__ \ 11 | --out-dir ./dist \ 12 | src 13 | echo "" 14 | echo "=> Complete" 15 | -------------------------------------------------------------------------------- /src/__tests__/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | expect 4 | } from 'chai'; 5 | import sinon from 'sinon'; 6 | 7 | import {createConstants} from '../' 8 | 9 | describe('index', () => { 10 | it('exports a createConstants() function', () => { 11 | expect(core.createConstants).to.be.defined; 12 | }) 13 | }) 14 | -------------------------------------------------------------------------------- /src/__tests__/lib/apiClient.spec.js: -------------------------------------------------------------------------------- 1 | import sinon from 'sinon'; 2 | import {expect} from 'chai'; 3 | import ApiClient from '../../lib/apiClient'; 4 | import configureMockStore from 'redux-mock-store'; 5 | import {makeStore} from '../spec_helpers'; 6 | import fetchMock from 'fetch-mock'; 7 | 8 | const BASE_URL = 'http://fullstackreact.com'; 9 | 10 | const baseOpts = { 11 | _debug: false, 12 | baseUrl: BASE_URL, 13 | appendExt: false, // optional 14 | headers: { 15 | 'X-Requested-With': 'spec' 16 | } 17 | } 18 | 19 | describe('ApiClient', () => { 20 | let client, state; 21 | let helpers; 22 | 23 | beforeEach(() => { 24 | fetchMock 25 | .mock(`${BASE_URL}/foo`, { 26 | status: 200, 27 | body: {msg: 'world'} 28 | }) 29 | }); 30 | 31 | afterEach(() => fetchMock.restore()); 32 | 33 | beforeEach(() => { 34 | state = {}; 35 | client = new ApiClient(baseOpts, () => state); 36 | }); 37 | 38 | describe('option parsing', () => { 39 | const makeOptionParsingTest = (key, val) => { 40 | // common tests for each option 41 | it(`accepts ${key} in defaultOpts as a value`, () => { 42 | let res = client._parseOpt(key, {}, { [key]: val }); 43 | expect(res).to.eql(val) 44 | }); 45 | it(`accepts ${key} in instance options as a value`, () => { 46 | let res = client._parseOpt(key, { [key]: val }); 47 | expect(res).to.eql(val) 48 | }); 49 | it(`accepts ${key} as a function`, () => { 50 | let res = client._parseOpt(key, { [key]: () => val }); 51 | expect(res).to.eql(val) 52 | }); 53 | it(`accepts ${key} as false (nullify)`, () => { 54 | let res = client._parseOpt(key, { [key]: false }); 55 | expect(res).to.be.null; 56 | }); 57 | } 58 | 59 | // Test for appendPath 60 | makeOptionParsingTest('appendPath', `/${Math.random(0, 20)}`) 61 | makeOptionParsingTest('appendExt', 'json') 62 | 63 | }) 64 | 65 | describe('get', () => { 66 | it('defines GET as a function', () => { 67 | expect(typeof client.get).to.eql('function'); 68 | }) 69 | 70 | it('runs a request', (done) => { 71 | client.get({url: `${BASE_URL}/foo`}) 72 | .then((resp) => { 73 | expect(resp.msg).to.eql('world') 74 | done(); 75 | }).catch(done); 76 | }); 77 | 78 | it('accepts a string as a path', done => { 79 | client.get('/foo') 80 | .then((resp) => { 81 | expect(resp.msg).to.eql('world'); 82 | done(); 83 | }).catch(done); 84 | }) 85 | 86 | it('accepts a path (appended to the baseUrl)', done => { 87 | client.get({path: '/foo'}) 88 | .then((resp) => { 89 | expect(resp.msg).to.eql('world'); 90 | done(); 91 | }).catch(done); 92 | }); 93 | 94 | it('accepts appendPath', done => { 95 | fetchMock.mock(`${BASE_URL}/foo/yellow`, '{}') 96 | client.get({path: '/foo', appendPath: '/yellow'}) 97 | .then(() => done()).catch(done); 98 | }); 99 | }); 100 | 101 | describe('post', () => { 102 | it('defines POST as a function', () => { 103 | expect(typeof client.post).to.eql('function'); 104 | }); 105 | 106 | it('sends `data` along with the request', (done) => { 107 | fetchMock.post(`${BASE_URL}/foo`, { 108 | msg: 'world' 109 | }) 110 | client.post({ 111 | path: '/foo', 112 | data: {msg: 'hello'} 113 | }).then((data) => { 114 | expect(data).to.eql({msg: 'world'}) 115 | done(); 116 | }).catch(done); 117 | }) 118 | }) 119 | 120 | describe('error handling', () => { 121 | let client; 122 | const generateError = (status, msg={}, options={}) => { 123 | return fetchMock.mock(`${BASE_URL}/err`, (reqUrl, reqOpts) => { 124 | return { 125 | status, 126 | body: JSON.stringify(msg) 127 | } 128 | }) 129 | } 130 | 131 | beforeEach(() => { 132 | client = new ApiClient(baseOpts, () => state); 133 | }); 134 | 135 | it('responds with the status code', (done) => { 136 | let p = generateError(500, {msg: 'blah'}); 137 | client.get({path: '/err'}) 138 | .catch((err) => { 139 | expect(err.status).to.equal(500); 140 | done(); 141 | }) 142 | }); 143 | 144 | it('responds with the error messsage', (done) => { 145 | generateError(400, {msg: 'error error'}); 146 | client.get({path: '/err'}) 147 | .catch((err) => { 148 | err.body.then((json) => { 149 | expect(json.msg).to.eql('error error') 150 | done(); 151 | }) 152 | }) 153 | }) 154 | }) 155 | 156 | describe('request transforms', () => { 157 | let transform = (state, opts) => req => { 158 | req.headers['X-Name'] = 'Ari'; 159 | return req; 160 | } 161 | beforeEach(() => { 162 | fetchMock.mock(`${BASE_URL}/name`, (reqUrl, reqOpts) => { 163 | return { 164 | status: 200, 165 | body: JSON.stringify(reqOpts) 166 | } 167 | }); 168 | client = new ApiClient(baseOpts, () => state); 169 | }); 170 | 171 | it('can accept a single requestTransform', () => { 172 | baseOpts.requestTransforms = [transform]; 173 | client = new ApiClient(baseOpts, () => state); 174 | client.get({path: '/name'}) 175 | .then((json) => { 176 | expect(res.headers['X-Name']).to.eql('Ari') 177 | }); 178 | }); 179 | 180 | it('accepts multiple requestTransforms', () => { 181 | client = new ApiClient(baseOpts, () => state); 182 | client.get({path: '/name', requestTransforms: [transform]}) 183 | }); 184 | }); 185 | 186 | describe('response transforms', () => { 187 | let time, msg; 188 | let transform = (state, opts) => res => { 189 | res.headers.set('X-Response-Time', time); 190 | return res; 191 | } 192 | let jsonTransform = (state, opts) => (res) => { 193 | let time = res.headers.get('X-Response-Time'); 194 | return res.json() 195 | .then(json => ({...json, time})) 196 | } 197 | beforeEach(() => { 198 | time = new Date() 199 | msg = 'hello world'; 200 | fetchMock.mock(`${BASE_URL}/response/time`, { 201 | status: 200, 202 | body: JSON.stringify({time, msg}) 203 | }); 204 | client = new ApiClient(baseOpts, () => state); 205 | }); 206 | 207 | it('returns parsed JSON by default without responseTransforms', (done) => { 208 | client = new ApiClient(baseOpts, () => state) 209 | .get({path: '/response/time'}) 210 | .then(json => { 211 | expect(json.msg).to.eql(msg); 212 | done(); 213 | }).catch(done) 214 | }); 215 | 216 | it('can accept a single responseTransforms', (done) => { 217 | baseOpts.responseTransforms = [transform]; 218 | client = new ApiClient(baseOpts, () => state); 219 | client.get({path: '/response/time'}) 220 | .then((res) => { 221 | expect(res.headers.get('X-Response-Time')).to.eql(time) 222 | done(); 223 | }).catch(done) 224 | }); 225 | 226 | it('accepts multiple responseTransforms', (done) => { 227 | client = new ApiClient(baseOpts, () => state); 228 | client.get({path: '/response/time', 229 | responseTransforms: [transform, jsonTransform]}) 230 | .then((json) => { 231 | expect(json.time).to.eql(time); 232 | done(); 233 | }).catch(done) 234 | }); 235 | }); 236 | 237 | }) 238 | -------------------------------------------------------------------------------- /src/__tests__/lib/constants.spec.js: -------------------------------------------------------------------------------- 1 | import { 2 | expect 3 | } from 'chai'; 4 | import { 5 | createConstants, 6 | apiKeys, 7 | apiValues 8 | } from '../../lib/constants'; 9 | 10 | describe('createConstants', () => { 11 | let obj, typeFn; 12 | beforeEach(() => { 13 | obj = {}; 14 | typeFn = createConstants({}); 15 | }); 16 | 17 | const prefixTests = (types, expected) => { 18 | it('creates a constant on the given object', () => { 19 | expect(types.HARRY).to.exist; 20 | }); 21 | 22 | Object.keys(expected).forEach(key => { 23 | it(`creates a ${key} constant to equal ${expected[key]}`, () => { 24 | expect(types[key]).to.eql(expected[key]) 25 | }) 26 | }) 27 | return types; 28 | } 29 | 30 | describe('with prefix', () => { 31 | prefixTests(createConstants({ 32 | prefix: 'person' 33 | })('HARRY'), { 34 | 'HARRY': 'PERSON_HARRY' 35 | }) 36 | }) 37 | 38 | describe('with a string opts', () => { 39 | const types = createConstants('some_prefix')('CREATE'); 40 | expect(types.CREATE).to.eql('SOME_PREFIX_CREATE'); 41 | }); 42 | 43 | 44 | describe('without prefix', () => { 45 | prefixTests(createConstants({})('HARRY'), { 46 | 'HARRY': '_HARRY' 47 | }) 48 | }) 49 | 50 | describe('with initialObject', () => { 51 | const types = prefixTests(createConstants({ 52 | initialObject: { 53 | 'bob': 1 54 | } 55 | })('HARRY'), { 56 | 'HARRY': '_HARRY', 57 | 'bob': 1 58 | }); 59 | 60 | it('does not overwrite the initial value', () => { 61 | expect(Object.keys(types)).to.include('HARRY') 62 | }); 63 | }); 64 | 65 | describe('objects', () => { 66 | let types; 67 | beforeEach(() => { 68 | types = createConstants({})({ 69 | 'HISTORY': true, 70 | 'PERSON': { 71 | api: true 72 | }, 73 | 'DOG': { 74 | api: true, 75 | states: ['sit', 'stay'] 76 | } 77 | }) 78 | }) 79 | it('accepts an object definition', () => { 80 | expect(types.HISTORY).to.exist; 81 | }); 82 | it('creates api events for each type', () => { 83 | expect(types.PERSON).to.exist; 84 | expect(types.PERSON_LOADING).to.exist; 85 | expect(types.PERSON_SUCCESS).to.exist; 86 | expect(types.PERSON_ERROR).to.exist; 87 | }); 88 | it('creates api type postfixes', () => { 89 | expect(types.PERSON).to.eql('_PERSON'); 90 | expect(types.PERSON_LOADING).to.eql('API__PERSON_LOADING'); 91 | expect(types.PERSON_SUCCESS).to.eql('API__PERSON_SUCCESS'); 92 | expect(types.PERSON_ERROR).to.eql('API__PERSON_ERROR'); 93 | }); 94 | it('accepts custom states', () => { 95 | expect(types.DOG).to.eql('_DOG'); 96 | expect(types.DOG_SIT).to.eql('API__DOG_SIT') 97 | expect(types.DOG_STAY).to.eql('API__DOG_STAY'); 98 | expect(types.DOG_LOADING).not.to.exist; 99 | }) 100 | }) 101 | 102 | describe('separator', () => { 103 | it('can accept a string separator', () => { 104 | let types = createConstants({ 105 | separator: '/' 106 | })('DOG', 'CAT'); 107 | expect(Object.keys(types).length).to.equal(2); 108 | expect(types.DOG).to.eql('/DOG') 109 | expect(types.CAT).to.eql('/CAT'); 110 | }); 111 | 112 | it('accepts a string prefix', () => { 113 | const types = createConstants({ 114 | separator: '/', 115 | prefix: 'animals' 116 | })('DOG', 'CAT') 117 | expect(types.DOG).to.eql('ANIMALS/DOG'); 118 | expect(types.CAT).to.eql('ANIMALS/CAT'); 119 | }) 120 | 121 | it('accepts an array prefix', () => { 122 | const types = createConstants({ 123 | separator: '/', 124 | prefix: ['test', 'animals'] 125 | })('DOG', 'CAT') 126 | expect(Object.keys(types).length).to.equal(2); 127 | expect(types.DOG).to.eql('TEST/ANIMALS/DOG'); 128 | expect(types.CAT).to.eql('TEST/ANIMALS/CAT'); 129 | }) 130 | }) 131 | 132 | describe('custom types', () => { 133 | let typeCreator; 134 | beforeEach(() => { 135 | typeCreator = createConstants({ 136 | prefix: 'animals', 137 | customTypes: { 138 | 'myApi': ['loading', 'error', 'success'], 139 | 'sockets': ['connected', 'disconnected'] 140 | } 141 | }) 142 | }) 143 | 144 | it('creates a constant with each of the different states of the constant', () => { 145 | let types = typeCreator({'DOG': {types: 'sockets'}}, {'CAT': { types: 'myApi' }}, 'BIRD') 146 | // types should have types: 147 | // types.DOG_CONNECTED: 'ANIMALS_SOCKETS_DOG_CONNECTED', 148 | // types.DOG_DISCONNECTED: 'ANIMALS_SOCKETS_DOG_DISCONNECTED' 149 | expect(types.DOG_CONNECTED).to.be.defined; 150 | expect(types.DOG_CONNECTED).to.eql('ANIMALS_SOCKETS_DOG_CONNECTED') 151 | expect(types.DOG_DISCONNECTED).to.be.defined; 152 | expect(types.DOG_DISCONNECTED).to.eql('ANIMALS_SOCKETS_DOG_DISCONNECTED') 153 | 154 | expect(types.CAT_LOADING).to.be.defined; 155 | expect(types.CAT_LOADING).to.eql('ANIMALS_MYAPI_CAT_LOADING'); 156 | }); 157 | 158 | it('associates api types with api', () => { 159 | let types = typeCreator('BIRD', {'CAT': {api: true}}) 160 | expect(types.CAT_LOADING).to.be.defined; 161 | expect(types.CAT_LOADING).to.eql('API_ANIMALS_CAT_LOADING'); 162 | expect(types.CAT_SUCCESS).to.eql('API_ANIMALS_CAT_SUCCESS'); 163 | }) 164 | 165 | }) 166 | }) 167 | 168 | describe('apiValues', () => { 169 | it('passes api values', () => { 170 | let vals = apiValues('BALL') 171 | expect(vals.BALL_LOADING).to.eql('API_BALL_LOADING') 172 | }); 173 | it('passes api values with custom states', () => { 174 | let vals = apiValues('DOG', ['sit']) 175 | expect(vals.DOG_SIT).to.eql('API_DOG_SIT') 176 | }) 177 | }) 178 | -------------------------------------------------------------------------------- /src/__tests__/lib/createApiActions.spec.js: -------------------------------------------------------------------------------- 1 | import sinon from 'sinon'; 2 | import {expect} from 'chai'; 3 | import ApiClient from '../../lib/apiClient'; 4 | import {createApiAction, API_CONSTANTS} from '../../lib/createApiActions'; 5 | import {REDUX_MODULE_API_ACTION_KEY} from '../../lib/constants'; 6 | import configureMockStore from 'redux-mock-store'; 7 | import {generateResponse, makeBaseOpts, BASE_URL, makeStore, doDispatch, doGetState} from '../spec_helpers'; 8 | import fetchMock from 'fetch-mock'; 9 | 10 | const createStubStore = () => { 11 | let res = makeStore({ 12 | baseUrl: BASE_URL, 13 | }, {numbers: []}) 14 | let store = res.store; 15 | return {res, store}; 16 | } 17 | describe('@api decorator', () => { 18 | let fn, decorated, baseOpts, store; 19 | beforeEach(() => baseOpts = makeBaseOpts({})); 20 | beforeEach(() => { 21 | let stub = createStubStore(); 22 | store = stub.store; 23 | fn = (client) => client.get('/go') 24 | }); 25 | beforeEach(() => decorated = createApiAction('YES')(fn)(baseOpts)) 26 | afterEach(() => fetchMock.restore()); 27 | 28 | it('calls two actions (LOADING, SUCCESS)', (done) => { 29 | generateResponse('/go', 200); 30 | let {type, meta} = decorated(store.dispatch, store.getState); 31 | const {runFn} = meta; 32 | expect(type).to.eql(REDUX_MODULE_API_ACTION_KEY); 33 | expect(typeof runFn).to.eql('function') 34 | 35 | runFn(baseOpts) 36 | .then((json) => { 37 | let actions = store.getActions(); 38 | expect(actions.length).to.equal(2); 39 | expect(actions[0].type).to.eql('API_YES_LOADING'); 40 | expect(actions[1].type).to.eql('API_YES_SUCCESS'); 41 | done(); 42 | }) 43 | .catch((err) => { 44 | console.log('An error occurred', err); 45 | done(err); 46 | }) 47 | }); 48 | 49 | it('calls the error action when error is received', (done) => { 50 | generateResponse('/go', 500); 51 | let {type, meta} = decorated(store.dispatch, store.getState); 52 | const {runFn} = meta; 53 | 54 | runFn(baseOpts) 55 | .then((json) => { 56 | let actions = store.getActions(); 57 | 58 | expect(actions.length).to.equal(2); 59 | expect(actions[0].type).to.eql('API_YES_LOADING'); 60 | expect(actions[1].type).to.eql('API_YES_ERROR'); 61 | 62 | done(); 63 | }).catch(done) 64 | }); 65 | 66 | describe('meta creator', () => { 67 | it('appends isApi to the meta object of loading/success', (done) => { 68 | generateResponse('/go', 200) 69 | let {type, meta} = decorated(store.dispatch, store.getState); 70 | const {runFn} = meta; 71 | 72 | runFn(baseOpts) 73 | .then((json) => { 74 | let actions = store.getActions(); 75 | 76 | expect(actions.length).to.equal(2); 77 | expect(actions[0].meta.isApi).to.be.true; 78 | expect(actions[1].meta.isApi).to.be.true; 79 | 80 | done(); 81 | }).catch(done) 82 | }); 83 | 84 | it('appends the errorStatus to the payload object of error', (done) => { 85 | generateResponse('/go', 418) 86 | 87 | let {type, meta} = decorated(store.dispatch, store.getState); 88 | const {runFn} = meta; 89 | 90 | runFn(baseOpts) 91 | .then((json) => { 92 | let actions = store.getActions(); 93 | 94 | expect(actions.length).to.equal(2); 95 | expect(actions[0].meta.isApi).to.be.true; 96 | 97 | const {payload} = actions[1]; 98 | expect(payload.error).to.be.defined; 99 | expect(payload.status).to.eql(API_CONSTANTS[418]) 100 | 101 | done(); 102 | }).catch(done) 103 | }); 104 | 105 | }) 106 | 107 | }); 108 | -------------------------------------------------------------------------------- /src/__tests__/lib/createApiHandler.spec.js: -------------------------------------------------------------------------------- 1 | import sinon from 'sinon'; 2 | import {expect} from 'chai'; 3 | import {createApiHandler} from '../../lib/createApiHandler'; 4 | import configureMockStore from 'redux-mock-store'; 5 | import {BASE_URL, generateResponse, makeStore} from '../spec_helpers'; 6 | // import 'whatwg-fetch'; 7 | import fetchMock from 'fetch-mock'; 8 | 9 | describe('apiHandler', () => { 10 | let fn, handlers, store; 11 | let dispatch, getState; 12 | const responseData = 'hello world'; 13 | beforeEach(() => { 14 | fn = (state, action) => responseData; 15 | }); 16 | beforeEach(() => { 17 | handlers = createApiHandler('A_TYPE', (apiStates) => {})(fn); 18 | }); 19 | beforeEach(() => { 20 | let res = makeStore({ 21 | baseUrl: BASE_URL 22 | }, {numbers: []}) 23 | store = res.store; 24 | dispatch = store.dispatch; 25 | getState = store.getState; 26 | }); 27 | 28 | it('can create an apiHandler', () => { 29 | expect(handlers).to.exist; 30 | expect(typeof handlers['A_TYPE_LOADING']).to.eql('function'); 31 | expect(typeof handlers['A_TYPE_ERROR']).to.eql('function'); 32 | expect(handlers['API_A_TYPE_SUCCESS']).to.eql(fn); 33 | }); 34 | 35 | describe('default handlers', () => { 36 | beforeEach(() => { 37 | store = sinon.mock(store); 38 | }) 39 | 40 | it('sets the state to loading without a loading handler taking', () => { 41 | let expectedAction = { 42 | type: 'A_TYPE_SUCCESS', 43 | payload: responseData 44 | } 45 | let res = handlers['A_TYPE_LOADING'](dispatch, getState); 46 | expect(res.loading).to.be.true; 47 | }); 48 | 49 | it('sets runs the success handler function on success', () => { 50 | let res = handlers['A_TYPE_SUCCESS'](dispatch, getState); 51 | expect(typeof res).to.eql('object'); 52 | }) 53 | 54 | it('sets the loading state to false on ERROR', () => { 55 | let res = handlers['A_TYPE_ERROR'](dispatch, getState); 56 | expect(typeof res).to.eql('object'); 57 | }) 58 | }); 59 | 60 | }) 61 | -------------------------------------------------------------------------------- /src/__tests__/lib/createApiMiddleware.spec.js: -------------------------------------------------------------------------------- 1 | import sinon from 'sinon'; 2 | import {expect} from 'chai'; 3 | import configureMockStore from 'redux-mock-store'; 4 | import {makeStore} from '../spec_helpers'; 5 | 6 | const BASE_URL = 'http://fullstackreact.com'; 7 | 8 | const doDispatch = () => {}; 9 | const doGetState = () => {}; 10 | const makeDispatchAction = (action, fn) => dispatch => { 11 | fn && fn(action); 12 | return dispatch(action) 13 | }; 14 | 15 | describe('ApiClient middleware', () => { 16 | let nextHandler, apiMiddleware; 17 | let store, mockStore; 18 | 19 | let createNext = fn => (action) => fn && fn(action); 20 | 21 | let initialState = { numbers: [] }; 22 | let runtimeOpts = {dispatch: doDispatch, getState: doGetState} 23 | 24 | beforeEach(() => { 25 | let res = makeStore({ 26 | baseUrl: BASE_URL 27 | }, {numbers: []}) 28 | nextHandler = res.nextHandler; 29 | store = res.store; 30 | }); 31 | 32 | 33 | it('returns a function', () => { 34 | const actionHandler = nextHandler(createNext()); 35 | 36 | expect(typeof actionHandler).to.eql('function'); 37 | expect(actionHandler.length).to.equal(1); 38 | }) 39 | 40 | describe('non-api requests', () => { 41 | const testType = 'TEST'; 42 | let action, msg; 43 | beforeEach(() => { 44 | let payload = JSON.stringify({add: 1}) 45 | msg = {type: testType, payload}; 46 | }) 47 | 48 | it('runs the action with dispatch', done => { 49 | action = makeDispatchAction(msg, () => done()); 50 | store.dispatch(action) 51 | expect(store.getActions().length).to.eql(1); 52 | expect(store.getActions()[0].type).to.eql(testType); 53 | }); 54 | }); 55 | 56 | describe('api requests', () => { 57 | // pending... as in... this works differently now 58 | // so the old tests do not make sense any more... 59 | // the functionality is tested in createApiActions.spec 60 | }) 61 | }); 62 | -------------------------------------------------------------------------------- /src/__tests__/lib/createReducer.spec.js: -------------------------------------------------------------------------------- 1 | import {expect} from 'chai'; 2 | import {makeStore} from '../spec_helpers'; 3 | import {createReducer} from '../../lib/createReducer'; 4 | 5 | describe('createReducer', () => { 6 | let reducer, handlers, store; 7 | 8 | beforeEach(() => { 9 | let res = makeStore({}, {msg: 'init'}) 10 | store = res.store; 11 | }); 12 | 13 | beforeEach(() => { 14 | let handlers = { 15 | 'HANDLE_THING': (state, action) => ({msg: 'called'}) 16 | } 17 | reducer = createReducer(handlers) 18 | }) 19 | 20 | it('calls a reducer when defined in the hash', () => { 21 | let resp = reducer(store.getState(), {type: 'HANDLE_THING'}); 22 | expect(resp.msg).to.eql('called'); 23 | }); 24 | 25 | it('returns original state with non-defined type handler', () => { 26 | let resp = reducer(store.getState(), {type: 'HANDLE_OTHER_THING'}); 27 | expect(resp.msg).to.eql('init'); 28 | }) 29 | }); 30 | -------------------------------------------------------------------------------- /src/__tests__/lib/createRootReducer.spec.js: -------------------------------------------------------------------------------- 1 | import {expect} from 'chai'; 2 | import sinon from 'sinon' 3 | import {makeStore} from '../spec_helpers'; 4 | import {createRootReducer} from '../../lib/createRootReducer'; 5 | 6 | describe('createRootReducer', () => { 7 | let handlers, store; 8 | 9 | beforeEach(() => { 10 | let res = makeStore({}, {msg: 'init'}) 11 | store = res.store; 12 | }); 13 | 14 | beforeEach(() => { 15 | handlers = createRootReducer({ 16 | users: {} 17 | }); 18 | }) 19 | 20 | it('returns an actions object', () => { 21 | expect(handlers.actions).to.be.defined; 22 | }) 23 | it('returns a reducers object', () => { 24 | expect(handlers.reducers).to.be.defined; 25 | }) 26 | it('returns an initialState object', () => { 27 | expect(handlers.initialState).to.be.defined; 28 | }); 29 | 30 | ['actions', 'reducers', 'initialState'].forEach(key => { 31 | // A little meta 32 | it(`has a users key in ${key}`, () => { 33 | expect(handlers[key].users).to.be.defined; 34 | }); 35 | }); 36 | 37 | describe('initialInitialState', () => { 38 | beforeEach(() => { 39 | handlers = createRootReducer({ 40 | users: { 41 | initialState: { currentUser: { name: 'Ari' }} 42 | }, 43 | events: {} 44 | }, { 45 | initialInitialState: { 46 | users: { currentUser: { name: 'fred' }}, 47 | } 48 | }); 49 | }) 50 | 51 | it('overrides the initial state of the user', () => { 52 | expect(handlers.initialState.users.currentUser.name).to.eql('Ari') 53 | }) 54 | it('does not override initial state when none is defined', () => { 55 | expect(handlers.initialState.events).to.eql({}) 56 | }); 57 | }) 58 | 59 | describe('initialActions', () => { 60 | let sayFn, rejectFn, makeFn; 61 | beforeEach(() => { 62 | sayFn = sinon.spy(); 63 | rejectFn = sinon.spy(); 64 | makeFn = sinon.spy(); 65 | 66 | handlers = createRootReducer({ 67 | users: { 68 | actions: { say: sayFn } 69 | }, 70 | events: {} 71 | }, { 72 | initialActions: { 73 | users: {reject: rejectFn} 74 | } 75 | }) 76 | }) 77 | 78 | it('creates actions as an empty object for modules, even if they do not exist', () => { 79 | expect(handlers.actions.events).to.eql({}); 80 | }) 81 | 82 | it('keeps the actions defined for those that do define actions', () => { 83 | expect(handlers.actions.users.say).to.be.defined; 84 | expect(typeof handlers.actions.users.say).to.eql('function'); 85 | }); 86 | 87 | it('does not override a function in actions', () => { 88 | handlers.actions.users.say('bob') 89 | expect(sayFn).to.have.been.calledWith('bob') 90 | handlers.actions.users.reject(); 91 | expect(rejectFn).to.have.been.called 92 | }); 93 | }) 94 | 95 | describe('initialReducers', () => { 96 | let routingReducer, userReducer; 97 | beforeEach(() => { 98 | routingReducer = sinon.spy(); 99 | userReducer = sinon.spy(); 100 | 101 | handlers = createRootReducer({ 102 | users: { 103 | reducer: userReducer 104 | }, 105 | events: {} 106 | }, { 107 | initialReducers: { 108 | routing: routingReducer 109 | } 110 | }) 111 | }); 112 | 113 | it('merges passed reducer in', () => { 114 | expect(handlers.reducers.users).to.eql(userReducer); 115 | }) 116 | 117 | it('sets the reducer to a noop value when no reducer is passed', () => { 118 | expect(typeof handlers.reducers.events).to.eql('function') 119 | }); 120 | 121 | it('sets the reducer to the initial reducer if no module is found', () => { 122 | expect(handlers.reducers.routing).to.eql(routingReducer) 123 | }) 124 | }) 125 | 126 | }); 127 | -------------------------------------------------------------------------------- /src/__tests__/lib/utils.spec.js: -------------------------------------------------------------------------------- 1 | import {expect} from 'chai'; 2 | import {apiKeys, syncEach} from '../../lib/utils'; 3 | 4 | describe('Utils', () => { 5 | describe('apiKeys', () => { 6 | it('creates state keys', () => { 7 | let keys = apiKeys('PERSON') 8 | expect(keys).to.include('PERSON_LOADING') 9 | expect(keys).to.include('PERSON_SUCCESS') 10 | expect(keys).to.include('PERSON_ERROR') 11 | }); 12 | it('creates state keys with dynamic states', () => { 13 | let keys = apiKeys('PERSON', ['sit']) 14 | expect(keys).to.include('PERSON_SIT') 15 | }); 16 | }) 17 | 18 | describe('syncEach', () => { 19 | 20 | it('returns the initial value with an empty list', (done) => { 21 | syncEach(101, (curr) => curr)([]) 22 | .then((val) => { 23 | expect(val).to.equal(101); 24 | done(); 25 | }).catch(done); 26 | }) 27 | 28 | it('waits for a list of atomic values', (done) => { 29 | syncEach(1, (val, curr) => val + curr)([2, 3]) 30 | .then((val) => { 31 | expect(val).to.equal(6); 32 | done(); 33 | }).catch(done); 34 | }); 35 | 36 | it('waits for a list of promises', (done) => { 37 | const delayedPromise = (n) => (curr) => { 38 | return new Promise(resolve => { 39 | setTimeout(() => resolve(n + curr), n); 40 | }) 41 | } 42 | const list = [ 43 | delayedPromise(5), 44 | delayedPromise(5) 45 | ] 46 | 47 | syncEach(Promise.resolve(10))(list) 48 | .then(val => { 49 | expect(val).to.equal(20); // 10 + 15 + 20 50 | done(); 51 | }).catch(done); 52 | }) 53 | 54 | }) 55 | }) 56 | -------------------------------------------------------------------------------- /src/__tests__/spec_helpers.js: -------------------------------------------------------------------------------- 1 | import configureMockStore from 'redux-mock-store'; 2 | import fetchMock from 'fetch-mock'; 3 | import thunk from 'redux-thunk'; 4 | import createApiMiddleware from '../lib/createApiMiddleware'; 5 | 6 | import chai from 'chai'; 7 | import sinonChai from 'sinon-chai'; 8 | 9 | chai.use(sinonChai); 10 | 11 | export const makeStore = (opts, initialState) => { 12 | let apiMiddleware = createApiMiddleware(opts); 13 | let nextHandler = apiMiddleware(store) 14 | 15 | let mockStore = configureMockStore([apiMiddleware, thunk]) 16 | let store = mockStore(initialState); 17 | return {nextHandler, store}; 18 | } 19 | 20 | export const BASE_URL = 'http://fullstackreact.com'; 21 | 22 | const handleResponse = (status, msg) => (reqUrl, reqOpts) => { 23 | if (typeof msg === 'function') { 24 | return msg(reqUrl, reqOpts); 25 | } 26 | return {status, body: JSON.stringify(msg)} 27 | } 28 | 29 | export const makeBaseOpts = (opts = {}) => Object.assign({}, { 30 | _debug: false, 31 | autoExecute: false, 32 | baseUrl: BASE_URL, 33 | appendExt: false, // optional 34 | headers: { 35 | 'X-Requested-With': 'spec' 36 | } 37 | }, opts); 38 | 39 | export const generateResponse = (path, status, msg={}) => { 40 | return fetchMock.mock(`${BASE_URL}${path}`, handleResponse(status, msg)); 41 | } 42 | 43 | export const doDispatch = () => {}; 44 | export const doGetState = () => {}; 45 | -------------------------------------------------------------------------------- /src/api.js: -------------------------------------------------------------------------------- 1 | export { apiClient } from './lib/apiClient.js'; 2 | export { createApiMiddleware } from './lib/createApiMiddleware'; 3 | export { createApiAction, api } from './lib/createApiActions'; 4 | export { createApiHandler, apiHandler } from './lib/createApiHandler'; 5 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | export { createConstants } from './lib/constants'; 2 | export { createReducer } from './lib/createReducer'; 3 | export { bindActionCreatorsToStore } from './lib/bindActionCreatorsToStore'; 4 | export { createRootReducer } from './lib/createRootReducer'; 5 | -------------------------------------------------------------------------------- /src/lib/actions.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fullstackreact/redux-modules/6f8a4daade976b5d189f6044a4d4f59bc3cc5e2c/src/lib/actions.js -------------------------------------------------------------------------------- /src/lib/apiClient.js: -------------------------------------------------------------------------------- 1 | import * as qs from 'query-string'; 2 | import {noop, syncEach} from './utils'; 3 | 4 | export const sharedHeaders = { 5 | 'Content-Type': 'application/json', 6 | 'Accept': 'application/json', 7 | 'X-Requested-With': 'XMLHttpRequest' 8 | }; 9 | 10 | // Helpers 11 | // JSON parser 12 | // const parseJson = (resp) => resp.json(); 13 | const parseJson = (state, opts) => (resp) => { 14 | return resp.json(); 15 | } 16 | 17 | // MIDDLEWARE THINGS 18 | const checkStatus = (resp) => { 19 | if (!resp.ok) { 20 | let err = new Error(resp.statusText); 21 | err.status = resp.status; 22 | err.response = resp; 23 | err.body = Promise.resolve(noop(resp)) 24 | .then(resp => resp.json()) 25 | .catch((err) => Promise.reject({msg: 'Service error'})) 26 | throw err; 27 | } 28 | return resp; 29 | } 30 | 31 | /** 32 | * API Client class 33 | * 34 | * baseOpts 35 | * { 36 | * baseUrl: Required, 37 | * appendExt: boolean || string 38 | * } 39 | */ 40 | export class ApiClient { 41 | constructor(baseOpts, getState) { 42 | // basically makeRequest 43 | this._debugging = baseOpts._debug; 44 | 45 | ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'].forEach((method) => { 46 | this[method.toLowerCase()] = (options) => { 47 | let opts = this.requestDefaults(method, options, baseOpts); 48 | 49 | let url = this._getUrl(options, baseOpts); 50 | 51 | let requestTransforms = 52 | this._parseOpt('requestTransforms', options, baseOpts, []); 53 | let responseTransforms = 54 | this._parseOpt('responseTransforms', options, baseOpts, [parseJson]); 55 | 56 | // let requestTransforms = [].concat(reqTransforms); 57 | // let responseTransforms = [].concat(respTransforms); 58 | 59 | return new Promise((resolve, reject) => { 60 | this.runTransforms(requestTransforms, getState, opts) 61 | .then(this.debugLog(() => 'requesting...')) 62 | .then((transformedOpts) => fetch(url, transformedOpts)) 63 | .then(this.debugLog()) 64 | .then(checkStatus) 65 | .then(this.debugLog(resp => `Status: ${resp}`)) 66 | .then((resp) => this 67 | .runTransforms(responseTransforms, getState, resp)) 68 | .then(this.debugLog(json => `JSON: ${json}`)) 69 | .then(resolve) 70 | .catch(err => reject(err)) 71 | }); 72 | } 73 | }); 74 | } 75 | 76 | runTransforms (transforms:Array, getState:Function, opts:Object) { 77 | return syncEach(noop(opts), (fn, prev) => { 78 | return typeof fn === 'function' ? fn(getState, opts) : fn; 79 | })(transforms) 80 | } 81 | 82 | debugLog(msgFn) { 83 | return (args) => { 84 | if (this._debugging) { 85 | console.log((msgFn || noop)(args)) 86 | } 87 | return args; 88 | } 89 | } 90 | 91 | // Option handling 92 | _parseOpt(key, opts, defaultOpts = {}, defaultValue = null) { 93 | let val = opts[key] || defaultOpts[key]; 94 | if (!val) { 95 | return defaultValue; 96 | } 97 | 98 | return (typeof val === 'function') ? val.call(this, opts) : val; 99 | } 100 | 101 | requestDefaults (method, params, defaultOpts) { 102 | let opts = params || {}; 103 | 104 | let customHeaders = this._parseOpt('headers', opts, defaultOpts, {}); 105 | let headers = Object.assign({}, sharedHeaders, customHeaders); 106 | 107 | let meta = this._parseOpt('meta', opts, defaultOpts, {}); 108 | let data = this._parseOpt('data', opts, defaultOpts, {}); 109 | 110 | let requestOpts = { 111 | method: method, 112 | headers: headers, 113 | meta: meta, 114 | } 115 | 116 | if (method === 'POST' || method === 'PUT' || method === 'PATCH') { 117 | requestOpts.body = JSON.stringify(data); 118 | } 119 | 120 | return requestOpts; 121 | } 122 | 123 | // Get custom url if included in the opts 124 | // otherwise, get the default one 125 | _getUrl(opts, defaultOpts = {}) { 126 | if (typeof opts === 'string') { 127 | opts = {path: opts} 128 | } 129 | let url = this._parseOpt('url', opts); 130 | let path = this._parseOpt('path', opts); 131 | 132 | if (path) { 133 | path = path[0] !== '/' ? '/' + path : path; 134 | } 135 | 136 | if (!url) { 137 | url = [defaultOpts.baseUrl, path].join(''); // eslint-disable-line no-undef 138 | } 139 | 140 | let appendPath = this._parseOpt('appendPath', opts, defaultOpts); 141 | if (appendPath) { 142 | url = [url, appendPath].join('') 143 | } 144 | 145 | // Append (or don't) 146 | let appendExt = this._parseOpt('appendExt', opts, defaultOpts) 147 | if (appendExt) { 148 | url = url + `.${appendExt}`; 149 | } 150 | 151 | let params = this._parseOpt('params', opts, defaultOpts); 152 | if (params) { 153 | let qsParams = qs.stringify(params); 154 | url = url + '?' + qsParams; 155 | } 156 | 157 | return url; 158 | } 159 | } 160 | 161 | export default ApiClient; 162 | -------------------------------------------------------------------------------- /src/lib/bindActionCreatorsToStore.js: -------------------------------------------------------------------------------- 1 | import { bindActionCreators } from 'redux' 2 | 3 | export const bindActionCreatorsToStore = (actions, store) => { 4 | Object.keys(actions).forEach(k => { 5 | let theseActions = actions[k]; 6 | 7 | let actionCreators = Object.keys(theseActions) 8 | .reduce((sum, actionName) => { 9 | // theseActions are each of the module actions which 10 | // we export from the `rootReducer.js` file (we'll create shortly) 11 | let fn = theseActions[actionName]; 12 | // We'll bind them to the store 13 | sum[actionName] = fn.bind(store); 14 | return sum; 15 | }, {}); 16 | 17 | // Using react-redux, we'll bind all these actions to the 18 | // store.dispatch 19 | actions[k] = bindActionCreators(actionCreators, store.dispatch); 20 | }); 21 | 22 | return actions; 23 | } 24 | -------------------------------------------------------------------------------- /src/lib/constants.js: -------------------------------------------------------------------------------- 1 | import invariant from 'invariant'; 2 | import {upcase, apiKeys, apiStates, getApiTypes, toApiKey} from './utils'; 3 | 4 | export const REDUX_MODULE_ACTION_KEY = 'REDUX_MODULES/ACTION' 5 | export const REDUX_MODULE_API_ACTION_KEY = 'REDUX_MODULES/API_ACTION' 6 | 7 | let customTypes = { 8 | api: apiStates 9 | } 10 | /* 11 | * get the api values 12 | */ 13 | export function apiValues(name, states = apiStates) { 14 | return apiKeys(name, states) 15 | .reduce((sum, key) => ({ 16 | ...sum, 17 | [key]: toApiKey(key) 18 | }), {}); 19 | } 20 | 21 | export function createCustomTypes(name, states = []) { 22 | customTypes[name] = states; 23 | } 24 | 25 | export function createConstants(opts) { 26 | opts = opts || {}; 27 | let separator = opts.separator || '_'; 28 | 29 | if (opts.customTypes) { 30 | Object.keys(opts.customTypes).forEach(key => { 31 | createCustomTypes(key, opts.customTypes[key]) 32 | }); 33 | } 34 | 35 | if (typeof opts === 'string') { 36 | opts = {prefix: opts} 37 | } 38 | 39 | const defineType = (obj, prefix, n, v) => { 40 | if (typeof n === 'object') { 41 | // If it's an API type, decorate with the different 42 | // api states 43 | Object.keys(n).forEach((key) => { 44 | if (n.hasOwnProperty(key)) { 45 | let val = n[key]; 46 | if (val && val.types) { 47 | let types = Array.isArray(val.types) ? val.types : val.types.split(' ,'); 48 | types.forEach(type => { 49 | // Define custom types for each 50 | const states = customTypes[type] || []; 51 | states.forEach((customKey) => { 52 | const name = upcase(`${key}${separator}${customKey}`) 53 | const keyPrefix = upcase([type, customKey].join(separator)) 54 | const valuePrefix = [prefix, type].join(separator); 55 | // const apiPrefix = `api_${prefix}`; 56 | defineType(obj, valuePrefix, name); 57 | }); 58 | }) 59 | } 60 | if (val && val.api) defineApi(obj, prefix, key, val.states); 61 | 62 | // Don't store objects in static arrays 63 | if (typeof val === 'object') { 64 | val = null; 65 | } 66 | 67 | defineType(obj, prefix, key, v); 68 | } 69 | }); 70 | } else { 71 | v = v || [].concat.apply([], [prefix, n]).join(separator).toUpperCase(); 72 | Object.defineProperty(obj, n, { 73 | value: v, 74 | enumerable: true, 75 | writable: false, 76 | configurable: false 77 | }); 78 | } 79 | return obj; 80 | }; 81 | 82 | const defineApi = (obj, prefix, n, states) => { 83 | apiKeys(n, states).forEach((apiKey) => { 84 | const apiPrefix = `api_${prefix}`; 85 | defineType(obj, apiPrefix, apiKey); 86 | }); 87 | }; 88 | 89 | 90 | const definer = (obj, prefix) => { 91 | return (...definitions) => { 92 | definitions.forEach((def) => { 93 | defineType(obj, prefix, def); 94 | }); 95 | return obj; 96 | }; 97 | }; 98 | 99 | let initialObject = opts.initialObject || {}; 100 | let prefix = opts.prefix || ''; 101 | return definer(initialObject, prefix); 102 | } 103 | 104 | export default createConstants; 105 | -------------------------------------------------------------------------------- /src/lib/createApiActions.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable func-names */ 2 | /* *********************************************** 3 | * Example usage: 4 | // take the main action, and then return an object with each apiState handler function. 5 | @apiHandler(types.DOTHING, (apiTypes) => ({ 6 | [apiTypes.LOADING]: (state) => ({ 7 | ...state, 8 | loading: true, 9 | time: Date.now(), 10 | errors: [], 11 | }), 12 | [apiTypes.ERROR]: (state, action) => { 13 | // do stuf, like set the biggest thing, and do not return object immediately. 14 | let biggest = state.things.sort().shift 15 | return { 16 | ...state, 17 | biggest: biggest, 18 | loading: false, 19 | errors: action.payload.error, 20 | performance: Date.now() - state.time, 21 | } 22 | }, 23 | })) 24 | handleGetMe: (state, action) => { 25 | return { 26 | ...userForState(state, action), 27 | wait_for_load_with_token: false, 28 | } 29 | }, 30 | // here is a template to start with: 31 | @apiHandler(types.SAVE_ESTIMATE, (apiTypes) => ({ 32 | [apiTypes.LOADING]: (state) => ({...state}), 33 | [apiTypes.ERROR]: (state, action) => ({...state, action.payload}), 34 | })) 35 | handleSaveEstimateSuccess: {} 36 | ************************************************/ 37 | import {createAction} from 'redux-actions'; 38 | import {REDUX_MODULE_API_ACTION_KEY} from './constants'; 39 | import ApiClient from './apiClient'; 40 | import {apiStates, getApiTypes, toApiKey, noop} from './utils'; 41 | 42 | export const API_CONSTANTS = { 43 | 401: 'API_ERROR_FOUR_OH_ONE', 44 | 418: 'API_ERROR_I_AM_A_LITTLE_TEAPOT', 45 | // 422: 'API_ERROR_UNPROCESSABLE', 46 | UNKNOWN_ERROR: 'API_ERROR_UNKNOWN' 47 | } 48 | 49 | const getActionTypesForKeys = (type, actionCreator = noop, metaCreator = noop) => getApiTypes(type) 50 | .reduce((memo, key, idx) => ({ 51 | ...memo, 52 | [apiStates[idx]]: createAction(toApiKey(key), actionCreator, (...args) => ({isApi: true, ...metaCreator(args)})) 53 | }), {}); 54 | 55 | // Define a decorator for a function defined in an object 56 | // that is expected to be an action. 57 | // @param type - string constant 58 | export function createApiAction(type, requestTransforms, responseTransforms, metaCreator) { 59 | // The decorator function wrapper (design: decoratorFn(fn())) 60 | // @param target - function to be decorated 61 | // @param name - the function name 62 | // @param def - the Object.defineProperty definition 63 | // 64 | // Functionally, this works by accepting the object definition type 65 | // from ES5 syntax, i.e. 66 | // Object.defineProperty(this, 'fetchAll', {configurable: false, value: 2}) 67 | // and it manipulates the definition by changing the value to be a function 68 | // that wraps the different api states, aka LOADING, SUCCESS, ERROR 69 | return function decoration(target) { 70 | // ApiTypes is the string constants mapped to a 71 | // createdAction (using `createAction`) 72 | // i.e. { loading: fetchAllLoading(), // anonymouse function 73 | // success: fetchAllSuccess(), 74 | // error: fetchAllError(), 75 | // } 76 | let apiTypes = getActionTypesForKeys(type, (t) => t, metaCreator); 77 | // The new value for the object definition 78 | // return function decorated(globalOpts) { 79 | // globalOpts = globalOpts || {}; 80 | // return a function (for thunk) 81 | return (configurationOpts={}) => (dispatch, getState) => { 82 | 83 | let autoExecute = true; 84 | if (typeof configurationOpts.autoExecute !== 'undefined') { 85 | autoExecute = configurationOpts.autoExecute; 86 | delete configurationOpts['autoExecute']; 87 | } 88 | 89 | // Small helper to turn all functions within this decorated functions 90 | // into a promise 91 | let promiseWrapper = (fn) => { 92 | return (...args) => Promise.resolve(dispatch(fn(...args))); 93 | }; 94 | 95 | // The default handlers for the different states of the api request 96 | let loading = promiseWrapper(apiTypes.loading); 97 | let success = promiseWrapper(apiTypes.success); 98 | let error = (errorObj) => { 99 | const getErrorStatus = status => typeof API_CONSTANTS[status] !== 'undefined' ? 100 | API_CONSTANTS[status] : 101 | API_CONSTANTS.UNKNOWN_ERROR; 102 | 103 | const reduceError = err => dispatch(apiTypes.error({error: errorObj, body: err})); 104 | const errType = toApiKey(getApiTypes(type)[2]); 105 | const errStatus = errorObj && errorObj.status ? 106 | getErrorStatus(errorObj.status) : 107 | API_CONSTANTS.UNKNOWN_ERROR; 108 | 109 | const action = { 110 | type: errType, 111 | payload: { 112 | error: errorObj, 113 | status: errStatus 114 | } 115 | }; 116 | 117 | dispatch(action) 118 | return action; 119 | } 120 | 121 | const runFn = (runtimeOpts) => { 122 | const opts = Object.assign({}, configurationOpts, runtimeOpts); 123 | // The `initializer` is the original pre-decorated function 124 | // let actionFn = def ? def.initializer(opts) : target; 125 | let actionFn = target; 126 | // Every action gets an instance of ApiClient 127 | let client = 128 | new ApiClient(opts, getState, requestTransforms, responseTransforms); 129 | // NOTE, check this: do we need below version ? 130 | // new ApiClient(opts, getState, requestTransforms, responseTransforms); 131 | 132 | // callAction wraps the `async` functionality that ensures 133 | // we always get a promise returned (and can be used to pass along 134 | // other thunk functions) 135 | let callAction = () => { 136 | loading(opts); 137 | let retVal = actionFn.call(null, client, opts, getState, dispatch); 138 | if (typeof retVal.then !== 'function') { 139 | retVal = Promise.resolve(retVal); 140 | } 141 | return retVal 142 | .then(success) 143 | // Should we _also_ fire the original event, even if it's an API request too? 144 | // .then((...args) => dispatch({type: type, payload: args})) 145 | .catch(error); 146 | }; 147 | // NOTE, check this: do we need below version ? 148 | // new ApiClient(opts, getState, requestTransforms, responseTransforms); 149 | 150 | // callAction wraps the `async` functionality that ensures 151 | // we always get a promise returned (and can be used to pass along 152 | // other thunk functions) 153 | return callAction(); 154 | }; 155 | 156 | const action = { 157 | type: REDUX_MODULE_API_ACTION_KEY, 158 | meta: { runFn, type } 159 | } 160 | if (autoExecute) { 161 | dispatch(action); 162 | } else { 163 | return action; 164 | } 165 | // dispatch(action); 166 | // return action; 167 | }; 168 | // }; 169 | }; 170 | } 171 | 172 | // decorator form 173 | // @param type - string constant 174 | // @return function - a nwe decorated function Object.defineProperty 175 | export function api(type, requestTransforms, responseTransforms, metaCreator) { 176 | // The decorator function wrapper (design: decoratorFn(fn())) 177 | // @param target - function to be decorated 178 | // @param name - the function name 179 | // @param def - the Object.defineProperty definition 180 | // 181 | // Functionally, this works by accepting the object definition type 182 | // from ES5 syntax, i.e. 183 | // Object.defineProperty(this, 'fetchAll', {configurable: false, value: 2}) 184 | // and it manipulates the definition by changing the value to be a function 185 | // that wraps the different api states, aka LOADING, SUCCESS< ERROR 186 | return function decoration(target, name, def) { 187 | let newVal = createApiAction(type, requestTransforms, responseTransforms, metaCreator)(def.initializer); 188 | let newDef = { 189 | enumerable: true, 190 | writable: true, 191 | configurable: true, 192 | value: newVal, 193 | }; 194 | 195 | return newDef; 196 | } 197 | } 198 | 199 | export default api; 200 | -------------------------------------------------------------------------------- /src/lib/createApiHandler.js: -------------------------------------------------------------------------------- 1 | import {upcase, apiStates, getApiTypes, toApiKey} from './utils'; 2 | 3 | function apiKeys(name) { 4 | return apiStates.map((state) => upcase(`${name}_${state}`)) 5 | } 6 | 7 | // Default reducers (this happens when you don't define a reducer per state) 8 | // Order is: loading, success, error 9 | const apiStateHandlers = [ 10 | (state) => ({...state, loading: true}), 11 | (state, action) => ({...state, loading: false, data: action.payload, errors: []}), 12 | (state, action) => ({...state, loading: false, data: [], errors: action.payload}) 13 | ] 14 | 15 | // Mapping of the state to their default handler from above 16 | // NOTE: this one differs from uncommented version also 17 | const apiReducers = { 18 | [apiStates[0]]: apiStateHandlers[0], 19 | [apiStates[1]]: apiStateHandlers[1], 20 | [apiStates[2]]: apiStateHandlers[2], 21 | } 22 | 23 | /** 24 | * Build the state to names handler reducer and 25 | * the handlers object in one to avoid multiple iterations 26 | * @constructor 27 | * @param {string} type string - the type constant 28 | * @returns {object} object returns with reducers and names 29 | */ 30 | function handlerReducersForType(type:String) { 31 | let apiActionTypes = getApiTypes(type); 32 | let reducers = {}; 33 | let namesToState = {}; 34 | apiActionTypes.forEach((key, idx) => { 35 | reducers[apiActionTypes[idx]] = apiReducers[apiStates[idx]]; 36 | namesToState[upcase(apiStates[idx])] = toApiKey(apiActionTypes[idx]); 37 | }); 38 | return {reducers, namesToState}; 39 | } 40 | 41 | // Decorator for a reducer object property function 42 | // @param String type - string constant type 43 | // @param Function handlerFn (optional) - Function defining custom reducers that 44 | // accepts a single argument of the api types mapped to their 45 | // corresponding constant, i.e. 46 | // { loading: 'FETCH_ALL_LOADING', 47 | // success: 'FETCH_ALL_SUCCESS', 48 | // error: 'FETCH_ALL_ERROR' } 49 | // Usage: 50 | // @apiHandler('FETCH_ALL', (apiStates) => {}) 51 | // i.e: 52 | // @apiHandler(types.SAVE_CROP) 53 | // handleSaveCrop: (state, action) => {return new state after doing stuff..}) 54 | export function createApiHandler(type, handlerFn) { 55 | // The decorator function 56 | // target is the object, 57 | // name is the function name 58 | // def is the object property definition 59 | return function decoratedHandler(target) { 60 | // Default api action handlers 61 | let {reducers, namesToState} = handlerReducersForType(type); 62 | 63 | // If there is no handle function or the handle function is not 64 | // a function, then set it to be a identity function 65 | if (!handlerFn || typeof handlerFn !== 'function') { 66 | handlerFn = (d) => { 67 | return d; 68 | } 69 | } 70 | 71 | // Custom handlers for the different api states from the second argument 72 | // If no function is passed, the identify function is used 73 | let fnHandlerKeys = handlerFn(namesToState) || {}; 74 | 75 | // Compute difference between the default hanlders and our almost new target 76 | // Keys our custom function handler overwrites defaults 77 | let handlerKeys = Object.keys(fnHandlerKeys); 78 | 79 | // All handler keys, i.e. loading, success, error 80 | let defaultReducerKeys = Object.keys(reducers); 81 | 82 | // The difference between what we handled and what we did not 83 | // i.e. allows us to only overwrite 1..n without overwriting other defaults 84 | let missingHandlerKeys = defaultReducerKeys.filter(x => handlerKeys.indexOf(x) === -1); 85 | 86 | let handlers = Object.assign({}, fnHandlerKeys, {}); 87 | // Set defaults for those undefined by custom function 88 | missingHandlerKeys.forEach(k => handlers[k] = reducers[k]); 89 | 90 | // The handler passed by the decorated function 91 | let valueHandler = target; 92 | 93 | // ALWAYS set the function to be the defined function 94 | handlers[namesToState.SUCCESS] = valueHandler; 95 | 96 | // Return the new object property definition 97 | return handlers; 98 | } 99 | } 100 | 101 | // decorator form 102 | // @param type - string constant 103 | // @return function - a nwe decorated function Object.defineProperty 104 | export function apiHandler(type, handlerFn) { 105 | // The decorator function wrapper (design: decoratorFn(fn())) 106 | // @param target - function to be decorated 107 | // @param name - the function name 108 | // @param def - the Object.defineProperty definition 109 | // 110 | // Functionally, this works by accepting the object definition type 111 | // from ES5 syntax, i.e. 112 | // Object.defineProperty(this, 'fetchAll', {configurable: false, value: 2}) 113 | // and it manipulates the definition by changing the value to be a function 114 | // that wraps the different api states, aka LOADING, SUCCESS< ERROR 115 | return function decoration(target, name, def) { 116 | let valueHandler = def.initializer(type); 117 | let handlers = createApiHandler(type, handlerFn)(valueHandler); 118 | 119 | // Dark and murky overwrite object in place -- possibly the grossest thing ever 120 | Object.assign(target, handlers); 121 | 122 | let newDef = { 123 | enumerable: true, 124 | writable: true, 125 | configurable: true, 126 | value: handlers, 127 | }; 128 | 129 | return newDef; 130 | } 131 | } 132 | 133 | export default apiHandler; 134 | -------------------------------------------------------------------------------- /src/lib/createApiMiddleware.js: -------------------------------------------------------------------------------- 1 | import {REDUX_MODULE_API_ACTION_KEY} from './constants'; 2 | /* 3 | * Decorate the api actions with common handlers 4 | */ 5 | export const createApiMiddleware = (baseOpts) => { 6 | return store => next => action => { 7 | 8 | if (action.type === REDUX_MODULE_API_ACTION_KEY) { 9 | const { runFn: fn } = action && action.meta || {}; 10 | if (fn) { 11 | const res = fn(baseOpts); 12 | return res; 13 | } 14 | } else { 15 | return next(action); 16 | } 17 | } 18 | } 19 | 20 | export default createApiMiddleware; 21 | -------------------------------------------------------------------------------- /src/lib/createReducer.js: -------------------------------------------------------------------------------- 1 | export const createReducer = function(actionHandlers, initialState={}) { 2 | return function(state = initialState, action): Object { 3 | const handler = actionHandlers[action.type]; 4 | return handler ? handler(state, action) : state; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/lib/createRootReducer.js: -------------------------------------------------------------------------------- 1 | // create root reducer 2 | import { combineReducers } from 'redux'; 3 | 4 | const noop = (r) => r; 5 | export const createRootReducer = (modules, { 6 | initialActions={}, 7 | initialInitialState={}, 8 | initialReducers={} 9 | }={}) => { 10 | // Copies of initially passed in config objects 11 | let actions = Object.assign({}, initialActions); 12 | let initialState = Object.assign({}, initialInitialState); 13 | let reducers = Object.assign({}, initialReducers); 14 | 15 | Object.keys(modules).forEach(key => { 16 | const module = modules[key]; 17 | 18 | initialState[key] = Object.assign({}, 19 | initialState[key] || {}, 20 | module.initialState || {}); 21 | 22 | actions[key] = Object.assign({}, 23 | actions[key] || {}, 24 | module.actions || {}); 25 | 26 | reducers[key] = module.reducer || noop; 27 | }); 28 | 29 | return {initialState, actions, reducers} 30 | } 31 | // const containers = { 32 | // events: require('./modules/events'), 33 | // currentEvent: require('./modules/currentEvent'), 34 | // images: require('./modules/images'), 35 | // users: require('./modules/users') 36 | // } 37 | // export let actions = { 38 | // routing: { 39 | // navigateTo: path => dispatch => dispatch(push(path)) 40 | // } 41 | // } 42 | // 43 | // export let initialState = {} 44 | // export let reducers = {routing}; 45 | // 46 | // Object.keys(containers).forEach(key => { 47 | // const container = containers[key]; 48 | // initialState[key] = container.initialState || {}; 49 | // actions[key] = container.actions; 50 | // reducers[key] = container.reducer; 51 | // }); 52 | // 53 | // export const rootReducer = combineReducers(reducers); 54 | -------------------------------------------------------------------------------- /src/lib/utils.js: -------------------------------------------------------------------------------- 1 | import invariant from 'invariant'; 2 | 3 | /* 4 | * Default api states 5 | */ 6 | export const apiStates = ['loading', 'success', 'error']; 7 | 8 | export const upcase = (str) => str.toUpperCase(); 9 | 10 | // Polyfill Array.isArray 11 | if (!Array.isArray) { 12 | Array.isArray = function(arg) { 13 | return Object.prototype.toString.call(arg) === '[object Array]'; 14 | }; 15 | } 16 | 17 | /* 18 | * apiKeys to fetch the api key type 19 | */ 20 | export function apiKeys(name, states = apiStates) { 21 | return states.map((state) => upcase(`${name}_${state}`)) 22 | } 23 | 24 | export const toApiKey = (key) => upcase(`api_${key}`) 25 | export const getApiTypes = (type) => apiKeys(type).reduce((memo, key) => memo.concat(key), []); 26 | 27 | export const noop = (r) => r; 28 | export const syncEach = (initial, cb) => { 29 | invariant(initial, 'No initial value defined'); 30 | 31 | cb = typeof cb === 'function' ? cb : noop; 32 | 33 | return (list) => { 34 | return new Promise(function(resolve, reject) { 35 | list = list.slice(0); 36 | 37 | const doNext = (val) => { 38 | if (list.length) { 39 | let item = list.shift(); 40 | 41 | let fn = typeof item === 'function' ? cb(item) : cb; 42 | 43 | let ret; 44 | if ('then' in Object(val)) { 45 | ret = val.then((res) => fn(res, item)) 46 | } else { 47 | ret = Promise.resolve(fn(val, item)) 48 | } 49 | 50 | ret.then(doNext, reject); 51 | } else { 52 | resolve(val); 53 | } 54 | } 55 | 56 | doNext(initial); 57 | }); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | // require('babel-register'); 2 | 3 | const env = process.env; 4 | const NODE_ENV = process.env.NODE_ENV; 5 | const isDev = NODE_ENV === 'development'; 6 | const isTest = NODE_ENV === 'test'; 7 | 8 | const webpack = require('webpack'); 9 | const marked = require('marked'); 10 | const fs = require('fs'); 11 | const path = require('path'), 12 | join = path.join, 13 | resolve = path.resolve; 14 | 15 | const root = resolve(__dirname); 16 | const src = join(root, 'src'); 17 | const examples = join(root, 'www'); 18 | const modules = join(root, 'node_modules'); 19 | const dest = join(root, 'public'); 20 | 21 | const getConfig = require('hjs-webpack') 22 | 23 | var config = getConfig({ 24 | isDev, 25 | in: join(examples, 'index.js'), 26 | out: dest, 27 | clearBeforeBuild: true, 28 | html: function(context, cb) { 29 | context.publicPath = isDev ? 'http://localhost:3000/' : '' 30 | 31 | fs.readFile(join(root, 'README.md'), (err, data) => { 32 | if (err) { 33 | return cb(err); 34 | } 35 | cb(null, { 36 | 'index.html': context.defaultTemplate(), 37 | }) 38 | }) 39 | } 40 | }); 41 | 42 | const dotenv = require('dotenv'); 43 | const envVariables = dotenv.config(); 44 | 45 | // Converts keys to be surrounded with __ 46 | const defines = 47 | Object.keys(envVariables) 48 | .reduce((memo, key) => { 49 | const val = JSON.stringify(envVariables[key]); 50 | memo[`__${key.toUpperCase()}__`] = val; 51 | return memo; 52 | }, { 53 | __NODE_ENV__: JSON.stringify(env.NODE_ENV), 54 | __IS_DEV__: isDev 55 | }) 56 | 57 | 58 | config.externals = { 59 | 'window.google': true 60 | } 61 | 62 | // Setup css modules require hook so it works when building for the server 63 | const cssModulesNames = `${isDev ? '[path][name]__[local]__' : ''}[hash:base64:5]`; 64 | const matchCssLoaders = /(^|!)(css-loader)($|!)/; 65 | 66 | const findLoader = (loaders, match, fn) => { 67 | const found = loaders.filter(l => l && l.loader && l.loader.match(match)) 68 | return found ? found[0] : null; 69 | } 70 | 71 | const cssloader = findLoader(config.module.loaders, matchCssLoaders); 72 | const newloader = Object.assign({}, cssloader, { 73 | test: /\.module\.css$/, 74 | include: [src, examples], 75 | loader: cssloader.loader.replace(matchCssLoaders, `$1$2?modules&localIdentName=${cssModulesNames}$3`) 76 | }) 77 | config.module.loaders.push(newloader); 78 | cssloader.test = new RegExp(`[^module]${cssloader.test.source}`) 79 | cssloader.loader = 'style!css!postcss' 80 | 81 | cssloader.include = [src, examples]; 82 | 83 | config.module.loaders.push({ 84 | test: /\.css$/, 85 | include: [modules], 86 | loader: 'style!css' 87 | }); 88 | 89 | config.module.loaders.push({ 90 | test: /\.md$/, 91 | include: [join(root, 'README.md')], 92 | loader: 'markdown-with-front-matter' 93 | }) 94 | 95 | config.plugins = [ 96 | new webpack.DefinePlugin(defines) 97 | ].concat(config.plugins); 98 | 99 | config.postcss = [].concat([ 100 | require('precss')({}), 101 | require('autoprefixer')({}), 102 | require('cssnano')({}) 103 | ]) 104 | 105 | module.exports = config; 106 | -------------------------------------------------------------------------------- /www/Container.js: -------------------------------------------------------------------------------- 1 | import React, {PropTypes as T} from 'react' 2 | import ReactDOM from 'react-dom' 3 | import {Link} from 'react-router' 4 | import GitHubForkRibbon from 'react-github-fork-ribbon' 5 | 6 | import styles from './styles.module.css' 7 | import Readme from './readme'; 8 | 9 | export const Container = React.createClass({ 10 | 11 | propTypes: { 12 | children: T.element, 13 | readme: T.object, 14 | highlight: T.func 15 | }, 16 | 17 | contextTypes: { 18 | router: T.object 19 | }, 20 | 21 | componentDidMount: function() { 22 | this.props.highlight(); 23 | }, 24 | 25 | render: function() { 26 | const {routeMap, routeDef} = this.props; 27 | const {router} = this.context; 28 | 29 | return ( 30 |
31 | 34 | Fork me on GitHub 35 | 36 |
37 |
38 |
39 |

Redux modules

40 |

Readme

41 |
42 | 43 |
44 |
45 |
46 | ) 47 | } 48 | }) 49 | 50 | export default Container; 51 | -------------------------------------------------------------------------------- /www/global.styles.css: -------------------------------------------------------------------------------- 1 | @import url("../node_modules/highlight.js/styles/tomorrow-night.css"); 2 | @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,300); 3 | 4 | #readme { 5 | font-family: 'Open Sans', sans-serif; 6 | font-size: 18px; 7 | padding: 10px; 8 | 9 | img { 10 | width: 100%; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /www/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom' 3 | import {Router, hashHistory, Redirect, Route, IndexRoute, Link} from 'react-router' 4 | 5 | import styles from './global.styles.css'; 6 | import Container from './Container' 7 | 8 | const highlight = () => { 9 | const hljs = require('highlight.js'); 10 | 11 | const codes = document.querySelectorAll('pre code'); 12 | for (var i = 0; i < codes.length; i++) { 13 | const block = codes[i] 14 | hljs.highlightBlock(block); 15 | } 16 | return hljs; 17 | } 18 | 19 | const mountNode = document.querySelector('#root') 20 | const main = 21 | ReactDOM.render(main, mountNode); 22 | -------------------------------------------------------------------------------- /www/readme.js: -------------------------------------------------------------------------------- 1 | import React, {Component, PropTypes as T} from 'react' 2 | import ReactDOM, {render} from 'react-dom'; 3 | 4 | import styles from './styles.module.css'; 5 | 6 | const readme = require("../README.md") 7 | 8 | import Inspector from 'react-inspector'; 9 | import { createConstants } from '../src/index'; 10 | 11 | const Demo = (props) => ( 12 |
13 |

{props.name || 'Demo'}

14 | {props.children} 15 |
16 | ) 17 | 18 | // Examples 19 | class CreateConstantsExample extends Component { 20 | render() { 21 | const types = createConstants('TODO')({ 22 | 'CREATE': 'unimportant', 23 | 'FETCH_ALL': { api: true } 24 | }); 25 | const str = `createConstants('TODO')({ 26 | 'CREATE': true, // value is ignored 27 | 'FETCH_ALL': { api: true } 28 | }); ` 29 | return ( 30 | 31 |
 {str} 
32 | 33 |
34 | ) 35 | } 36 | } 37 | 38 | export class Readme extends React.Component { 39 | componentDidMount() { 40 | this.props.highlight(); 41 | this.mountExamples(); 42 | } 43 | 44 | componentDidUpdate() { 45 | this.props.highlight(); 46 | this.mountExamples(); 47 | } 48 | 49 | mountExamples() { 50 | const constantExampleNode = document.querySelector('#constantExample') 51 | render(, constantExampleNode); 52 | } 53 | 54 | render() { 55 | return ( 56 |
57 |
59 |
60 | ) 61 | } 62 | } 63 | 64 | export default Readme; 65 | -------------------------------------------------------------------------------- /www/styles.module.css: -------------------------------------------------------------------------------- 1 | $dominantColor: #1BCAFF; 2 | $listColor: #333; 3 | $textColor: #333; 4 | 5 | @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,300); 6 | 7 | html, body { 8 | height: 100%; 9 | margin: 0; 10 | padding: 0; 11 | } 12 | .container { 13 | font-family: 'Open Sans', sans-serif; 14 | font-weight: lighter; 15 | } 16 | .header { 17 | font-size: 0.5em; 18 | background: color($dominantColor a(80%)); 19 | padding: 10px; 20 | margin: 0; 21 | color: $textColor; 22 | text-align: center; 23 | border-bottom: 2px solid color($dominantColor blackness(40%)); 24 | } 25 | .wrapper { 26 | .content { 27 | position: relative; 28 | min-height: 100%; 29 | } 30 | 31 | .demo { 32 | border: 1px solid #efefef; 33 | padding: 10px; 34 | } 35 | 36 | .container { 37 | padding: 15px; 38 | margin: 10px 0; 39 | } 40 | } 41 | --------------------------------------------------------------------------------