はじめに
Netlify Functionsで作成する API の URL 形式を 初期設定の /.netlify/functions/example?hoge=10
のような形から /example/10
形式に rewrite する方法です。
netlify.toml の指定
Netlify ではプロジェクトのルートに配置する netlify.toml
で redirect を指定することができます。また、status
を 200
に設定すると redirect ではなく rewrite として機能します。
When you assign an HTTP status code of 200 to a redirect rule, it becomes a rewrite. This means that the URL in the visitor's address bar remains the same, while Netlify's servers fetch the new location behind the scenes.
URL の指定にはプレースホルダーが使えるので、例えば /v1/digit/200/6/123456/
のような URL を ?width=600&digit=6&number=123456
に変換する記述は次のようにかけそうです。
[[redirects]]
from = "/v1/digit/:width/:digit/:number/"
to = "/.netlify/functions/digit/?width=:width&digit=:digit&number=:number"
status = 200
が、残念ながらリライトはされるものの、(2020/4 現在)Lambda エンドポイントの event.queryStringParameters
に値が渡ってきません。
exports.handler=async(event)=>{console.log(event.queryStringParameters);// {}}
Netlify Community にも同件の報告があがっていました。
queryStringParameters not working with redirect on production - Support - Netlify Community
event.path から取得する
Community のほうに event.path
から取得してみてはどうかとありましたので、(悲しいですが)次のように event.path
を path-parser
で URL をパースすることにしました。
import{Path}from'path-parser';functionparseQueryArgs(rewriteUrl,urlpath,format){constparse=Path.createPath(rewriteUrl).test(urlpath);letresult={};for(constkeyinformat){if(parse&&parse[key]){result[key]=parse[key];}else{// default valueresult[key]=format[key]}}returnresult;}exports.handler=async(event)=>{constargs=parseQueryArgs('/v1/digit/:width<\\d+>/:digit<\\d+>/:number<\\d+>/',event.path,{width:160,digit:6,number:12345});// ..snip};
この場合の netlify.toml
は単純に次のようになります。
[[redirects]]
from = "/v1/digit/*"
to = "/.netlify/functions/digit"
status = 200
rewrite が使えないローカル netlify-lambda 環境の考慮も入れた版を github においてあります。
動作サンプル
/v1/digit/幅px/桁数/ナンバー/
として動作します。
https://sample-counter.netlify.com/v1/digit/640/9/123456789/
関連
Netlify Functions で古のアクセスカウンター(アクセサリー)をつくる - Qiita
github リポジトリー