nik
nik

Reputation: 69

where to define database logic in express?

I am using express node js for my redirection project.I am just beginner in express node js. I don't know where to define my database logic.

Aim:- Getting the url from database and redirect to that url.

my directory structure:-

 app.js
 controller
     ---------index.js
  node_modules
  package.json
  public
  ------images
  ------stylesheet
  ------javascripts
  routes
  -----index.js
  views

app.js

var express = require('express')
, http = require('http')
, mysql = require('mysql')
, path = require('path');
var app = express();
var controller =  require('./controller')({app: app});

// all environments
 app.configure(function() {

app.set('port', process.env.PORT || 8888);
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(app.router);
app.get('/', function( req, res) {
res.render('index');
 });

 });        
 //connect to mysql database
 var connection = mysql.createConnection({
 host : 'localhost',
 user : 'root',
 password : 'xxxxx',
 database : 'nodejsmysql'
 });
 connection.connect();

 http.createServer(app).listen(app.get('port'), function(){
     console.log('Express server listening on port ' + app.get('port'));
 });

controller

function controller(param)
  {
var app = param.app;

app.get('/id', function(request, response) {
    var id= request.param("id");
   // i need to use this id to fetch corresponding url from database and redirect that url.
 });
 }

module.exports = controller;

database query:- select url from db where id='id';

Upvotes: 0

Views: 308

Answers (1)

Hector Correa
Hector Correa

Reputation: 26690

Typically you create Models to handle database logic. The general pattern is

  • app.js - list all your routes
  • routesX.js - handles code for routes (say /x/whatever). This is where you evaluate HTTP values like querystring, cookies, and form data. Renders the view after calling the model.
  • modelsX.js - handles the domain logic for the routes (including database access)

So for example in a routesX.js you might have something like this:

var blogModel = require('./modelsX.js');

exports.blogAll = function(req, res) {

   blogModel.getAll(function(data) {
       res.render('someView', data);
   });

}

and in your modelsX.js you might have something like this:

exports.getAll = function(callback) {

   // get data from the database here
   // and call the callback 
   callback()

}

If you want to see a full end-to-end example, check out this repo: https://github.com/hectorcorrea/hectorcorrea.com/blob/master/routes/blogRoutes.js

Upvotes: 1

Related Questions