Advertisement
Guest User

A Node API Example For Node/Angular MVC

a guest
May 26th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //nasty SQL value handling, but Named parameters don't seem to work, ERROR:25 ??
  2.  
  3.  
  4. /*
  5.  *   A model class, creates table if needed (no database init needed)
  6.  *   Stores all data in memory, async node/sqlite3 keeps data save
  7.  */
  8. var Model = function( name, model ) {
  9.     this.name = name;
  10.     this.model = model;
  11.     this.data = [];
  12.    
  13.     //Returns a create table sql statement
  14.     this.toSQLcreate = function( ) {
  15.         var sql = "CREATE TABLE '" + this.name + "' ("
  16.         for(var prop in this.model){
  17.             sql += "'" + prop + "' " + this.model[prop] + ", "
  18.         }
  19.         sql = sql.slice(0,-2);
  20.         sql += ")";
  21.        
  22.       return sql;
  23.     }
  24.    
  25.     //Check if table exists in database, of not, create
  26.     this.check = function( ) {
  27.         var t = this;
  28.         db.all("SELECT id FROM '" + t.name + "' LIMIT 0,1", function(err, rows) {
  29.             if( err && err.toString().indexOf("no such table: " + t.name) > -1  ) {
  30.                 db.run( t.toSQLcreate() );
  31.             }
  32.         });
  33.     }
  34.    
  35.     //Check if table exists in database, of not, create
  36.     this.create = function( data ) {
  37.         var sql = "INSERT INTO '" + this.name + "' ("
  38.        
  39.         //Todo : check if data is valid for model, but should always be as it is given by Angular
  40.        
  41.         for(var prop in data){
  42.             sql += "" + prop + ", "
  43.         }
  44.         sql = sql.slice(0,-2);
  45.         sql += ") VALUES (";
  46.         for(var prop in data){
  47.             if( this.model[prop].indexOf("INTEGER" > -1 )
  48.                 sql += data[prop] + ", "
  49.             else
  50.                 sql += "'" + data[prop] + "', "
  51.         }
  52.         sql = sql.slice(0,-2);
  53.         sql += ")";
  54.        
  55.         db.run(sql);
  56.     }
  57.    
  58.     this.update = function( data ) {
  59.         var sql = "UPDATE '" + this.name + "' SET"
  60.        
  61.         //Todo : check if data is valid for model, but should always be as it is given by Angular
  62.        
  63.         for(var prop in data){
  64.             if( this.model[prop].indexOf("INTEGER" > -1 )
  65.                 sql += prop + " = " + data[prop] + ", "
  66.             else
  67.                 sql += prop + " = '" + data[prop] + "', "
  68.         }
  69.         sql = sql.slice(0,-2);
  70.         sql += " WHERE id = " + data.id;
  71.        
  72.         db.run(sql);
  73.     }
  74.    
  75.     this.delete = function( schedule_id ) {
  76.         db.run("DELETE FROM '" + this.name + "' WHERE id = " + schedule_id);
  77.         var cnt = 0;
  78.         for( s in this.data ) {
  79.             if( s.id == schedule_id ) {
  80.                 this.data.splice(cnt,1);
  81.                 break;
  82.             }
  83.             cnt++;
  84.         }
  85.     }
  86.    
  87.     //Put all database data in data array
  88.     this.all = function( ) {
  89.         var t = this;
  90.         db.all("SELECT * FROM '" + t.name + "'", function(err, rows) {
  91.             t.data = rows;
  92.         });
  93.     }
  94.    
  95.     this.find = function( what ) {
  96.         var sql = "SELECT * FROM '" + this.name + "'"
  97.        
  98.         if( what.length ) {
  99.             sql += " WHERE"
  100.             for(var prop in what){
  101.                 if( this.model[prop].indexOf("INTEGER" > -1 )
  102.                     sql += prop + " = " + data[prop] + " AND "
  103.                 else
  104.                     sql += prop + " = '" + data[prop] + "' AND "
  105.             }
  106.             sql = sql.slice(0,-5);
  107.         }
  108.        
  109.         var found = [];
  110.         db.all(sql, function(err, rows) {
  111.             found = rows;
  112.         });
  113.        
  114.         return found;
  115.     }
  116.    
  117.    
  118.     this.check();
  119.     this.all();
  120.    
  121.    
  122. }
  123.  
  124.  
  125.  
  126. // classes ========================
  127. var Schedule = function( model ) {
  128.     this.model = model;
  129. }
  130.  
  131.  
  132.  
  133.  
  134. // set up ========================
  135. var express        = require('express');
  136. var app            = express();
  137. var sqlite3        = require('sqlite3').verbose();
  138. var morgan         = require('morgan');
  139. var bodyParser     = require('body-parser');
  140. var methodOverride = require('method-override');
  141.  
  142.  
  143.  
  144. // configuration =================
  145. var db = new sqlite3.Database('newton.db');
  146.  
  147. app.use(express.static(__dirname + '/public'));                 // set the static files location /public/img will be /img for users
  148. app.use(morgan('dev'));                                         // log every request to the console
  149. app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
  150. app.use(bodyParser.json());                                     // parse application/json
  151. app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
  152. app.use(methodOverride());
  153.  
  154.  
  155. // define model =================
  156. var Schedule = new Schedule(
  157.         new Model('Schedule',
  158.             {
  159.             id : 'INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL',
  160.             description : 'TEXT NOT NULL',
  161.             planned_on : 'DATETIME NOT NULL',
  162.             time_estimated : 'INTEGER NOT NULL',
  163.             }
  164.         )
  165. );
  166.  
  167.  
  168.  
  169. // listen (start app with node server.js) ======================================
  170. app.listen(8080);
  171. console.log("App listening on port 8080");
  172.  
  173.  
  174.  
  175. // routes ======================================================================
  176.  
  177. /*
  178.  *  API Calls
  179.  */
  180.  
  181. //Get all schedules
  182. app.get('/api/schedule', function(req, res) {
  183.     res.json( Schedule.model.find() );
  184. });
  185.  
  186. //Createa a schedule with JSON POST
  187. app.post('/api/schedule', function(req, res) {
  188.     // create a todo, information comes from AJAX request from Angular
  189.     Schedule.create( JSON.parse( req.body.text ) , function() {
  190.         res.json(Schedule.model.find());
  191.     });
  192.  
  193. });
  194.  
  195.    
  196. // delete a todo
  197. app.delete('/api/schedule/:id', function(req, res) {
  198.     Schedule.delete( req.params.schedule_id );    
  199. });
  200.  
  201.  
  202. app.get('*', function(req, res) {
  203.     res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
  204. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement