LoginSignup
1
0

More than 5 years have passed since last update.

Stripe webhookの処理にResolverを試してみた覚書

Last updated at Posted at 2018-12-11

初めて試したので、忘れないようにメモ。

やりたいこと

webhookのtypeに応じて使うクラスを変えたい

試したこと

ask-sdk v2にも使われているResolverを入れてみた。

参考

https://speakerdeck.com/hidenorigoto/sok-solidfalseyuan-ze-tutedonnahuunishi-ufalse-opunkurozudofalseyuan-ze-senpaifalsekodeingufalsetobian
https://qiita.com/shinichi-takahashi/items/7191d3d393e08b2746f0

Resolver

class Resolver {
  constructor () {
    this.updater = []
    this.set(this.getArgs(arguments))
  }
  getArgs (arg) {
    return Array.prototype.slice.call(arg, 0)
  }
  set (updaters) {
    this.updater = updaters
  }
  setUpdaters () {
    this.set(this.getArgs(arguments))
  }
  addUpdater (updater) {
    this.updater.push(updater)
  }
  resolve (type) {
    const target = this.updater.filter(updater => updater.supports(type))
    if (target.length < 1) throw new Error(`Unsupported webhook type: ${type}`)
    return target[0]
  }
}

constructorsetUpdaterで一括登録が可能。
addUpdaterで後から追加可能。

resolveされる側

class CustomerInfoUpdater {
  supports (type) {
    return type === 'customer.created' || type === 'customer.updated'
  }
  process () {
    return 'customer'
  }
}
class SubscriptionInfoUpdater {
  supports (type) {
    return type === 'customer.subscription.created' || type === 'customer.subscription.updated' || type === 'customer.subscription.deleted'
  }
  process () {
    return 'subscription'
  }
}

class InvoiceInfoUpdater {
  supports (type) {
    return type === 'invoice.payment_succeeded'
  }
  process () {
    return 'invoice'
  }
}

それぞれsupportsで指定しているwebhookのtypeの時に、processで処理を実行するという想定です。

組み合わせる

try {
  const resolver = new Resolver(
    new CustomerInfoUpdater(),
    new SubscriptionInfoUpdater(),
    new InvoiceInfoUpdater()
  )
  const t1 = resolver.resolve('customer.updated')
  console.log(t1.process())
  const t2 = resolver.resolve('customer.subscription.created')
  console.log(t2.process())
  const t3 = resolver.resolve('invoice.payment_succeeded')
  console.log(t3.process())
  const t4 = resolver.resolve('hoge')
  console.log(t4.process())
} catch (e) {
  console.log(`[ERROR!] ${e.message}`)
}

実行結果がこちら

$ node test.js
customer
subscription
invoice
[ERROR!] Unsupported webhook type: hoge

ちゃんと対応するメソッドが実行されてますね。

この後

既存のソース側でTypeScriptのビルドが事故る現象があったので、interfaceなどの実装は先送り。
新規のPJなどであればTypeScriptでもうちょっといい感じにしていきたい。

1
0
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
0