Commit 8d56fe7c by Jun Matsushita

Middleware works

parent eee49550
......@@ -30,6 +30,8 @@
"babel-polyfill": "^6.8.0",
"babel-runtime": "^6.5.0",
"isomorphic-fetch": "^2.2.1",
"pouch-redux-middleware": "^0.2.0",
"pouchdb": "^5.4.4",
"ramda": "^0.21.0",
"react": "^15.0.2",
"react-dom": "^15.0.2",
......
import * as types from './_action_types'
import React from 'react';
import { render } from 'react-dom';
import { createStore, compose } from 'redux';
import PouchMiddleware from 'pouch-redux-middleware'
import PouchDB from 'pouchdb'
import { createStore, compose, applyMiddleware, combineReducers } from 'redux';
import { Provider, connect } from 'react-redux';
import reduxElm from 'redux-elm';
export default (containerDomId, View, updater) => {
const storeFactory = compose(
reduxElm,
window.devToolsExtension ? window.devToolsExtension() : f => f
)(createStore);
const store = storeFactory(updater);
const db = new PouchDB('app');
const remoteDB = new PouchDB('https://oi:oi@staging-store.openintegrity.org/claims', {skip_setup: true})
const pouchMiddleware = PouchMiddleware({
path: '/app/claims',
db,
actions: {
// remove: doc => store.dispatch({type: 'REMOVE_CLAIM', id: doc._id}),
insert: doc => store.dispatch({type: 'INSERT_CLAIM', claim: doc}),
// update: doc => store.dispatch({type: 'UPDATE_CLAIM', claim: doc}),
remove: doc => console.log("removed", doc),
// insert: doc => console.log(doc),
update: doc => console.log("updated", doc),
}
})
db.sync(remoteDB, {
live: true,
retry: true
}).on('change', function (change) {
console.log(change)
console.log("yo, something changed!");
}).on('paused', function (info) {
console.log("replication was paused, usually because of a lost connection");
}).on('active', function (info) {
console.log(info)
console.log("replication was resumed");
}).on('error', function (err) {
console.log(err)
console.log("totally unhandled error (shouldn't happen)")
});
/**
* Logs all actions and states after they are dispatched.
*/
const logger = store => next => action => {
console.group(action.type)
console.info('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
console.groupEnd(action.type)
return result
}
/**
* Sends crash reports as state is updated and listeners are notified.
*/
const crashReporter = store => next => action => {
try {
return next(action)
} catch (err) {
console.error('Caught an exception!', err)
Raven.captureException(err, {
extra: {
action,
state: store.getState()
}
})
throw err
}
}
const store = createStore(
updater,
compose(
reduxElm,
applyMiddleware(
pouchMiddleware,
logger,
crashReporter
),
// applyMiddleware(createLogger()),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
// const storeFactory = compose(
// reduxElm,
// window.devToolsExtension ? window.devToolsExtension() : f => f
// )(createStore);
//
// const store = storeFactory(updater);
const ConnectedView = connect(appState => ({
model: appState
......@@ -21,4 +105,20 @@ export default (containerDomId, View, updater) => {
<ConnectedView />
</Provider>
), document.getElementById(containerDomId));
// console.log(db)
// db.allDocs()
// .then(docs => console.log(docs))
//
// const remoteDB = new PouchDB('https://oi:oi@staging-store.openintegrity.org/app', {skip_setup: true})
//
// db.sync(remoteDB).on('complete', function () {
// console.log("yay, we're in sync!");
// }).on('error', function (err) {
// console.log(err)
// console.log("boo, we hit an error!");
// });
//
}
tr.attr(key=index)
th(scope='row') 1
td= doc.category
td= doc.project
if (doc.evidence)
td= doc.evidence.url
else
......
......@@ -3,7 +3,8 @@ table.table.table-hover
tr
th #
th Category
th Last Name
th Username
th Project
th Url
th Author
tbody
= rows
......@@ -2,9 +2,9 @@ import PouchDB from 'pouchdb'
require('isomorphic-fetch');
const uuid = new PouchDB('https://oi:oi@staging-store.openintegrity.org/_uuids', {skip_setup: true})
const claims = new PouchDB('https://oi:oi@staging-store.openintegrity.org/claims', {skip_setup: true})
// const uuid = new PouchDB('https://oi:oi@staging-store.openintegrity.org/_uuids', {skip_setup: true})
//
// const claims = new PouchDB('https://oi:oi@staging-store.openintegrity.org/claims', {skip_setup: true})
export const fetchSchema = measurement =>
fetch(
......@@ -24,25 +24,25 @@ export const fetchSchema = measurement =>
})
.then(json => JSON.parse(new Buffer(json.content, 'base64').toString('binary')));
export const fetchClaims = () =>
claims
.allDocs({include_docs: true})
.then(function(results) {
console.log('you have fetched claims');
console.log(results);
return results;
}).catch(function(err) {
console.log(err.message);
});
// export const fetchClaims = () =>
// claims
// .allDocs({include_docs: true})
// .then(function(results) {
// console.log('you have fetched claims');
// console.log(results.rows.map((r) => r.doc ));
// return results.rows.map( (r) => r.doc );
// }).catch(function(err) {
// console.log(err.message);
// });
export const submitClaim = claim =>
uuid.get('')
.then((id) => claims.put({...claim, _id: id.uuids[0] }))
.then((response) => {
console.log('you have inserted the claim');
console.log(response);
})
.catch(function(err) {
throw(err);
});
// export const submitClaim = claim =>
// uuid.get('')
// .then((id) => claims.put({...claim, _id: id.uuids[0] }))
// .then((response) => {
// console.log('you have inserted the claim');
// console.log(response);
// })
// .catch(function(err) {
// throw(err);
// });
......@@ -11,39 +11,38 @@ const getMeasurement = model => model.measurement;
function* fetchSchema() {
const measurement = yield select(getMeasurement);
const schema = yield call(Effects.fetchSchema, measurement);
yield put({ type: 'NewSchema', schema });
yield put({ type: 'SCHEMA_FETCHED', schema });
}
function* action(req) {
switch (req.type) {
case 'SubmitClaim':
yield call(Effects.submitClaim, req.payload);
default:
const claims = yield call(Effects.fetchClaims);
yield put({ type: 'NewClaims', claims });
}
}
function* fetchClaims() {
const claims = yield call(Effects.fetchClaims);
yield put({ type: 'NewClaims', claims });
}
function* submitClaim() {
yield call(Effects.submitClaim, claim);
const claims = yield call(Effects.fetchClaims);
yield put({ type: 'NewClaims', claims });
}
// function* action(req) {
// switch (req.type) {
// case 'INSERT_CLAIM':
// // yield call(Effects.submitClaim, req.payload);
// default:
// const claims = yield call(Effects.fetchClaims);
// yield put({ type: 'CLAIMS_FETCHED', claims });
//
// }
// }
//
// function* fetchClaims() {
// const claims = yield call(Effects.fetchClaims);
// yield put({ type: 'CLAIMS_FETCHED', claims });
// }
//
// function* submitClaim() {
// yield call(Effects.submitClaim, claim);
// const claims = yield call(Effects.fetchClaims);
// yield put({ type: 'CLAIMS_FETCHED', claims });
// }
function* saga() {
yield* fetchSchema();
yield* fetchClaims();
yield* takeEvery(['SubmitClaim', 'Request'], action);
// yield* fetchClaims();
// yield* takeEvery(['INSERT_CLAIM', 'FETCH_CLAIMS'], action);
}
export const request = () => ({ type: 'Request' });
// export const request = () => ({ type: 'Request' });
type claimsModel = {
measurement: string,
......@@ -51,16 +50,16 @@ type claimsModel = {
claims: Array<any>
};
export const init = measurement => ({
measurement,
export const init = (measurement) => ({
measurement: measurement,
schema: null,
claims: null
claims: []
});
const updater : Updater<claimsModel> = new Updater(init('pseudonymity'), saga)
.case('NewSchema', (model, { schema }) => ({ ...model, schema: schema }))
.case('NewClaims', (model, { claims }) => ({ ...model, claims: claims }))
.case('SubmitClaim', model => model)
.case('Request', model => ({ ...model, claims: null }));
const updater : Updater<claimsModel> = new Updater(model = init('pseudonymity'), saga)
.case('SCHEMA_FETCHED', (model, { schema }) => ({ ...model, schema: schema }))
.case('INSERT_CLAIM', (model, { claim }) => ({ ...model, claims: [ claim, ...model.claims ] }))
// .case('CLAIMS_FETCHED', (model, { claims }) => ({ ...model, claims: claims }))
// .case('FETCH_CLAIMS', model => ({ ...model, claims: claims }));
export default updater.toReducer();
......@@ -14,10 +14,10 @@ const renderSchema = (schema, dispatch) => {
return <Form schema={schema}
formData={formData}
liveValidate={true}
onChange={log("changed")}
/*onChange={log("changed")}*/
onSubmit={
// log("submitted")
({formData}) => dispatch({ type: 'SubmitClaim' , payload: formData })
({formData}) => dispatch({ type: 'INSERT_CLAIM' , claim: ({...formData, _id: 'measurement/' + formData.category + '/user/jun/date/' + new Date().toJSON()}) })
}
onError={log("errors")} />
} else {
......@@ -33,8 +33,8 @@ export default view(({ model, dispatch }) => (
<h2 style={{ textAlign: 'center' }}>{model.measurement}</h2>
</div>
<div className="col-md-8">
{claims_table({rows: model.claims && model.claims.rows.map((claim, index) => claims_row({ doc: claim.doc, index: index } ))})}
<button onClick={() => dispatch({ type: 'Request' })} className="btn btn-info">Get Claims!</button>
{claims_table({rows: model.claims.map((claim, index) => claims_row({ doc: claim, index: index } ))})}
<button onClick={() => dispatch({ type: 'FETCH_CLAIMS' })} className="btn btn-info">Get Claims!</button>
</div>
<div className="col-md-4">
{renderSchema(model.schema, dispatch)}
......
......@@ -5,10 +5,10 @@ import claimsUpdater, { init as claimsInitialModel } from './claims/updater';
export const initialModel = {
hello: helloInitialModel,
claims: claimsInitialModel('pseudonymity')
app: claimsInitialModel('pseudonymity')
};
export default new Updater(initialModel)
.case('Hello', (model, ...rest) => ({ ...model, hello: helloUpdater(model.hello, ...rest) }))
.case('Claims', (model, ...rest) => ({ ...model, claims: claimsUpdater(model.claims, ...rest) }))
.case('App', (model, ...rest) => ({ ...model, app: claimsUpdater(model.app, ...rest) }))
.toReducer();
......@@ -2,11 +2,11 @@ import React from 'react';
import { view, forwardTo } from 'redux-elm';
import Hello from './hello-world/view';
import Claims from './claims/view';
import App from './claims/view';
export default view(({ model, dispatch }) => (
<div>
<Claims model={model.claims} dispatch={forwardTo(dispatch, 'Claims')} />
<App model={model.app} dispatch={forwardTo(dispatch, 'App')} />
</div>
));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment