Error in separating responsibilities

Asked

Viewed 80 times

0

On 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 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 you have the following error:

sequelize is not defined

My question is beyond the error, is how do I separate the project into several layers, because in my project I still can’t remove the connection to the model. 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 running the CRUD.

It would basically be a DDD structure

1 answer

0


The first problem is that the sequelize that you should use when defining the models is the configured instance with the seat and 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 this does not solve your other problem which is modularization. I suggest the following configuration:

root/

  • models/

    • configureDatabase.js

    • index js.

    • user js.

Being the configureDatabase.js the seat configuration:

// 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 within the models (user js.):

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

And so, in the 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 models just do:

const models = require('./models')
models.load()
.then(() => {
    return models.User.findAll()
})
  • The part : Return authenticatedSequelize.defines( tarafrog ) Is the object passed by parameter ? The configureDatabase gave error "Cannot read Property 'define'", so I didn’t quite understand being that I called the sequelize

  • Replaces the tarafrog by the actual example copying from the example above, to see if it becomes clearer. I also described literally the content of configureDatabase.js to avoid this mistake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.