Skip to content
This repository has been archived by the owner on Apr 23, 2022. It is now read-only.

Commit

Permalink
feat: 以 axios-extensions 取代 LRU cache
Browse files Browse the repository at this point in the history
  • Loading branch information
henry40408 committed May 15, 2018
1 parent b114910 commit 7560560
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 55 deletions.
2 changes: 0 additions & 2 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { log } from './common'
import DIConstants from './constants'

import AccessTokenRepository from './background/accessTokenRepository'
import CacheService from './background/cacheService'
import ChromeStorageService from './background/chromeStorageService'
import ContextMenuService from './background/contextMenuService'
import GithubService from './background/githubService'
Expand All @@ -26,7 +25,6 @@ container.register({
[DIConstants.LOG]: awilix.asValue(log),
[DIConstants.MESSAGE_ROUTER]: awilix.asClass(MessageRouter).singleton(),
[DIConstants.R_ACCESS_TOKEN]: awilix.asClass(AccessTokenRepository).singleton(),
[DIConstants.S_CACHE]: awilix.asClass(CacheService).singleton(),
[DIConstants.S_CHROME_STORAGE]: awilix.asClass(ChromeStorageService),
[DIConstants.S_CONTEXT_MENU]: awilix.asClass(ContextMenuService).singleton(),
[DIConstants.S_GITHUB]: awilix.asClass(GithubService)
Expand Down
12 changes: 0 additions & 12 deletions app/scripts/background/cacheService.js

This file was deleted.

78 changes: 39 additions & 39 deletions app/scripts/background/githubService.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import axios from 'axios/index'
import { cacheAdapterEnhancer } from 'axios-extensions'
import includes from 'lodash/includes'
import ApolloClient from 'apollo-boost'
import gql from 'graphql-tag'
Expand All @@ -8,8 +9,6 @@ import DIConstants from '../constants'
class GithubService {
AWESOME_LIST_URL = 'https://raw.githubusercontent.com/sindresorhus/awesome/master/readme.md'

AWESOME_LIST_KEY = '@@awesome-list'

RATE_LIMIT_THRESHOLD = 0.5

constructor (ctx) {
Expand All @@ -18,9 +17,6 @@ class GithubService {
/** @type {AccessTokenRepository} */
this.accessToken = ctx[DIConstants.R_ACCESS_TOKEN]

/** @type {CacheService} */
this.cache = ctx[DIConstants.S_CACHE]

/** @type {ContextMenuService} */
this.contextMenu = ctx[DIConstants.S_CONTEXT_MENU]

Expand All @@ -29,6 +25,12 @@ class GithubService {

/** @type {AxiosInstance} */
this.restfulClient = null

/** @type {AxiosInstance} */
this.rawRestfulClient = axios.create({
baseURL: `https://api.github.com`,
adapter: cacheAdapterEnhancer(axios.defaults.adapter)
})
}

async buildClient () {
Expand All @@ -38,8 +40,9 @@ class GithubService {
if (!this.apolloClient || !this.restfulClient || this.accessToken.changed) {
let headers = {}
let request = async () => {}

if (token) {
headers = { Authorization: `Bearer ${token}` }
headers = { ...headers, Authorization: `Bearer ${token}` }
request = async operation => operation.setContext({ headers })
}

Expand All @@ -54,26 +57,18 @@ class GithubService {

this.restfulClient = axios.create({
baseURL: 'https://api.github.com',
headers
headers,
adapter: cacheAdapterEnhancer(axios.defaults.adapter)
})

this.accessToken.changed = false
}
}

async fetchAwesomeListAsync () {
/** @type {string} */
let awesomeList = this.cache.get(this.AWESOME_LIST_KEY)

if (!awesomeList) {
let response = await axios.get(this.AWESOME_LIST_URL)
awesomeList = response.data
this.cache.set(this.AWESOME_LIST_KEY, awesomeList)
}

let { data: awesomeList } = await this.rawRestfulClient.get(this.AWESOME_LIST_URL)
let awesomeListSize = (awesomeList.length / 1024).toFixed(3)
this.log('📄 fetch awesome list', awesomeListSize, 'KB(s) from cache')

this.log('📄 fetch awesome list', awesomeListSize, 'KB(s)')
return awesomeList
}

Expand All @@ -83,15 +78,7 @@ class GithubService {
let numberFormatter = new Intl.NumberFormat('en-US')
let percentFormatter = new Intl.NumberFormat('en-US', { style: 'percent' })

let [graphqlRateLimit, restfulRateLimit] = await Promise.all([
this.fetchGraphQLRateLimitAsync(),
this.fetchRESTfulRateLimitAsync()
])

let { remaining: restfulRemaining } = restfulRateLimit
let { remaining: graphqlRemaining } = graphqlRateLimit
let { remaining, limit } = restfulRemaining < graphqlRemaining ? restfulRateLimit : graphqlRateLimit

let { remaining, limit } = await this.selectRateLimitAsync()
this.log('🚦 rate limit:', { remaining, limit })

let title = chrome.i18n.getMessage('menuRateLimit', [
Expand All @@ -104,7 +91,20 @@ class GithubService {
return { remaining, limit }
}

async fetchGraphQLRateLimitAsync () {
async selectRateLimitAsync () {
let [graphql, restful] = await Promise.all([
this._fetchGraphQLRateLimitAsync(),
this._fetchRESTfulRateLimitAsync()
])

let { remaining: restfulRemaining } = restful
let { remaining: graphqlRemaining } = graphql
let { remaining, limit } = restfulRemaining < graphqlRemaining ? restful : graphql

return { remaining, limit }
}

async _fetchGraphQLRateLimitAsync () {
let query = gql`query RateLimit {
rateLimit {
remaining
Expand All @@ -116,7 +116,7 @@ class GithubService {
return { remaining, limit }
}

async fetchRESTfulRateLimitAsync () {
async _fetchRESTfulRateLimitAsync () {
let response = await this.restfulClient.get('/rate_limit')
let { rate: { remaining, limit } } = response.data
return { remaining, limit }
Expand All @@ -135,8 +135,8 @@ class GithubService {
)
}

let cues = GithubService.tuplesToCues(tuples)
let query = GithubService.cuesToGraphQLQuery(cues)
let cues = GithubService._buildCuesFromTuples(tuples)
let query = GithubService._buildGraphQLQueryFromCues(cues)

let { data } = await this.apolloClient.query({ query })

Expand All @@ -145,25 +145,25 @@ class GithubService {
this.log('🌀', entries.length, 'repositorie(s) fetched')
}

return this.graphQLToTuples(cues, data)
return this._tuplesFromGraphQLResponseAsync(cues, data)
}

async isAwesomeListAsync ({ owner, name }) {
let awesomeList = await this.fetchAwesomeListAsync()
return includes(awesomeList, `${owner}/${name}`)
}

static tuplesToCues (tuples) {
static _buildCuesFromTuples (tuples) {
return tuples.map((tuple, index) => ({ alias: `repository${index}`, ...tuple }))
}

static cuesToGraphQLQuery (cues) {
static _buildGraphQLQueryFromCues (cues) {
return gql`query Repositories {
${cues.map(GithubService.cueToGraphQLQuery).join('\n')}
${cues.map(GithubService._buildGraphQLFromCue).join('\n')}
}`
}

static cueToGraphQLQuery (cue) {
static _buildGraphQLFromCue (cue) {
let { alias, owner, name } = cue
return `${alias}: repository(owner: "${owner}", name: "${name}") {
owner { login }
Expand All @@ -172,7 +172,7 @@ class GithubService {
}`
}

async graphQLToTuples (cues, data) {
async _tuplesFromGraphQLResponseAsync (cues, data) {
return Promise.all(cues.map(async cue => {
let { alias, owner, name } = cue

Expand All @@ -185,12 +185,12 @@ class GithubService {
return {
owner,
name,
star: await this.fallbackToRESTful(owner, name)
star: await this._fetchStarCountFromRESTfulAPIAsync(owner, name)
}
}))
}

async fallbackToRESTful (owner, name) {
async _fetchStarCountFromRESTfulAPIAsync (owner, name) {
this.log('🆖 missing repository', owner, name, 'found, fallback to RESTful')
let response = await this.restfulClient.get(`https://api.github.com/repos/${owner}/${name}`)
let { data } = response
Expand Down
1 change: 0 additions & 1 deletion app/scripts/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
export default {
MESSAGE_ROUTER: Symbol('router'),
R_ACCESS_TOKEN: Symbol('access token repository'),
S_CACHE: Symbol('cache service'),
S_CHROME_STORAGE: Symbol('chrome storage service'),
S_COMMON: Symbol('common service'),
S_CONTEXT_MENU: Symbol('context menu service'),
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"apollo-boost": "^0.1.6",
"awilix": "~3.0.5",
"axios": "~0.18.0",
"axios-extensions": "^3.0.2",
"bluebird": "~3.5.0",
"chomex": "~1.0.5",
"chrome-promise": "~3.0.0",
Expand Down
19 changes: 18 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,10 @@
version "3.0.1"
resolved "https://registry.yarnpkg.com/@types/inline-style-prefixer/-/inline-style-prefixer-3.0.1.tgz#8541e636b029124b747952e9a28848286d2b5bf6"

"@types/lru-cache@^4.1.0":
version "4.1.0"
resolved "https://registry.yarnpkg.com/@types/lru-cache/-/lru-cache-4.1.0.tgz#ef69ce9c3ebb46bd146f0d80f0c1ce38b0508eae"

"@types/react@^16.0.18":
version "16.0.36"
resolved "https://registry.yarnpkg.com/@types/react/-/react-16.0.36.tgz#ceb5639013bdb92a94147883052e69bb2c22c69b"
Expand Down Expand Up @@ -799,7 +803,16 @@ aws4@^1.2.1, aws4@^1.6.0:
version "1.6.0"
resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.6.0.tgz#83ef5ca860b2b32e4a0deedee8c771b9db57471e"

axios@~0.18.0:
axios-extensions@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/axios-extensions/-/axios-extensions-3.0.2.tgz#bac9abd723ccdbfd638b7aa618d41c1a98384e38"
dependencies:
"@types/lru-cache" "^4.1.0"
axios "*"
lru-cache "^4.1.1"
tslib "^1.9.0"

axios@*, axios@~0.18.0:
version "0.18.0"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.18.0.tgz#32d53e4851efdc0a11993b6cd000789d70c05102"
dependencies:
Expand Down Expand Up @@ -9632,6 +9645,10 @@ tryit@^1.0.1:
version "1.0.3"
resolved "https://registry.yarnpkg.com/tryit/-/tryit-1.0.3.tgz#393be730a9446fd1ead6da59a014308f36c289cb"

tslib@^1.9.0:
version "1.9.1"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.9.1.tgz#a5d1f0532a49221c87755cfcc89ca37197242ba7"

tty-browserify@0.0.0:
version "0.0.0"
resolved "https://registry.yarnpkg.com/tty-browserify/-/tty-browserify-0.0.0.tgz#a157ba402da24e9bf957f9aa69d524eed42901a6"
Expand Down

0 comments on commit 7560560

Please sign in to comment.