Skip to content

Commit

Permalink
Initial code
Browse files Browse the repository at this point in the history
  • Loading branch information
ForbesLindesay committed Sep 12, 2015
0 parents commit ff16d57
Show file tree
Hide file tree
Showing 10 changed files with 552 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"optional": ["es7.objectRestSpread"]
}
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pids
logs
npm-debug.log
node_modules
/lib
5 changes: 5 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pids
logs
npm-debug.log
node_modules
/src
3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
language: node_js
node_js:
- "0.12"
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2015 Forbes Lindesay

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
156 changes: 156 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# redux-optimist

Optimistically apply actions that can be later commited or reverted.

[![Build Status](https://img.shields.io/travis/ForbesLindesay/redux-optimist/master.svg)](https://travis-ci.org/ForbesLindesay/redux-optimist)
[![Dependency Status](https://img.shields.io/gemnasium/ForbesLindesay/redux-optimist.svg)](https://gemnasium.com/ForbesLindesay/redux-optimist)
[![NPM version](https://img.shields.io/npm/v/redux-optimist.svg)](https://www.npmjs.org/package/redux-optimist)

## Installation

npm install redux-optimist

## Usage

### Step 1: Wrap your top level reducer in redux-optimist

#### `reducers/todos.js`

```js
export default function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text]);
default:
return state;
}
}
```

#### `reducers/status.js`

```js
export default function status(state = {writing: false, error: null}, action) {
switch (action.type) {
case 'ADD_TODO':
return {writing: true, error: null};
case 'ADD_TODO_COMPLETE':
return {writing: false, error: null};
case 'ADD_TODO_FAILED':
return {writing: false, error: action.error};
default:
return state;
}
}
```

#### `reducers/index.js`

```js
import optimist from 'redux-optimist';
import { combineReducers } from 'redux';
import todos from './todos';
import status from './status';

export default optimist(combineReducers({
todos,
status
}));
```

As long as your top-level reducer returns a plain object, you can use optimist. You don't
have to use `Redux.combineReducers`.

### Step 2: Mark your optimistic actions with the `optimist` key

#### `middleware/api.js`

```js
import {BEGIN, COMMIT, REVERT} from 'optimist';
import request from 'then-request';

let nextTransactionID = 0;
export default function (store) {
return next => action => {
if (action.type !== 'ADD_TODO') {
return next(action);
}
let transactionID = nextTransactionID++;
next({
type: 'ADD_TODO',
text: action.text,
optimist: {type: BEGIN, id: transactionID}
});
request('POST', '/add_todo', {text: action.text}).getBody().done(
res => next({
type: 'ADD_TODO_COMPLETE',
text: action.text,
response: res,
optimist: {type: COMMIT, id: transactionID}
}),
err => next({
type: 'ADD_TODO_FAILED',
text: action.text,
error: err,
optimist: {type: REVERT, id: transactionID}
})
);
}
};
```

Note how we always follow up by either COMMITing the transaction or REVERTing it. If you do neither, you will get a memory leak. Also note that we use a serialisable transactionID such as a number. These should always
be unique accross the entire system.

### Step 3:

Using this, we can safely fire off `ADD_TODO` actions in the knowledge that the UI will update optimisticly, but will revert if the write to the server fails.

`App.js`

```js
import { createStore, applyMiddleware } from 'redux';
import api from './middleware/api';
import reducer from './reducers';

let store = applyMiddleware(api)(createStore)(reducer);
console.log(store.getState());
// {
// optimist: {...},
// todos: [],
// status: {writing: false, error: null}
// }

store.dispatch({
type: 'ADD_TODO',
text: 'Use Redux'
});
console.log(store.getState());
// {
// optimist: {...},
// todos: ['Use Redux'],
// status: {writing: true, error: null}
// }

// You can apply other actions here and their updates won't get lost
// even if the original ADD_TODO action gets reverted.

// Some time later...
console.log(store.getState());
// either
// {
// optimist: {...},
// todos: ['Use Redux'],
// status: {writing: false, error: null}
// }
// or
// {
// optimist: {...},
// todos: [],
// status: {writing: false, error: Error}
// }
```

## License

MIT
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('./lib/index.js');
22 changes: 22 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "redux-optimist",
"version": "0.0.0",
"description": "Optimistically apply actions that can be later commited or reverted.",
"keywords": [],
"dependencies": {},
"devDependencies": {
"babel": "^5.8.23",
"testit": "^2.0.2"
},
"scripts": {
"prepublish": "npm run build",
"build": "babel src --out-dir lib",
"test": "babel-node test/index.js"
},
"repository": {
"type": "git",
"url": "https://github.com/ForbesLindesay/redux-optimist.git"
},
"author": "ForbesLindesay",
"license": "MIT"
}
94 changes: 94 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
'use strict';

var BEGIN = 'BEGIN';
var COMMIT = 'COMMIT';
var REVERT = 'REVERT';
var INITIAL_OPTIMIST = {};

module.exports = optimist;
module.exports.BEGIN = BEGIN;
module.exports.COMMIT = COMMIT;
module.exports.REVERT = REVERT;
function optimist(fn) {
return function (state, action) {
let {optimist = INITIAL_OPTIMIST, ...oldState} = (state || {});
let oldOptimist = optimist;
if (!state) oldState = undefined;
if (
action.optimist &&
(action.optimist.type === COMMIT || action.optimist.type === REVERT)
) {
let {[action.optimist.id]: transaction, ...transactions} = optimist;
if (!transaction) {
console.error(
'Cannot ' +
action.optimist.type +
' transaction with id "' +
action.optimist.id +
'" because it does not exist'
);
}
optimist = transactions;
if (transaction && action.optimist.type === REVERT) {
let {state, actions} = transaction;
actions.forEach(function (action) {
state = fn(state, action);
});
oldState = state;
}
}
if (Object.keys(optimist).length) {
let newOptimist = {};
Object.keys(optimist).forEach(function (key) {
newOptimist[key] = {state: optimist[key].state, actions: optimist[key].actions.concat([action])};
});
optimist = newOptimist;
}
if (action.optimist && action.optimist.type === BEGIN) {
if (action.optimist.id in optimist) {
console.error(
'Implicitly committing transaction with id "' +
action.optimist.id +
'" because it already exists, and you are starting' +
' it again.'
);
}
if (!state) {
console.error(
'You should never begin an optimistic transaction before initializing your store.' +
' You would have nothing to revert to!'
);
}
optimist = {
...optimist,
[action.optimist.id]: {state: oldState, actions: []}
};
}
let newState = fn(oldState, action);
if (!newState || typeof newState !== 'object' || Array.isArray(newState)) {
throw new TypeError(
'Error while handling "' +
action.type +
'": Optimist requires that state is always a plain object.'
);
}
if (oldOptimist !== optimist || !equal(newState, oldState)) return {optimist, ...newState};
else return state;
};
}

function equal(newState, oldState) {
if (newState === oldState) return true;
if (!(newState && oldState)) return false;
for (let key in newState) {
if (newState[key] !== oldState[key]) {
return false;
}
}
for (let key in oldState) {
if (newState[key] !== oldState[key]) {
return false;
}
}
return true;
}
Loading

0 comments on commit ff16d57

Please sign in to comment.