Created
March 12, 2017 01:57
-
-
Save deecewan/7f1080244ad0f9c8f4df7fa46eed07f6 to your computer and use it in GitHub Desktop.
Simple script to test Google Cloud Functions background functions
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
#!/usr/bin/env node | |
const join = require('path').join; | |
const read = require('fs').readFileSync; | |
const args = process.argv.slice(2); | |
const fnName = args[0]; | |
const payload = args[1]; | |
const fileBuffer = read(join(__dirname, 'payloads', `${payload}.json`)); | |
// construct event to be sent | |
const event = { | |
data: { | |
data: fileBuffer.toString('base64'), | |
}, | |
timestamp: (new Date()).toISOString(), | |
eventId: 1, | |
}; | |
const fn = require(join(process.cwd(), 'build', fnName)).default; | |
const originalLog = console.log; | |
// alias so we can see what's happening | |
console.log = (...args) => originalLog.apply(console, [`[${fnName}]`, ...args]); | |
const thenFn = () => { console.log = originalLog; console.log('Test Complete!')} | |
// let it do what it needs to do | |
if (fn.length === 1) { | |
const res = fn(event); | |
if (res instanceof Promise) { | |
res.then(thenFn); | |
} else { | |
throw new Error('Function only has one param and doesn\'t return a Promise'); | |
} | |
} else { | |
const x = setTimeout(() => { | |
throw new Error('Function has taken too long to execute'); | |
process.exit(1); | |
}, 8000); // die after 8 seconds | |
const cb = c => () => {clearTimeout(x); c()} | |
new Promise(res => fn(event, cb(res))).then(thenFn); // will keep running until cb is called | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment