dubdiff/src/server/index.js

90 lines
2.3 KiB
JavaScript
Raw Normal View History

import express from 'express'
import path from 'path'
import bodyParser from 'body-parser'
import * as Redux from 'redux'
2016-12-02 17:20:59 +01:00
import fetch from 'isomorphic-fetch'
import comparisonRouter from './comparison'
2016-12-02 17:20:59 +01:00
import * as reducers from '../common/reducers'
2016-12-17 16:21:00 +01:00
import {Status, StatusError} from '../common/constants'
2016-12-02 17:20:59 +01:00
import render from './render'
2016-12-02 17:20:59 +01:00
const PORT = 8080
const app = express()
2016-12-02 17:20:59 +01:00
//serve the dist static files at /dist
app.use('/dist', express.static(path.join(__dirname, '..', '..', 'dist')))
//serve the comparison api at /api/compare
2016-12-02 17:20:59 +01:00
app.use(bodyParser.json())
app.use('/api/compare', comparisonRouter);
//the following routes are for server-side rendering of the app
//we should render the comparison directly from the server
2016-12-17 16:21:00 +01:00
//this loading logic could be moved into ../common/actions because it is isomorphic
app.route('/:comparisonId')
.get((req, res) => {
2016-12-17 16:21:00 +01:00
const store = createSessionStore()
2016-12-17 16:21:00 +01:00
const endpointUri = `http://localhost:${PORT}/api/compare/${req.params.comparisonId}`
//fetch the comparison
2016-12-17 16:21:00 +01:00
fetch(endpointUri)
.then(response => {
if (response.ok)
return response.json()
else {
response.text().then( () => {
const error = {message:`${response.status}: ${response.statusText}`}
initAndRenderError(error, store, req, res)
})
}
})
.then( ({a,b}) => {
initAndRenderComparison({a,b}, store, req, res)
})
.catch( error => {
initAndRenderError(error, store, req, res)
})
})
app.route('/')
.get((req, res) => {
render(createSessionStore(), req, res)
})
2016-12-02 17:20:59 +01:00
app.listen(PORT, function () {
2016-12-02 17:20:59 +01:00
console.log('Server listening on port 8080.')
})
//creates the session store
function createSessionStore() {
//create the redux store
return Redux.createStore(
Redux.combineReducers(reducers)
)
}
2016-12-02 17:20:59 +01:00
2016-12-17 16:21:00 +01:00
function initAndRenderComparison({a,b}, store, req, res) {
store.dispatch({type: 'UPDATE_ORIGINAL_INPUT', data: a})
store.dispatch({type: 'UPDATE_FINAL_INPUT', data: b})
store.dispatch({type: 'STATUS_SET', data: Status.CLEAN})
render(store, req, res)
}
2016-12-02 17:20:59 +01:00
2016-12-17 16:21:00 +01:00
function initAndRenderError(error, store, req, res) {
store.dispatch({type: 'STATUS_SET', data: Status.EMPTY})
store.dispatch({type: 'STATUS_SET_ERROR', data: StatusError.LOAD_ERROR, error})
render(store, req, res)
}