|
| 1 | +const { createProbot } = require('probot-ts'); |
| 2 | +const { resolve } = require('probot-ts/lib/resolver') |
| 3 | +const { findPrivateKey } = require('probot-ts/lib/private-key') |
| 4 | +const { template } = require('./views/probot') |
| 5 | + |
| 6 | +const loadProbot = (plugin) => { |
| 7 | + const probot = createProbot({ |
| 8 | + id: process.env.APP_ID, |
| 9 | + secret: process.env.WEBHOOK_SECRET, |
| 10 | + cert: findPrivateKey() |
| 11 | + }) |
| 12 | + |
| 13 | + if (typeof plugin === 'string') { |
| 14 | + plugin = resolve(plugin) |
| 15 | + } |
| 16 | + |
| 17 | + probot.load(plugin) |
| 18 | + |
| 19 | + return probot |
| 20 | +} |
| 21 | + |
| 22 | + |
| 23 | +module.exports.serverless = (plugin) => { |
| 24 | + |
| 25 | + return (event, context, callback) => { |
| 26 | + |
| 27 | + // 🤖 A friendly homepage if there isn't a payload |
| 28 | + if (event.httpMethod === 'GET' && event.path === '/probot') { |
| 29 | + const res = { |
| 30 | + statusCode: 200, |
| 31 | + headers: { |
| 32 | + 'Content-Type': 'text/html' |
| 33 | + }, |
| 34 | + body: template |
| 35 | + } |
| 36 | + return callback(null, res) |
| 37 | + } |
| 38 | + |
| 39 | + // Otherwise let's listen handle the payload |
| 40 | + const probot = loadProbot(plugin) |
| 41 | + |
| 42 | + // Ends function immediately after callback |
| 43 | + context.callbackWaitsForEmptyEventLoop = false |
| 44 | + |
| 45 | + // Determine incoming webhook event type |
| 46 | + const e = event.headers['x-github-event'] || event.headers['X-GitHub-Event'] |
| 47 | + const id = event.headers['x-github-delivery'] || event.headers['X-GitHub-Delivery'] |
| 48 | + |
| 49 | + // Convert the payload to an Object if API Gateway stringifies it |
| 50 | + event.body = (typeof event.body === 'string') ? JSON.parse(event.body) : event.body |
| 51 | + |
| 52 | + // Do the thing |
| 53 | + console.log(`Received event ${e}${event.body.action ? ('.' + event.body.action) : ''}`) |
| 54 | + if (event) { |
| 55 | + try { |
| 56 | + probot.receive({ |
| 57 | + event: e, |
| 58 | + payload: event.body |
| 59 | + }).then(() => { |
| 60 | + const res = { |
| 61 | + statusCode: 200, |
| 62 | + body: JSON.stringify({ |
| 63 | + message: 'Executed' |
| 64 | + }) |
| 65 | + } |
| 66 | + return callback(null, res) |
| 67 | + }) |
| 68 | + } catch (err) { |
| 69 | + console.error(err) |
| 70 | + callback(err) |
| 71 | + } |
| 72 | + } else { |
| 73 | + console.error({ event, context }) |
| 74 | + callback('unknown error') |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments