Skip to content
This repository has been archived by the owner on Jan 20, 2023. It is now read-only.

Commit

Permalink
feat($fetch): new env: SKIP_CACHE and AUTH_TOKEN
Browse files Browse the repository at this point in the history
  • Loading branch information
ulivz committed Feb 7, 2019
1 parent 5665483 commit c0530d9
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions lib/yuque.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit c0530d9

Please sign in to comment.