Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

Netlify Functions で API の URL を rewrite する

$
0
0

はじめに

Netlify Functionsで作成する API の URL 形式を 初期設定の /.netlify/functions/example?hoge=10のような形から /example/10形式に rewrite する方法です。

netlify.toml の指定

Netlify ではプロジェクトのルートに配置する netlify.tomlで redirect を指定することができます。また、status200に設定すると redirect ではなく rewrite として機能します。

Rewrites and proxies

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.pathpath-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 においてあります。

動作サンプル

Screenshot_2020-04-02 fujilcd.png

/v1/digit/幅px/桁数/ナンバー/として動作します。

https://sample-counter.netlify.com/v1/digit/640/9/123456789/

関連

Netlify Functions で古のアクセスカウンター(アクセサリー)をつくる - Qiita

github リポジトリー

h1romas4/netlify-functions-template


Viewing all articles
Browse latest Browse all 8691

Trending Articles