LoginSignup
0
0

More than 3 years have passed since last update.

Netlify Functions で API の URL を rewrite する

Last updated at Posted at 2020-04-02

はじめに

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';

function parseQueryArgs(rewriteUrl, urlpath, format) {
    const parse = Path.createPath(rewriteUrl).test(urlpath);
    let result = {};
    for(const key in format) {
        if(parse && parse[key]) {
            result[key] = parse[key];
        } else {
            // default value
            result[key] = format[key]
        }
    }

    return result;
}

exports.handler = async (event) => {
    const args = 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

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