Skip to content

Commit

Permalink
chore: compatibility with older yuque client (without token)
Browse files Browse the repository at this point in the history
  • Loading branch information
x-cold committed May 7, 2019
1 parent e08ff8b commit aae718d
Showing 3 changed files with 60 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -30,7 +30,7 @@ A downloader for articles from yuque

## Config

如果你的知识库是私有的,请使用环境变量注入 Token 信息,在语雀上点击个人头像->设置—> Token 即可获取。
如果你的知识库是私有的,请使用环境变量 (YUQUE_TOKEN=xxx) 注入 Token 信息,在语雀上点击个人头像->设置—> Token 即可获取。

> package.json
58 changes: 58 additions & 0 deletions lib/yuque.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use strict';

const SDK = require('@yuque/sdk');
const deprecate = require('depd')('yuque-hexo');


function handler(res) {
// should handler error yourself
@@ -16,9 +18,65 @@ function handler(res) {
return res.data;
}

'use strict';

const urllib = require('urllib');
const debug = require('debug')('yuque-hexo:client');

/**
* doesn't support token
*/
class AnonymousYuqueClient {
constructor(config) {
const { baseUrl, login, repo } = config;
this.config = Object.assign({}, config);
this.config.namespace = `${login}/${repo}`;
debug(`create client: baseUrl: ${baseUrl}, login: ${login}, repo: ${repo}`);
}

async _fetch(method, api, data) {
const { baseUrl, namespace, timeout = 30000 } = this.config;
const path = `${baseUrl}/repos/${namespace}${api}`;
debug(`request data: api: ${path}, data: ${data}`);
try {
const result = await urllib.request(path, {
dataType: 'json',
method,
data,
timeout,
});
return result.data;
} catch (error) {
throw new Error(`请求数据失败: ${error.message}`);
}
}

async getArticles() {
const api = '/docs';
const result = await this._fetch('GET', api);
return result;
}

async getArticle(slug) {
const api = `/docs/${slug}?raw=true`;
const result = await this._fetch('GET', api);
return result;
}

// async getToc() {
// const api = '/toc';
// const result = await this._fetch('GET', api);
// return result;
// }
}

class YuqueClient extends SDK {
constructor(config) {
const { baseUrl, login, repo, token } = config;
if (!token) {
deprecate('TOKEN of yuque will be required while verion >v1.6.0.');
return new AnonymousYuqueClient(config);
}
const endpoint = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
const superConfig = {
endpoint,
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -29,6 +29,7 @@
"chalk": "^2.4.1",
"common-bin": "^2.7.3",
"debug": "^3.1.0",
"depd": "^2.0.0",
"ejs": "^2.6.1",
"hexo-front-matter": "^0.2.3",
"html-entities": "^1.2.1",

0 comments on commit aae718d

Please sign in to comment.