burnchart/proxy.coffee

46 lines
1.3 KiB
CoffeeScript
Raw Normal View History

2013-08-17 12:54:48 +00:00
#!/usr/bin/env coffee
{ _ } = require 'lodash'
http = require 'http'
fs = require 'fs'
connect = require 'connect'
request = require 'request'
# Read the original config.
config = JSON.parse fs.readFileSync './config.json', 'utf-8'
2013-09-29 22:14:30 +00:00
# Some defaults.
config.host ?= 'api.github.com'
2013-08-17 12:54:48 +00:00
# This is the scrubbed version.
2013-09-29 21:14:24 +00:00
_.extend scrubbed = {}, config, { 'protocol': 'http', 'token': null }
2013-08-17 12:54:48 +00:00
proxy = (req, res, next) ->
write = (code, body) ->
res.writeHead code, {'Content-Type': 'application/json; charset=utf-8'}
res.end body
# Config?
if req.url is '/config.json'
# Refer to us like so.
scrubbed.host = req.headers.host
return write 200, JSON.stringify scrubbed, null, 4
# API request?
if req.url.match /^\/repos/
# The new headers.
2013-09-29 22:14:30 +00:00
headers = 'Accept': 'application/vnd.github.raw'
2013-08-17 12:54:48 +00:00
# Add a token?
headers.Authorization = 'token ' + config.token if config.token
2013-09-29 22:14:30 +00:00
# Make the HTTPS request.
2013-08-17 12:54:48 +00:00
return request {
2013-09-29 22:14:30 +00:00
'uri': 'https://' + config.host + req.url
2013-08-17 12:54:48 +00:00
headers
}, (_err, _res, body) ->
2013-09-29 22:14:30 +00:00
return write(500) if _err
2013-08-17 12:54:48 +00:00
write _res.statusCode, body
# Get handled by Connect.
next()
app = connect()
.use(proxy)
.use(connect.static(__dirname + '/public'))
.listen process.env.PORT