STEP6: REST API で Create

このステップでは、ブックマーク新規作成APIの実装方法と、MeteorクライアントからAPI経由でブックマーク作成する方法について学びます。

6.1 ブックマーク新規作成API実装

ブックマークリソースを作成するAPIを実装していきましょう。

rest.js の Api.addRoute('bookmarks',{ ... }) 内にpostオブジェクトを追加します。

imports/api/rest.js

// ...省略

Api.addRoute('bookmarks', { 
  // GET /api/bookmarks 
  get: { 
    action: function() { 
      return { 
        status: 'success', 
        data: Bookmarks.find().fetch(), 
      }; 
    }, 
  }, 
  // POST /api/bookmarks 
  post: { 
    action: function() { 
      const { url, title } = this.bodyParams; 
      const bookmark = { 
        url, 
        title, 
        createdAt: new Date(), 
      }; 
      const res = Bookmarks.insert(bookmark);
      return { 
        status: 'success', 
        data: Bookmarks.findOne(res), 
      }; 
    }, 
  },
});

// GET /api/bookmarks/:id
Api.addRoute('bookmarks/:id', {
  //... 省略
});

export default Api;

変更を保存したら、ターミナルで以下のコマンドを実行します。

$ curl -X POST http://localhost:3000/api/bookmarks -d "url=http://yahoo.co.jp/" -d "title=Yahoo! Japan"

以下のようなJSONレスポンスが返ってこれば成功です。

{ 
  "status": "success", 
  "data": { 
    "_id": "rF22BNyfcoQE5wBMc", 
    "url": "http://yahoo.co.jp/", 
    "title": "Yahoo! Japan", 
    "createdAt": "2016-07-22T22:57:15.329Z" 
  }
}

また、Webブラウザで http://localhost:3000/ にアクセスすると、新しいブックマークが追加されているのが確認できます。

ここまでのコード: https://github.com/j-hack/meteor-rest-app/tree/step6.1

6.2 ブックマーク追加フォーム作成

続いて、ブックマーク追加フォームを作成します。

ソースコードを以下のように修正します。

client/main.html

<head> 
  <!-- 省略 -->
</head>

<body> 
  <div class="container"> 
    <h1>Bookmarks</h1> 
    {{> BookmarkForm}} <!-- ←追加 --> 
    {{> Bookmarks}} 
  </div>
</body>

<template name="Bookmarks">
  <!-- 省略 -->
</template>

<template name="Bookmark">
  <!-- 省略 -->
</template>

<!-- ↓追加 -->
<template name="BookmarkForm">
  <form class="form-inline bookmark-form">
    <div class="form-group">
      <label for="url">URL</label>
      <input type="url" class="form-control" id="url" name="url" placeholder="http://..." /> 
    </div> 
    <div class="form-group"> 
      <label for="title">Title</label> 
      <input type="text" class="form-control" id="title" name="title" />
    </div>
    <button type="submit" class="btn btn-default">Add</button> 
  </form>
</template>

client/main.js

// ...省略

Template.Bookmarks.onCreated(function() { 
  // ...省略
});

Template.Bookmarks.helpers({ 
  // ...省略
});

// 追加
Template.BookmarkForm.events({ 
  'submit .bookmark-form'(event) { 
    event.preventDefault();

    const url = event.target.url.value; 
    const title = event.target.title.value; 
    const callOptions = {data: {url, title}};

    HTTP.post('/api/bookmarks', callOptions, (err, res) => { 
      if (err) { console.log(err); return; } 
      event.target.url.value = ""; 
      event.target.title.value = ""; 
    }); 
  },
});

NOTE: HTTP.post() で指定したリソースに対してPOSTリクエストを実行します。

変更を保存して、Webブラウザで http://localhost:3000/ を確認します。

フォームにURLとタイトルを入力して、「Add」ボタンを実行するとブックマークが追加されます。

NOTE: ポーリングの関係で画面に反映されるのに少々タイムラグが発生します。

これでAPI経由でブックマークを追加することができるようになりました。

ここまでのコード: https://github.com/j-hack/meteor-rest-app/tree/step6.2

次のステップに進みましょう。

results matching ""

    No results matching ""