Created
December 12, 2011 18:38
-
-
Save mbostock/1468492 to your computer and use it in GitHub Desktop.
Node + MySQL + JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
process.env.TZ = "UTC"; | |
var util = require("util"), | |
express = require("express"), | |
gzip = require("connect-gzip"), | |
mysql = require("mysql"); | |
var client = mysql.createClient({ | |
host: /* mysql host, e.g., "host.example.com" */, | |
port: /* mysql port, e.g., 3306 */, | |
user: /* mysql user, e.g., "username" */, | |
password: /* mysql password, e.g., "password" */, | |
database: /* mysql database, e.g., "database" */ | |
}); | |
var server = express.createServer(); | |
server.use(gzip.gzip()); | |
server.use(express.static(__dirname + "/public")); | |
server.get("/things/:id([0-9]+).json", function(request, response, next) { | |
client.query("SELECT" | |
+ " t.name," | |
+ " t.favorite_color," | |
+ " t.airspeed_velocity" | |
+ " FROM things t" | |
+ " WHERE t.id = ?", [request.params.id], function(error, rows) { | |
if (error) return next(error); | |
response.json(rows); | |
}); | |
}); | |
server.listen(/* http port, e.g., 8888 */, /* http host, e.g., "0.0.0.0" */); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yea.. I would normally do it SQL side, but in this particular circumstance performance favors transformations in the middleware and not in DB. Ill give it a go. Thx!