Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mevdschee committed Jan 17, 2017
0 parents commit a893d7a
Show file tree
Hide file tree
Showing 4 changed files with 161 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.vscode
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Maurits van der Schee

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
127 changes: 127 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
var http = require("http");
var mysql = require("mysql");

// connect to the mysql database

var pool = mysql.createPool({
connectionLimit: 100, //important
host: 'localhost',
user: 'php-crud-api',
password: 'php-crud-api',
database: 'php-crud-api',
charset: 'utf8',
debug: false
});

// ensure request has database connection

var withConnection = function (handler) {
return function (req, resp) {
pool.getConnection(function (err, connection) {
if (err) {
resp.writeHead(404)
resp.end(err);
return;
}
req.db = connection;
handler(req, resp);
});
}
};

// ensure request has (post) body

var withBody = function (handler) {
return function (req, resp) {
var input = "";
req.on("data", function (chunk) {
input += chunk;
});
req.on("end", function () {
req.body = input;
handler(req, resp);
});
}
};

// main web handler

var server = http.createServer(withConnection(withBody(function (req, resp) {

// get the HTTP method, path and body of the request
var method = req.method;
var request = req.url.replace(/^[\/]+|[\/]+$/g, '').split('/');
try {
var input = JSON.parse(req.body);
} catch (e) {
var input = {};
}

// retrieve the table and key from the path
var table = req.db.escapeId(request.shift());
var key = parseInt(request.shift());

// escape the columns and values from the input object
var columns = Object.keys(input).map(function (key) {
return req.db.escapeId(key);
});
var values = Object.keys(input).map(function (key) {
var value = input[key];
if (value === null) return null;
return req.db.escape(value);
});

// build the SET part of the SQL command
var set = '';
for (i = 0; i < columns.length; i++) {
set += (i > 0 ? ',' : '') + columns[i] + '=';
set += (values[i] === null ? 'NULL' : values[i]);
}

// create SQL based on HTTP method
var sql = '';
switch (req.method) {
case 'GET':
sql = "select * from " + table + (key ? " WHERE id=" + key : '');
break;
case 'PUT':
sql = "update " + table + " set " + set + " where id=" + key;
break;
case 'POST':
sql = "insert into " + table + " set " + set;
break;
case 'DELETE':
sql = "delete " + table + " where id=" + key;
break;
}

// execute SQL statement
req.db.query(sql, function (err, result) {

// stop using mysql connection
req.db.release();

// return if SQL statement failed
if (err) {
resp.writeHead(404)
resp.end(err);
return;
}

// print results, insert id or affected row count
resp.writeHead(200, {
"Content-Type": "application/json"
})
if (req.method == 'GET') {
resp.end(JSON.stringify(result));
} else if (method == 'POST') {
resp.end(JSON.stringify(result.insertId));
} else {
resp.end(JSON.stringify(result.affectedRows));
}

});

})));

server.listen(8000);
11 changes: 11 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "js-crud-api",
"description": "A Node.js port of the full php-crud-api project (single file REST API)",
"version": "0.0.1",
"author": "Maurits van der Schee <maurits@vdschee.nl>",
"repository": "mevdschee/js-crud-api",
"license": "MIT",
"dependencies": {
"mysql": "*"
}
}

0 comments on commit a893d7a

Please sign in to comment.