Is there any way to import a dependency into an object? NODE.JS

Asked

Viewed 59 times

2

I’m developing an Electron application together with Node.js, and I can’t import a dependency within an object.

inserir a descrição da imagem aqui

You can do this, import a dependency into an object?

const conexao = {    

    **//Acredito que o problema está aqui.**
    msql = require('mysql'),

    connection = msql.createConnection({
        host: 'localhost',
        user: 'root',
        password : 'root',
        database: 'bd_barbearia'
    }),

    criarConexao: function(){
        connection.connect();
    },

    fecharConexao: function(){
        connection.end();
    },

    verificarUsuario: function(nome,senha){
        connect.query("call verificarCliente('"+this.nome+"','"+this.senha+"')", function(error,results){
            if(error) throw error;
            lista = JSON.parse(JSON.stringify(results[0]));
            resposta = String(lista[0].alert);

            return resposta;
        });
    }
};

module.exports = conexao;
  • Why don’t you just put the Mysql import out of the object? So you won’t need it with the various problems that the this of the JS brings...

1 answer

2


The error really is on the line you placed the comment on. Not because of the require, but rather because of = where the correct would be to use :.

To create an object in javascript you must follow some rules:

Each name/value pair must be separated by a comma and the name and value, in each case, separated by two points. The syntax always follows this pattern:

var nomeDoObjeto = {
  nomeMembro1: valorMembro1,
  nomeMembro2: valorMembro2,
  nomeMembro3: valorMembro3
};

So the correct code would be:


// estamos deixando a importação "do lado de fora" do objeto para não termos problemas com referência do objeto.
const mysql = require('mysql');

// mesma coisa com com sua conexão.
const connection = msql.createConnection({
    host: 'localhost',
    user: 'root',
    password : 'root',
    database: 'bd_barbearia'
})

const conexao = {

    **//Acredito que o problema está aqui.**
    msql: mysql, // mude o = por :

    connection: connection,

    criarConexao: function(){
        connection.connect();
    },

    fecharConexao: function(){
        connection.end();
    },

    verificarUsuario: function(nome,senha){
        connect.query("call verificarCliente('"+this.nome+"','"+this.senha+"')", function(error,results){
            if(error) throw error;
            lista = JSON.parse(JSON.stringify(results[0]));
            resposta = String(lista[0].alert);

            return resposta;
        });
    }
};

module.exports = conexao;

Browser other questions tagged

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