Created
June 20, 2024 12:51
-
-
Save karthikziffer/249247f1dc944dbf6466cf05616c1376 to your computer and use it in GitHub Desktop.
nodeJS POST API (write record to Azure SQL)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
app.use(express.json()) | |
var Connection = require('tedious').Connection; | |
var config = { | |
server: '', //update me | |
authentication: { | |
type: 'default', | |
options: { | |
userName: '', //update me | |
password: '' //update me | |
} | |
}, | |
options: { | |
// If you are on Microsoft Azure, you need encryption: | |
encrypt: true, | |
database: 'turns' //update me | |
} | |
}; | |
////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
var Request = require('tedious').Request | |
var TYPES = require('tedious').TYPES; | |
function writeRow(connection, inbound_id, quantity) { | |
var request = new Request("UPDATE dbo.inbound SET quantity=@quantity WHERE inbound_id=@inbound_id;", function(err) { | |
if (err) { | |
console.log(err);} | |
}); | |
request.addParameter('inbound_id', TYPES.NVarChar, inbound_id); | |
request.addParameter('quantity', TYPES.Int , quantity); | |
// Close the connection after the final event emitted by the request, after the callback passes | |
request.on("requestCompleted", function (rowCount, more) { | |
connection.close(); | |
}); | |
connection.execSql(request); | |
} | |
////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
app.post('/api/data', (req, res) => { | |
const { inbound_id, quantity } = req.body; | |
var connection = new Connection(config); | |
connection.connect(); | |
connection.on('connect', function(err) { | |
// If no error, then good to proceed. | |
console.log("Connected"); | |
writeRow(connection, inbound_id, quantity); | |
}); | |
res.json({ message: 'Done writing Data' }); | |
}); | |
////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
const PORT = process.env.PORT || 3000; | |
app.listen(PORT, () => { | |
console.log(`Server is running on port ${PORT}`); | |
}); | |
////////////////////////////////////////////////////////////////////////////////////////////////////////// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment