bitcore-node-zcash/config/express.js

87 lines
2.1 KiB
JavaScript
Raw Normal View History

2014-01-06 08:33:58 -08:00
'use strict';
/**
* Module dependencies.
*/
var express = require('express'),
2014-02-26 07:05:30 -08:00
config = require('./config'),
2014-02-26 06:50:09 -08:00
path = require('path');
2014-01-06 08:33:58 -08:00
module.exports = function(app, historicSync, peerSync) {
2014-01-19 05:09:59 -08:00
2014-02-26 06:50:09 -08:00
//custom middleware
var setHistoric = function(req, res, next) {
2014-01-31 09:20:56 -08:00
req.historicSync = historicSync;
next();
2014-02-26 06:50:09 -08:00
};
var setPeer = function(req, res, next) {
req.peerSync = peerSync;
next();
2014-02-26 06:50:09 -08:00
};
2014-01-06 08:33:58 -08:00
2014-01-31 09:20:56 -08:00
app.set('showStackError', true);
2014-01-06 08:33:58 -08:00
2014-02-05 10:59:44 -08:00
// Compress JSON outputs
app.set('json spaces', 0);
2014-01-06 09:37:32 -08:00
//Enable jsonp
2014-01-19 05:09:59 -08:00
app.enable('jsonp callback');
app.use(config.apiPrefix + '/sync', setHistoric);
app.use(config.apiPrefix + '/peer', setPeer);
2014-01-31 09:20:56 -08:00
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.compress());
2014-01-06 08:33:58 -08:00
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
});
2014-02-26 11:27:22 -08:00
if (config.publicPath) {
var staticPath = path.normalize(config.rootPath + '/../' + config.publicPath);
2014-02-26 06:50:09 -08:00
//IMPORTANT: for html5mode, this line must to be before app.router
2014-02-26 07:05:30 -08:00
app.use(express.static(staticPath));
2014-02-26 06:50:09 -08:00
}
// manual helpers
app.use(function(req, res, next) {
app.locals.config = config;
next();
});
2014-01-31 09:20:56 -08:00
//routes should be at the last
app.use(app.router);
2014-01-31 09:20:56 -08:00
//Assume "not found" in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
app.use(function(err, req, res, next) {
//Treat as 404
if (~err.message.indexOf('not found')) return next();
2014-01-06 08:33:58 -08:00
2014-01-31 09:20:56 -08:00
//Log it
console.error(err.stack);
2014-01-06 08:33:58 -08:00
2014-01-31 09:20:56 -08:00
//Error page
res.status(500).jsonp({
status: 500,
2014-01-31 09:20:56 -08:00
error: err.stack
2014-01-06 09:37:32 -08:00
});
2014-01-31 09:20:56 -08:00
});
2014-01-06 08:33:58 -08:00
2014-01-31 09:20:56 -08:00
//Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).jsonp({
status: 404,
2014-01-31 09:20:56 -08:00
url: req.originalUrl,
error: 'Not found'
2014-01-06 08:33:58 -08:00
});
2014-01-06 09:37:32 -08:00
});
};