From 84a518dd7450c2fc4439792033f248872ec5636c Mon Sep 17 00:00:00 2001 From: Gregor Date: Fri, 23 Nov 2018 22:27:19 -0800 Subject: [PATCH] feat: caching installation tokens --- index.js | 8 +++++--- lib/get-cache.js | 13 +++++++++++++ lib/get-installation-access-token.js | 13 +++++++++++-- 3 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 lib/get-cache.js diff --git a/index.js b/index.js index 9f31a0242..f9c12df24 100644 --- a/index.js +++ b/index.js @@ -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), diff --git a/lib/get-cache.js b/lib/get-cache.js new file mode 100644 index 000000000..7cc907cd0 --- /dev/null +++ b/lib/get-cache.js @@ -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 + }) +} diff --git a/lib/get-installation-access-token.js b/lib/get-installation-access-token.js index 069dac4e8..e2a610cd5 100644 --- a/lib/get-installation-access-token.js +++ b/lib/get-installation-access-token.js @@ -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) }