Skip to content
Permalink
Browse files

feat($fetch): new env: SKIP_CACHE and AUTH_TOKEN

  • Loading branch information...
ulivz committed Feb 7, 2019
1 parent 5665483 commit c0530d98b09d80d2c66ff48696476490c346fc1d
Showing with 27 additions and 12 deletions.
  1. +27 −12 lib/yuque.js
@@ -3,7 +3,11 @@ const url = require('url')
const wfetch = require('./fetch')
const store = require('./store')
const { hash, logger, chalk } = require('@vuepress/shared-utils')
const Yuque = require('./yuque')
const { PACKAGE_NAME } = require('./constant')
const debug = require('debug')(`${PACKAGE_NAME}:yuque`)

const AUTH_TOKEN = process.env.YUQUE_QUTH_TOKEN
const SKIP_CACHE = process.env.SKIP_CACHE

let instance
let repoId
@@ -14,28 +18,39 @@ module.exports = class Yuque {
}

static getInstance() {
if (instance) {
return instance
if (!instance) {
instance = new Yuque(repoId)
}
return new Yuque(repoId)
return instance
}

static async fetch(url, options = {}) {
debug('fetch', url, 'with', JSON.stringify(options, null, 2))
const { useCache = true } = options
const yuque = Yuque.getInstance()
const { store } = yuque
const key = hash(url + JSON.stringify(options))
const cacheKey = `fetch.${key}`

if (useCache && store.get(cacheKey)) {
logger.debug(`Using cache for ${chalk.yellow(url)}`)
return store.get(cacheKey)
let yuque

if (repoId && useCache && !SKIP_CACHE) {
yuque = Yuque.getInstance()
const cached = yuque.store.get(cacheKey)
if (cached) {
debug(`Using cache for ${chalk.yellow(url)}`)
return cached
}
}

let response
const foptions = {}
if (AUTH_TOKEN) {
foptions.headers = {
'X-Auth-Token': AUTH_TOKEN
}
}

try {
response = await wfetch(url, options)
store.set(cacheKey, response)
response = await wfetch(url, foptions)
yuque && yuque.store.set(cacheKey, response)
return response
} catch (e) {
return e

0 comments on commit c0530d9

Please sign in to comment.
You can’t perform that action at this time.