Skip to content

Commit

Permalink
feat: caching installation tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
gr2m committed Nov 24, 2018
1 parent 4d3d103 commit 84a518d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
8 changes: 5 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
module.exports = App

const getSignedJsonWebToken = require('./lib/get-signed-json-web-token')
const getCache = require('./lib/get-cache')
const getInstallationAccesToken = require('./lib/get-installation-access-token')
const getSignedJsonWebToken = require('./lib/get-signed-json-web-token')

function App ({ id, privateKey }) {
function App ({ id, privateKey, cache }) {
const state = {
id,
privateKey
privateKey,
cache: cache || getCache()
}
const api = {
getSignedJsonWebToken: getSignedJsonWebToken.bind(null, state),
Expand Down
13 changes: 13 additions & 0 deletions lib/get-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = getCache

// https://github.com/isaacs/node-lru-cache#readme
const LRU = require('lru-cache')

function getCache () {
return new LRU({
// cache max. 15000 tokens, that will use less than 10mb memory
max: 15000,
// Cache for 1 minute less than GitHub expiry
maxAge: 1000 * 60 * 59
})
}
13 changes: 11 additions & 2 deletions lib/get-installation-access-token.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@ const getSignedJsonWebToken = require('./get-signed-json-web-token')

// https://developer.github.com/v3/apps/#create-a-new-installation-token
function getInstallationAccesToken (state, { installationId }) {
return request('POST /app/installations/:installation_id/access_tokens', {
const token = state.cache.get(installationId)
if (token) {
return Promise.resolve(token)
}

return request({
method: 'POST',
url: '/app/installations/:installation_id/access_tokens',
installation_id: installationId,
headers: {
accept: 'application/vnd.github.machine-man-preview+json',
// TODO: cache the installation token if it's been less than 60 minutes
authorization: `bearer ${getSignedJsonWebToken(state)}`
}
}).then(response => {
state.cache.set(installationId, response.data.token)
return response.data.token
})
.then(response => response.data.token)
}

0 comments on commit 84a518d

Please sign in to comment.