Created
July 15, 2016 23:17
-
-
Save tjanczuk/5cd621776ffa5b4ca2013c95966a3ed2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var mysql = require('mysql'); | |
// Webtask compiler entry point. options.script contains parameterized T-SQL script. | |
module.exports = function (options, cb) { | |
// Return a JavaScript function in one of the three basic signatures supported by Webtasks | |
return cb(null, function (ctx, cb) { | |
// Create MySQL connection on first invocation | |
if (!global.connection) { | |
// Validate that required MySQL connection parameters were specified at webtask creation | |
var secrets = ['HOST','DB','USER','PASSWORD']; | |
for (var i = 0; i < secrets.length; i++) | |
if (!ctx.secrets[secrets[i]]) | |
return cb(new Error('You must specify the ' + secrets[i] + ' secret when creating the webtask.')); | |
// Create MySQL connection and cache it in-memory for use by later webtask requests | |
global.connection = mysql.createConnection({ | |
host : ctx.secrets.HOST, | |
user : ctx.secrets.DB, | |
password : ctx.secrets.PASSWORD, | |
database : ctx.secrets.USER | |
}); | |
global.connection.connect(); | |
} | |
// Execute parameterized MySQL query setting parameter value(s) based on | |
// the value of the URL query parameter(s) `q`. Webtask will return MySQL error or | |
// a JSON array of matching rows. | |
return global.connection.query(options.script, ctx.query.q, cb); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment