Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
// 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