Created
December 23, 2016 20:16
-
-
Save Domacoski/bdd400fd70baca44d26ce3b346445cec to your computer and use it in GitHub Desktop.
Rest Node JS + Sqlite
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
var sqlite3 = require('sqlite3').verbose(); | |
function getDataBase(){ | |
return new sqlite3.Database('user.db'); | |
} | |
var db =getDataBase(); | |
db.serialize(function() { | |
db.run("CREATE TABLE if not exists user_info (info TEXT)"); | |
}); | |
db.close(); | |
var express = require('express'); | |
var app = express(); | |
const hostname = '10.3.0.94'; | |
const port = 3000; | |
var bodyParser = require('body-parser'); | |
app.use( bodyParser.json() ); // to support JSON-encoded bodies | |
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies | |
extended: true | |
})); | |
app.get('/user_info', function (req, res) { | |
var dataBase = getDataBase(); | |
dataBase.all("SELECT rowid AS id, info FROM user_info", function(err, rows) { | |
if(rows){ | |
var resultText = '{"itens": [ '; | |
var len = rows.length; | |
console.log(rows); | |
for (var i = 0; i < len; i++) { | |
var item = rows[i]; | |
resultText += ' {"id": '+item.id+', "info": "'+item.info+ '"} '; | |
if(i != (len-1)){ | |
resultText += ','; | |
} | |
} | |
res.end( resultText+' ]}' ); | |
} | |
}); | |
dataBase.close(); | |
}); | |
app.post('/add_user_info', function (req, res) { | |
var itemTxt = req.body.info; | |
console.log( itemTxt ); | |
if(itemTxt){ | |
if('' != itemTxt){ | |
var dataBase = getDataBase(); | |
var stmt = dataBase.prepare("INSERT INTO user_info VALUES (?)"); | |
stmt.run(itemTxt); | |
stmt.finalize(); | |
dataBase.close(); | |
} | |
} | |
}); | |
app.post('/user_info_by_id', function (req, res) { | |
var _id = req.body.id; | |
if(_id){ | |
if('' != _id){ | |
var dataBase = getDataBase(); | |
dataBase.each("SELECT rowid AS id, info FROM user_info where id = "+_id, function(err, row) { | |
res.end(' {"id": '+row.id+', "info": "'+row.info+ '"} ' ); | |
}); | |
dataBase.close(); | |
} | |
} | |
}); | |
var server = app.listen(port, function () { | |
console.log("Start app listening at http://%s:%s", hostname, port) | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment