Monday, 17 April 2017

Nodejs express API one sequelize(db) instance to all models

I'm new to Nodejs and learning the api development from a udemy course https://www.udemy.com/api-development/learn/v4/content the course use mongodb(mongoose) but I'm now trying to replace mongoose with Sequelize

ill try to explain the problem in detail. i have a file db.js

import mongoose from 'mongoose';
import config from './config';
export default callback => {
    let db = mongoose.connect(config.mongoUrl);
    callback(db);
}

i replaced it with sequelize

import Sequelize from 'Sequelize';
import config from './config';

export default callback => {
    let db = new Sequelize(config.dbname, config.dbuser, config.dbpassword, {
      host: config.dbhost,
      dialect: 'mariadb',

      pool: {
        max: 5,
        min: 0,
        idle: 10000
      }
    });

    callback(db);

}

it takes this db instance and pass it to middleware and controllers in routes.js file

import express from 'express';
import config from '../config';
import middleware from '../middleware';
import initializeDb from '../db';
import restaurant from '../controller/restaurant';

let router = express();

//connect to db
initializeDb(db => {

    //internal middleware
    router.use(middleware({config,db}));

    // api routes
    router.use('/restaurant',restaurant({config,db}));
});

export default router;

and pass this routes to app.use when it creates the server

import http from 'http';
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';

import config from './config';
import routes from './routes'; //her it imports the routes and pass it to app.use below

let app = express();
app.server = http.createServer(app);

// middleware
// parse application/json

app.use(bodyParser.json({
    limit:config.bodyLimit
}));


// passport config


//api routes v1
app.use('/v1',routes); //here it pass the routes

var listener = app.server.listen(config.port,function(){
    console.log(`Started on port ${listener.address().port}`);
});


export default app;

so at this point the db instance is now available on my controllers here is how: this is one of the controller

import mongoose from 'mongoose';
import  { Router } from 'express';
import Restaurant from '../model/restaurant';

export default({config,db}) => {
    let api = Router();

    // '/v1/restaurant' - Read
    api.get('/',(req,res) => {
        // i have db available here
    }); 



    return api;
}

at this point i need the db instance in the model so i can just import it in the controller(return model to the controller) instead of using db instance in the controller import Restaurant from '../model/restaurant'; where Restaurant will be sequelize model

but since i dont have db available in the model, one way is to initialize db in the model file but i m thinking if there is the way to get the already initialized db instance it would be better, in mongoose it generates model using schema but for sequelize i need to have the db instance in order to create the model, below is the mongoose model.

import mongoose from 'mongoose';
let Schema = mongoose.Schema;

let restaurantSchema = new Schema({
    name:String
});

module.exports = mongoose.model('Restaurant',restaurantSchema);

any help would be appreciated, or if there is a better way of doing that please suggest



via Wasif Khalil

No comments:

Post a Comment