Serverless Frameworkでwebページを作るの続きです。
できたもの
ソースコード:https://github.com/hideokamoto/sls-wordpress-frontend
ライブラリのインストール
node-wpapiというsuperagentのラッパーライブラリがありますので、それを使います。WP APIの開発にも関わってる方が作られたライブラリなので、WP APIで何かしたい時はとりあえずこのライブラリ使っとくと重宝します。
$ npm install --save wpapi
node_moduleをLambda同梱する必要があるので、以下のようにして指定しておきましょう。
package:
include:
- node_modules/
LambdaからWP APIをコールする
以下のようにして、WPAPIオブジェクトにWP APIエンドポイントを指定後、posts()
メソッドで投稿を取得します。Promiseに対応しているので、thenとcachで処理しちゃいましょう。
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を返すようになっているので、レスポンスヘッダーを書き換えます。
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でやる予定。