1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

oauth モジュールを Promise でラップしてみた

1
Last updated at Posted at 2019-04-04

何の記事?

oauth モジュールのメソッドを Promise でラップしてみたよ。

oauth モジュールとは

  • OAuth 認証を簡単に実行できる Node.js パッケージ
  • 非同期処理の結果はコールバック形式

なぜラップするのか

  • Cookie 取得や連携許可・拒否画面の操作のため、request-promise モジュールと並行して使用したかった
  • Promise でラップすることで、非同期処理を async/await で統一して記述したかった

実装してみた

oauth.getOAuthRequestTokenoauth.getOAuthAccessTokenをラップしてみます。アクセストークンの取得までなら、使うのはこの二つだけです。

//型エイリアス
type oauthTokenCallback = {
  err: {
    statusCode: number,
    data?: any
  },
  token: string,
  tokenSecret: string,
  query: any
};

//リクエストトークン取得をラップ
const getOAuthRequestToken = (scope: {[key: string]: string}) => 
  new Promise<oauthTokenCallback>((resolve) =>
    this.oauth.getOAuthRequestToken(scope, (err, token, tokenSecret, query) => {
      resolve({err, token, tokenSecret, query});
    }));

//アクセストークン取得をラップ
const getOAuthAccessToken = (requestToken: string, requestTokenSecret: string, verifier: string) => 
    new Promise<oauthTokenCallback>((resolve) => 
      this.oauth.getOAuthAccessToken(requestToken, requestTokenSecret, verifier, (err, token, tokenSecret, query) => {
      resolve({err, token, tokenSecret, query});
    }));

try {
  //次のようにawaitできる
  const requestTokenResult = await getOAuthRequestToken(...);
  console.log(requestTokenResult.token);

  const accessTokenResult = await getOAuthAccessToken(...);
  console.log(accessTokenResult.tokenSecret);

} catch (reason) {
  console.log(reason)
}

最初に、コールバックの型として型エイリアス(oauthTokenCallback)を定義しました。
定義自体は oauth モジュールのOAuth.oauth1tokenCallbackと同じ形です。

実装全体は以下のリポジトリにて。
シングルトンにしちゃってますがそこは見逃してください><

HatenaBlogCode

宣伝

技術書典6で、このネタから生えた本を頒布します。
Visual Studio Code の拡張機能を開発する本です。よしなに。。。

技術書典6 くり返す日常

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?