app = express(),
mysql = require(‘mysql‘);
app.listen(3000);
console.log(‘Rest Demo Listening on port 3000‘);
DB Connection
Setup your database and create a pool of connections to MySQL server;
- var express = require(‘express‘),
- app = express(),
- mysql = require(‘mysql‘),
- connectionpool = mysql.createPool({
- host : ‘localhost‘,
- user : ‘root‘,
- password : ‘secret‘,
- database : ‘rest_demo‘
- });
- app.listen(3000);
- console.log(‘Rest Demo Listening on port 3000‘);
Where the configuration uses your host, username, password, and database name of course.
Routes
Your application will only need five REST routes to cover the methods table above.
- var express = require(‘express‘),
- app = express(),
- mysql = require(‘mysql‘),
- connectionpool = mysql.createPool({
- host : ‘localhost‘,
- user : ‘root‘,
- password : ‘secret‘,
- database : ‘rest_demo‘
- }),
- res.setHeader({ ‘Content-Type‘: ‘application/json‘ });
- app.get(‘/:table‘, function(req,res){});
- app.get(‘/:table/:id‘, function(req,res){});
- app.post(‘/:table‘, function(req,res){});
- app.put(‘/:table/:id‘, function(req,res){});
- app.delete(‘/:table/:id‘, function(req,res){});
-
- app.listen(3000);
- console.log(‘Rest Demo Listening on port 3000‘);
Each route takes a callback function with request and response objects.
You may also notice we are going to be sending json Content-Type as a response always. I will set it up so that even errors will be responding in json, this is personal preference and you might want to do something else but i see it with AWS, Google, Facebook, ect so figured its generally a good idea.
Connection and Error Handling
We will be getting a connection from our pool, which may have reached its allocated limit and throw an error which needs to be handled.
- var express = require(‘express‘),
- app = express(),
- mysql = require(‘mysql‘),
- connectionpool = mysql.createPool({
- host : ‘localhost‘,
- user : ‘root‘,
- password : ‘secret‘,
- database : ‘rest_demo‘
- });
- res.setHeader({ ‘Content-Type‘: ‘application/json‘ });
- app.get(‘/:table‘, function(req,res){
- connectionpool.getConnection(function(err, connection) {
- if (err) {
- console.error(‘CONNECTION error: ‘,err);
- res.statusCode = 503;
- res.send({
- result: ‘error‘,
- err: err.code
- });
- } else {
- // query the database using connection
- }
- });
- });
When we encounter connection errors node.js will log them to the console and our app will respond with http status code 503 Service Unavailable with a mysql server error code.
Querying MySQL
Our routes will define a table name and if required an id, which we will use to build our query and return some json data.
Take a look at fetching the latest 20 rows;
- var express = require(‘express‘),
- app = express(),
- mysql = require(‘mysql‘),
- connectionpool = mysql.createPool({
- host : ‘localhost‘,
- user : ‘root‘,
- password : ‘secret‘,
- database : ‘rest_demo‘
- });
- app.get(‘/:table‘, function(req,res){
- connectionpool.getConnection(function(err, connection) {
- if (err) {
- console.error(‘CONNECTION error: ‘,err);
- res.statusCode = 503;
- res.send({
- result: ‘error‘,
- err: err.code
- });
- } else {
- connection.query(‘SELECT * FROM ‘+req.params.table+‘ ORDER BY id DESC LIMIT 20‘, req.params.id, function(err, rows, fields) {
- if (err) {
- console.error(err);
- res.statusCode = 500;
- res.send({
- result: ‘error‘,
- err: err.code
- });
- }
- res.send({
- result: ‘success‘,
- err: ‘‘,
- fields: fields,
- json: rows,
- length: rows.length
- });
- connection.release();
- });
- }
- });
- });
- app.get(‘/:table/:id‘, function(req,res){});
- app.post(‘/:table‘, function(req,res){});
- app.put(‘/:table/:id‘, function(req,res){});
- app.delete(‘/:table/:id‘, function(req,res){});
- app.listen(3000);
- console.log(‘Rest Demo Listening on port 3000‘);
Other than the error handling (which returns a http code 500) we have responded to the requester with up to 20 rows of data.
They also get the field names and how many rows were returned.
Putting It All Together
Using the above technique we put together our server.js
like so, which comes in at 175 lines in total.
Source GitHub
Note:
Do not use this in production, it is simply a demo.
The main issue is with the varible table name part in the routing, this is a BADidea.
The first thing I would change is encapsulion of each database table in its own js file under a routes
directory, then require the needed js file for each request.
I hope you have enjoyed this demo - please leave your feedback below.
NodeJS REST API with MySQL and Express
标签: