Skip to content

Instantly share code, notes, and snippets.

@cflynn07
Last active December 15, 2015 16:59
Show Gist options
  • Save cflynn07/5293090 to your computer and use it in GitHub Desktop.
Save cflynn07/5293090 to your computer and use it in GitHub Desktop.
Configuring main file in express.io app to share routes between socket.io and HTTP requests for an API that's accessible via websockets and HTTP
fs = require 'fs'
express = require 'express.io'
path = require 'path'
#If we didn't get to server.js from bootstrap.js
if !GLOBAL.asset_hash?
GLOBAL.asset_hash = 'main'
#Read dotCloud ENV file if exists
try
GLOBAL.env = JSON.parse(fs.readFileSync('/home/dotcloud/environment.json', 'utf-8'))
catch error
GLOBAL.env = false
GLOBAL.apiSubDir = '/api'
#redis clients
pub = require('./config/redis').createClient()
sub = require('./config/redis').createClient()
store = require('./config/redis').createClient()
redisStore = require('./config/redis').createStore()
app = express().http().io()
GLOBAL.app = app
app.io.set 'store',
new express.io.RedisStore
redis: require 'redis'
redisPub: pub
redisSub: sub
redisClient: store
#app.io.enable('browser client etag')
app.io.set('log level', 3)
app.io.set('transports', [
# 'websocket'
# 'flashsocket'
'htmlfile'
'xhr-polling'
'jsonp-polling'
])
app.configure () ->
#TODO store sessions in redis-store rather than memory
app.use express.compress()
app.disable 'x-powered-by'
app.set 'port', process.env.PORT || 8080
app.set 'views', __dirname + '/views'
app.set 'view engine', 'ejs'
#TODO
#app.use express.favicon()
app.use express.logger 'dev'
app.use express.bodyParser()
app.use express.methodOverride()
app.use express.cookieParser()
app.use express.session
secret: '###'
store: redisStore
#Standard Requests
app.use (req, res, next) ->
res.jsonAPIRespond = (json) ->
res.json json
app.router(req, res, next)
#API Requests
app.io.route 'apiRequest', (req) ->
httpEmulatedRequest =
method: if req.data.method then req.data.method else 'get'
url: if req.data.url then req.data.url else '/api/'
headers: []
response =
jsonAPIRespond: (json) ->
req.io.respond json
app.router httpEmulatedRequest, response, () ->
app.configure 'production', () ->
maxAge = 31536000000
app.use express.static path.join(__dirname, '../client'), { maxAge: maxAge }
app.configure 'development', () ->
maxAge = 0 #Disable caching in development
app.use express.static path.join(__dirname, '../client'), { maxAge: maxAge }
app.use express.errorHandler()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment