Error in separating responsibilities

0

On the node, I created the following template to represent my user:

"use strict";

var Sequelize = require('sequelize');

module.exports = function() {
  return sequelize.define('user', {
    ID_USER: {
      type: Sequelize.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    Name: {
    type: Sequelize.STRING,
    field: 'NAME',
	allowNull : true
  },
	Email: {
    type: Sequelize.STRING,
    field: 'EMAIL',
	allowNull : true
  },
	Photo: {
    type: Sequelize.STRING,
    field: 'PHOTO',
	allowNull : true
  },
	Password: {
      type: Sequelize.STRING,
      field: 'PASSWORD',
	  allowNull : true
	},
    Country: {
      type: Sequelize.STRING,
      allowNull: true,
	  field: 'COUNTRY',
    },
    State: {
      type: Sequelize.STRING,
      allowNull: true,
	  field: 'STATE',
    },
    City: {
      type: Sequelize.STRING,
      allowNull: true,
	  field: 'CITY',
    },
    AddDate: {
      type: Sequelize.DATE,
      allowNull: true,
	  defaultValue: Sequelize.NOW,
	  field: 'ADD_DATE'
    }
  }, {
	createdAt: false,
	updatedAt: false,
    tableName: 'user'
})};

And in my main application I have created the following code:

var User = require('./User');

var Sequelize = require('sequelize')
  , sequelize = new Sequelize('uri', 'root', 'tibia+_.0017', {
      dialect: "mariadb", 
      port:    3306, 
    });

sequelize
  .authenticate()
  .then(function(err) {
    console.log('Connection has been established successfully.');
  }, function (err) { 
    console.log('Unable to connect to the database:', err);
  });
  

var bruno = new User({	
		Name: 'Bruno',
		Email: '[email protected]',
		Photo : 'teste',
		Password: 'cliente1234',
		Country: 'Brazil',
		State: 'SP',
		City: 'São Paulo'});

		
bruno.create({
  }).then(function(user) {
    res.json(user);
  });

When I run the main file it has the following error:

  

sequelize is not defined

My question is beyond error, it's how I separate the project into several layers, because in my project I still can not remove the connection to the template. My idea would be to have the following files:

Connection file. File that represents the model of the object (here I will have several files) File that runs CRUD.

It would basically be a DDD framework

    
asked by anonymous 15.03.2017 / 15:45

1 answer

0

The first problem is that the% w / o% you should use when defining the templates is the configured instance with the database, not the static class.

Example:

const Sequelize = require('sequelize') // evite misturar as definições estáticas das dinâmicas

const sequelize = new Sequelize('uri', 'root', 'tibia+_.0017', {
  dialect: "mariadb", 
  port:    3306, 
})

sequelize.authenticate()
.then(authenticatedSequelize => {
    
    authenticatedSequelize.define('user', {
        ID_USER: {
            type: Sequelize.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        ...
    })

})

But that does not solve your other problem, which is modularization. I suggest the following configuration:

  

root /

     
  • models /

         
    • configureDatabase.js

    •   
    • index.js

    •   
    • user.js

    •   
  •   

configureDatabase.js is the configuration of the database:

// evite misturar as definições estáticas com as dinâmicas
const Sequelize = require('sequelize')

module.exports = () => {
    const sequelize = new Sequelize('uri', 'root', 'tibia+_.0017', {
        dialect: "mariadb", 
        port:    3306, 
    })
    return sequelize.authenticate() // é aqui que gera o authenticatedSequelize
}

Being inside the templates ( user.js ):

module.exports = (authenticatedSequelize) => {
  return authenticatedSequelize.define('user', {
        ID_USER: {
            type: Sequelize.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        ...
    })
}

And so on index.js :

const configureDatabase = require('./configureDatabase')
const userModel = require('./user')

exports.load = () => {

  return configureDatabase() // faz a configuração do banco com seus parâmetros
  .then(authenticatedSequelize => {

    // é aqui que entrega a instância para os modelos
    exports.User = userModel(authenticatedSequelize)

    return
  }
}

In conclusion, to use your templates, you just need to do:

const models = require('./models')
models.load()
.then(() => {
    return models.User.findAll()
})
    
03.04.2017 / 20:32