Skip to content

Instantly share code, notes, and snippets.

@toinetoine
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toinetoine/a41923e3914e5e2f7e7d to your computer and use it in GitHub Desktop.
Save toinetoine/a41923e3914e5e2f7e7d to your computer and use it in GitHub Desktop.
App.js for reading data from Mysql. From 'Building a RESTful API' (post at http://www.antoinedahan.com/blog/BuildingRESTfulAPI/)
/* express initialization */
var express = require('express');
var app = express();
/* body-parser initialization (use the body-parser json package) */
var bodyParser = require('body-parser');
app.use(bodyParser.json());
/* Main Router */
var ourApiRouter = express.Router();
//Function that's called when /api/ is accessed
ourApiRouter.use(function (req, res, next) {
var requestFullPath = req.originalUrl;
if(requestFullPath != null) {
//Parse the lastname from the url
var lastName = requestFullPath.substring(requestFullPath.indexOf('api/') + 4);
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : 'password',
database : 'NFL',
}
);
connection.connect();
//Querey for selecting from Name column by lastname: lastName
var queryString = "select * from players WHERE Name REGEXP '^[A-z]+[ ]+" + lastName + "$'";
connection.query(queryString, function(err, rows, fields) {
if(rows != null) {
//If querey returned a row, then add its data in JSON to the response
if(rows.length == 1) {
res.json({ "name": rows[0].Name, "age": rows[0].Age, "height": rows[0].Height, "weight": rows[0].Weight, "position": rows[0].Position, "college": rows[0].College});
}
else {
res.json({"ERROR": "Querey of lastname " + lastName + " returned none or multiple results"});
}
}
});
connection.end();
}
});
//Registering the main router
app.use('/api/', ourApiRouter);
//Add our app the the module
module.exports = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment