日々是好日

プログラミングについてのあれこれ、ムダ知識など

はてなAPI叩いてみた

とりあえず叩いてみただけ。

はてな Blog のカテゴリ一覧取得。oauthモジュール Promise ベースでできれば……ってコールバック地獄になるわけではないから別にいいか( ˘ω˘)

this.atomUri = `https://blog.hatena.ne.jp/${id}/${domain}/atom`;

/**
* Get Hatena category.
*/
getCategory() {
    if (!this.existAccessToken()) {
        vscode.window.showErrorMessage("Not stored AccessToken!");
        return;
    }

    const categoriesUri = this.atomUri + '/category';
    this.oauthGET(categoriesUri, (err, result, response) => {        
        //gオプション(?)で一致部分を全て取得し配列に格納
        const regExp = new RegExp('category term=\".*\"', "g");
        const _categoryArray = (result as string).match(regExp);
        if (_categoryArray !== null) {
            _categoryArray.forEach((value, index, array) => {
                const _category = value.match('category term=\"(.*)\"');
                if (_category !== null){
                    console.log(_category[1]);
                }
            });
        }
    });
}

/**
* Wrapper of oauth.get method.
* @param uri 
* @param callback 
*/
private oauthGET(uri: string, callback: OAuth.dataCallback) {
    this.oauth.get(uri, this.accessToken.token, this.accessToken.secret, callback);
}

なお生のレスポンスは次のような感じ(はてなブログAtomPub - Hatena Developer Center)。

<?xml version="1.0" encoding="utf-8"?>
<app:categories
    xmlns:app="http://www.w3.org/2007/app"
    xmlns:atom="http://www.w3.org/2005/Atom"
    fixed="no">
  <atom:category term="Perl" />
  <atom:category term="Scala" />
  ...
</app:categories>

xml-jsモジュールで JSON として扱った方が楽…??(やってない)