LoginSignup
1
5

More than 3 years have passed since last update.

はじめに

サーバーにWebhookな機能を実装しようと思ってなんかないかなと探してみたらnode-webhooksというのを見つけたのでちょっと簡単に試してみようと思う。

つかってみる

まずはインストールする

npm i -S node-webhooks

POSTする先のサーバーを立ち上げるためにjson-serverをインストールする

npm i -D jsonserver

json-server用の設定ファイルを作成する

db.json
{
  "posts":[
    {"id":1,"title":"this is a test server"}
  ]
}

サンプルコードを作成する

index.js
var WebHooks = require('node-webhooks');

webHooks = new WebHooks({
  db: {"addPost": ["http://localhost:3000/posts"]}
});

webHooks.add('shortname1', 'http://localhost:3000/posts')
  .then(() => {
    console.log('triggerd shortname1');
  }).catch((err) => {
    console.log(err)
  });

webHooks.trigger('shortname1', {title: 'posted from node-webhooks'});

json-serverを起動する

npx json-server --watch db.json

npx: 248個のパッケージを6.449秒でインストールしました。

  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/posts

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

別タブでサンプルコードを実行する

node index.js

triggerd shortname1

json-serverのコンソールにPOSTされたログが出力されている

POST /posts 201 26.041 ms - 53

db.jsonを確認してみる。サンプルコードから投稿されたデータが追加されている

cat db.json | jq .

{
  "posts": [
    {
      "id": 1,
      "title": "this is a test server"
    },
    {
      "title": "posted from node-webhooks",
      "id": 2
    }
  ]
}

感想

コンパクトにまとまっているので使いやすい。自前で実装するのもいいがこれを使ったほうが楽なケースはあるんじゃないだろうか。

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