Skip to content

Instantly share code, notes, and snippets.

@deecewan
Created March 12, 2017 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deecewan/7f1080244ad0f9c8f4df7fa46eed07f6 to your computer and use it in GitHub Desktop.
Save deecewan/7f1080244ad0f9c8f4df7fa46eed07f6 to your computer and use it in GitHub Desktop.
Simple script to test Google Cloud Functions background functions
#!/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