Last active
June 21, 2018 21:00
-
-
Save amaurs/6087980f24f6fb4e0847237566363ca5 to your computer and use it in GitHub Desktop.
App that lets you connect to a SQL SERVER database with tedious and server the query through express.
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
if (process.env.NODE_ENV !== 'production') { | |
require('dotenv').load(); | |
} | |
var Connection = require('tedious').Connection; | |
var Request = require('tedious').Request; | |
var fs = require('fs'); | |
var query = fs.readFileSync("query.sql", "utf8"); | |
var port = 3000; | |
var config = { | |
userName: process.env.USER_NAME, | |
password: process.env.PASSWORD, | |
server: process.env.SERVER, | |
options: | |
{ | |
database: process.env.DATABASE | |
, encrypt: true | |
} | |
} | |
var connection = new Connection(config); | |
var express = require('express') | |
var app = express() | |
app.use(function (req, res, next) { | |
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); | |
res.setHeader('Access-Control-Allow-Methods', 'GET'); | |
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); | |
next(); | |
}); | |
app.get('/api', getData) | |
connection.on('connect', function(err) { | |
if (err) { | |
throw err; | |
} | |
else { | |
app.listen(port, '0.0.0.0'); | |
} | |
}); | |
function getData(req, res, next) { | |
request = new Request(query, function(err, rowCount, rows) { | |
console.log(rowCount + ' row(s) returned'); | |
}); | |
var results = []; | |
request.on('row', function(columns) { | |
var obj = {} | |
columns.forEach(function(column) { | |
obj[column['metadata']['colName']] = column['value']; | |
}) | |
results.push(obj); | |
}); | |
request.on('doneProc', function(rowCount, more, returnStatus, rows) { | |
res.json(results); | |
}); | |
request.on('error', next); | |
try { | |
connection.execSql(request); | |
} catch (e) { | |
next(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment