LoginSignup
0
1

More than 5 years have passed since last update.

Serverless FrameworkでWordPressの記事一覧を表示するページを作る

Last updated at Posted at 2016-12-28

Serverless Frameworkでwebページを作るの続きです。

できたもの

スクリーンショット 2016-12-29 0.07.41.png
ソースコード:https://github.com/hideokamoto/sls-wordpress-frontend

ライブラリのインストール

node-wpapiというsuperagentのラッパーライブラリがありますので、それを使います。WP APIの開発にも関わってる方が作られたライブラリなので、WP APIで何かしたい時はとりあえずこのライブラリ使っとくと重宝します。

$ npm install --save wpapi

node_moduleをLambda同梱する必要があるので、以下のようにして指定しておきましょう。

serverless.yml
package:
  include:
    - node_modules/

LambdaからWP APIをコールする

以下のようにして、WPAPIオブジェクトにWP APIエンドポイントを指定後、posts()メソッドで投稿を取得します。Promiseに対応しているので、thenとcachで処理しちゃいましょう。

index.js
module.exports.index = (event, context, callback) => {
    const wp = new WPAPI({ endpoint: 'http://wp-kyoto.net/wp-json' });
    wp.posts().then(function( data ) {
      const renderedContent = createListHtml(data)
      const renderedPage = renderFullPage( renderedContent, data );
      callback(null, renderedPage);
    }).catch(function( err ) {
        callback(err);
    });
};

あとは取得した値をHTMLに押し込んで、callbackの第二引数に渡せばOKです。

API Gateway側の設定

API GatewayはデフォルトだとJSONを返すようになっているので、レスポンスヘッダーを書き換えます。

serverless.yml
functions:
  index:
    handler: src/index.index
    events:
      - http:
          path: v1
          method: get
          integration: lambda
          response:
            headers:
              Content-Type: "'text/html'"
            template: $input.path('$')

ここまで実施した後、sls deployすればAPIエンドポイントが表示されますので、動作確認しておきましょう。

NEXT:React ServerSide Rendering

Apexでは既にトライ済ですが、Serverless Frameworkではまだなのでこちらもやってみます。

Serverless Webpack の使い方まとめという記事が幸いにもこの間出てきたばかりなので、これを参考にwebpackでやる予定。

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