Fede E.
Fede E.

Reputation: 1918

Using mssql in nodejs (function to insert row)

So, I'm new to Nodejs, and now I am trying to make an insert, based on an action I receive from a client.

I have a functions module, which is called by the routes to make certain tasks. Each action needs to be recorded in a mssql table, so I chose to use mssql from npm.

https://www.npmjs.com/package/mssql

Each function in the functions module calls the saveActionToDB function which received an action and a username to make the insert into the table like this:

function saveActionToDB(action, user){
    if (config.Logging.DB.type == 'mssql'){
        const dbOptions = {
            user: config.Logging.DB.user,
            password: config.Logging.DB.password,
            server: config.Logging.DB.server,
            database: config.Logging.DB.database,
            options: {
                encrypt: config.Logging.DB.encrypt
            }
        };
        const database = require('mssql');
        async () => {
            try{
                const pool = await database.connect(dbOptions);
                const result = await database.query(`insert into actions (action, user) values ("${action}", "${user}")`);
                console.log(pool);
            }
            catch (err){
                console.log(err);
                combinedLogger.error(err);
            }
        }
    }
    else if(config.Logging.DB.type == 'oracle'){
        //oracle
    }
}

The app needs to have the ability to use either mssql or oracle. That;s why it checks the config.Logging.DB.type val to use each of the two.

Right now, the functions call the saveActionToDB, but it doesn't do anything. No errors either. I am guessing it's an issue with the async thing.

Note that I don't need to wait for the saveActionToDB to end in order to respond to the client.

Can anyone help?

Upvotes: 0

Views: 338

Answers (1)

AbhinavD
AbhinavD

Reputation: 7282

You are not calling your async function. This just declares a function but does not execute. async () => {

Looks at this example

console.log('a');
x = async () => {
  console.log('b');
}

console.log('c');
x();

the output is a c b. However if I do

console.log('a');
async () => {
  console.log('b');
}

console.log('c');

Output is just a c.

Upvotes: 1

Related Questions