初めて試したので、忘れないようにメモ。
やりたいこと
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]
}
}
constructor
かsetUpdater
で一括登録が可能。
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でもうちょっといい感じにしていきたい。