dubdiff/src/server/index.js

84 lines
2.4 KiB
JavaScript
Raw Permalink 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
// set use port 8080 for dev, 80 for production
const PORT = (process.env.NODE_ENV !== 'production' ? 8080 : 80)
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')))
2016-12-02 17:20:59 +01:00
// serve the comparison api at /api/compare
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
// this loading logic could be moved into ../common/actions because it is isomorphic
app.route('/:comparisonId')
.get((req, res) => {
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) {
2016-12-17 16:21:00 +01:00
return response.json()
} else {
response.text().then(() => {
const error = {message: `${response.status}: ${response.statusText}`}
2016-12-17 16:21:00 +01:00
initAndRenderError(error, store, req, res)
})
}
})
.then(({a, b}) => {
initAndRenderComparison({a, b}, store, req, res)
2016-12-17 16:21:00 +01:00
})
.catch(error => {
2016-12-17 16:21:00 +01:00
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 () {
console.log(`Server listening on port ${PORT}.`)
2016-12-02 17:20:59 +01:00
})
// creates the session store
function createSessionStore () {
// create the redux store
return Redux.createStore(
Redux.combineReducers(reducers)
)
}
2016-12-02 17:20:59 +01:00
function initAndRenderComparison ({a, b}, store, req, res) {
2016-12-17 16:21:00 +01:00
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
function initAndRenderError (error, store, req, res) {
2016-12-17 16:21:00 +01:00
store.dispatch({type: 'STATUS_SET', data: Status.EMPTY})
store.dispatch({type: 'STATUS_SET_ERROR', data: StatusError.LOAD_ERROR, error})
render(store, req, res)
}