LoginSignup
11
12

More than 5 years have passed since last update.

HapiでWebhookを受ける側のカンタンなサーバーをたてる

Posted at

Webhookサーバーって言い方があってるのか分からないんですけど、SlackとかIFTTTとかGithubとかBibbutkcetとかのWebサービスからのWebhookを受け付けるサーバーです。

BitbucketやGithubにPUSHしたらサーバー側で自動PULLするNode.jsでのミニマム構成とかでやってるやつですね。このときの実装はとりあえずサーバーにリクエストがあったら処理をするって流れでしたが、送られてきたデータによってハンドリングは出来てませんでした。

環境と準備

  • node.js 5.9.1
  • hapi 13.2.2
$ npm i hapi

POSTのWebhookサーバー

こんな感じのコードで実現できます。 request.payloadを表示させるようにします。

app.js
'use strict'

const Hapi = require('hapi');
const server = new Hapi.Server();

server.connection({port: 8124});
server.route({
  method: 'POST',
  path:'/',
  handler: (request, reply) => {
    reply().code(204);
    console.log(request.payload);
    console.log('-------\n');
  }
});

server.start(() => {
  console.log('Server running at:', server.info.uri);
});
  • 実行する
$ node app.js
Server running at: http://localhost:8124

localhost:8124でwebhookサーバーが立ち上がるので、この待ち受け状態で別ターミナルでcurlでPOSTリクエストを送って試してみます。

$ curl --data "response=true" http://localhost:8124/

送信すると以下のように{ response: 'true' }のオブジェクトが表示されます。

$ node app.js
Server running at: http://localhost:8124
{ response: 'true' }
-------

あとはデータをうまく加工して使ってみましょう。

GETのWebhookサーバー

基本はPOST版と一緒です。 methodの値はGETで、request.queryで値が取得できます。

app.js
#省略

server.route({
  method: 'GET',
  path:'/',
  handler: (request, reply) => {
    reply().code(204);
    console.log(request.query);
    console.log('-------\n');
  }
});

#省略
  • 実行する

基本はPOSTと同じです。 curl側は以下のように送ります。

$ curl http://localhost:8124?response=true

まとめ

割と簡単に実現できました。
あとはGithubだったりIFTTTだったりとつなげてあげましょう。

色々なサービスからWebhookでJSONデータが送られてくるのですが、Node.jsで受け口を作って情報を加工したいなと思った時にexpressで試している人は多かったのですがHapiでやってる例は少なさそうな印象でした。

最近Hapiが好きなのでHapi使う人増えるといいなぁ。

11
12
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
11
12