probot / github-app

node module to handle authentication for the GitHub Apps API
51 stars 19 forks source link

Experiment with porting to octokit plugin #14

Closed bkeepers closed 5 years ago

bkeepers commented 6 years ago

@cirpo's feature request in https://github.com/octokit/rest.js/issues/980, as well as @gjtorikian pinging me about https://github.com/probot/github-app/pull/13 got me wondering what it would take to convert this module a plugin for @octokit/rest.

From the updated README:


Usage

const octokit = require('@octokit/rest')()
const githubApp = require('@octokit/github-app')
const fs = require('fs')

octokit.plugin(githubApp({
  id: 1234,
  pem: fs.readFileSync('private-key.pem', 'UTF-8')
}))

All requests are now authenticated as the app.

octokit.apps.getInstallations({}).then(res => {
  console.log('Installations:', res)  
})

To authenticate as a specific installation, which can be used to call any of the APIs supported by GitHub Apps, call authenticate with type: 'installation':

octokit.authenticate({
  type: 'installation',
  id: 12345
}).then(() => {
  octokit.issues.createComment({
    owner: 'foo',
    repo: 'bar',
    number: 999,
    body: 'hello world!'
  })
})

Important! This plugin changes the API of octokit.authenticate to return a Promise. You must wait for the Promise to resolve with await or by calling .then().


Here's a quick test script I wrote using this branch:

const octokit = require('@octokit/rest')()
const githubApp = require('.')
const fs = require('fs')

octokit.plugin(githubApp({
  id: 11053,
  pem: fs.readFileSync('private-key.pem', 'UTF-8')
}))

async function test () {
  const { data: installations } = await octokit.apps.getInstallations({})
  console.log('Installations:', installations)

  await octokit.authenticate({ type: 'installation', id: installations[0].id })
  const { data: repositories } = await octokit.apps.getInstallationRepositories({})
  console.log('Repositories:', repositories)
}

test()

There's still work to do here, but I think this will work.