Switch to Koa, more es6

This commit is contained in:
Jonathan Cremin 2015-06-03 21:45:54 -07:00
parent 1090affc9c
commit b3abff99ae
36 changed files with 25573 additions and 928 deletions

189
app.js
View file

@ -1,127 +1,102 @@
"use strict";
var express = require("express");
var helmet = require("helmet");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var session = require("express-session");
var cookieParser = require("cookie-parser");
var flash = require("connect-flash");
var compress = require("compression");
var bodyParser = require("body-parser");
var pmongo = require("promised-mongo");
import path from 'path';
import koa from 'koa';
import route from 'koa-route';
import logger from 'koa-logger';
import favicon from 'koa-favicon';
import compress from 'koa-compress';
import staticHandler from 'koa-static';
import bodyparser from 'koa-bodyparser';
import React from 'react';
import co from 'co';
import db from './config/db';
import index from './routes/index';
import search from './routes/search';
import share from './routes/share';
import itunesProxy from './routes/itunes-proxy';
import {routes} from './views/app.jsx';
import zlib from 'zlib';
import createHandler from './lib/react-handler';
var index = require("./routes/index");
var search = require("./routes/search");
var share = require("./routes/share");
var itunesProxy = require("./routes/itunes-proxy");
import debuglog from 'debug';
const debug = debuglog('match.audio');
var React = require("react");
require("node-jsx").install({extension: ".jsx"});
const app = koa();
var ErrorView = React.createFactory(require("./views/error.jsx"));
app.use(function* (next) {
this.set('Server', 'Nintendo 64');
try {
yield next;
} catch (err) {
if (!err.status) {
console.error(err.stack);
} else if (err.status === 404) {
let Handler = yield createHandler(routes, this.request.url);
var browserify = require("connect-browserify");
let App = React.createFactory(Handler);
let content = React.renderToString(new App());
var app = express();
var development = process.env.NODE_ENV !== "production";
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(compress());
app.use(favicon(path.join(__dirname, "/public/images/favicon.png")));
app.use(helmet());
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: "keyboard catz",
resave: false,
saveUninitialized: true
}));
app.use(flash());
app.use(express.static(path.join(__dirname, "public")));
var dbUrl = process.env.MONGOHQ_URL || "mongodb://localhost/match-audio";
app.use(function(req, res, next) {
req.db = res.db = pmongo(dbUrl, ["matches"]);
next();
this.body = '<!doctype html>\n' + content;
} else {
throw err;
}
}
});
if (development) {
app.get("/javascript/bundle.js",
browserify("./views/app.jsx", {
debug: true,
watch: true
}));
}
app.use(bodyparser());
app.use(compress({flush: zlib.Z_SYNC_FLUSH }));
app.use(favicon(path.join(__dirname, '/public/images/favicon.png')));
app.use(logger());
app.use(staticHandler(path.join(__dirname, 'public')));
app.get("*", function(req, res, next) {
let mongo = {};
co(function*() {
mongo = yield db();
});
app.use(function* (next){
this.db = mongo;
yield next;
});
app.use(function* (next) {
// force SSL
if (req.headers["cf-visitor"] && req.headers["cf-visitor"] !== "{\"scheme\":\"https\"}") {
return res.redirect("https://" + req.headers.host + req.url);
} else if (req.headers["cf-visitor"]) {
req.userProtocol = "https";
if (this.headers['cf-visitor'] && this.headers['cf-visitor'] !== '{"scheme":"https"}') {
return this.redirect('https://' + this.headers.host + this.url);
} else if (this.headers['cf-visitor']) {
this.userProtocol = 'https';
} else {
req.userProtocol = "http";
this.userProtocol = 'http';
}
// redirect www
if (req.headers.host.match(/^www/) !== null ) {
return res.redirect(req.userProtocol + "://" + req.headers.host.replace(/^www\./, "") + req.url);
if (this.headers.host.match(/^www/) !== null ) {
return this.redirect(this.userProtocol + '://' + this.headers.host.replace(/^www\./, '') + this.url);
} else {
next();
yield next;
}
});
app.get("/", index);
app.post("/search", search);
app.get("/:service/:type/:id.:format?", share);
app.get("/itunes/*", itunesProxy);
app.get("/recent", function(req, res, next) {
req.db.matches.find().sort({"created_at": -1}).limit(6).toArray().then(function(docs){
var recents = [];
docs.forEach(function(doc) {
recents.push(doc.services[doc._id.split("$$")[0]]); // eslint-disable-line no-underscore-dangle
});
res.json({recents: recents});
}).catch(function (error) {
return next(error);
app.use(route.get('/', index));
app.use(route.post('/search', search));
app.use(route.get('/itunes/(.*)', itunesProxy));
app.use(route.get('/:service/:type/:id.:format?', share));
app.use(route.get('/recent', function* () {
let recents = [];
let docs = yield this.db.matches.find().sort({'created_at': -1}).limit(6).toArray();
docs.forEach(function(doc) {
recents.push(doc.services[doc._id.split('$$')[0]]); // eslint-disable-line no-underscore-dangle
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get("env") === "development") {
app.use(function(err, req, res) {
console.log(err.stack);
res.status(err.status || 500);
var content = React.renderToString(new ErrorView({status: err.status || 500, message: err.message, error: err}));
res.send("<!doctype html>\n" + content);
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res) {
res.status(err.status || 500);
var content = React.renderToString(new ErrorView({status: err.status || 500, message: err.message, error: {status: err.status || 500}}));
res.send("<!doctype html>\n" + content);
});
this.body = {recents: recents};
}));
app.use(route.get('*', function* () {
this.throw(404);
}));
module.exports = app;
if (!module.parent) {
app.listen(process.env.PORT || 3000, function() {
debug('Koa server listening on port ' + (process.env.PORT || 3000));
});
}