関数でキーと値のペアを使用する - Amazon CloudFront

関数でキーと値のペアを使用する

キー値ストアのキーと値のペアを関数で使用できます。

注記

次のコードサンプルでは JavaScript ランタイム 2.0 を使用する必要があります。

この例は、HTTP リクエスト内の URL の内容を使用してキー値ストア内のカスタムパスを検索する関数を示しています。次に、CloudFront はそのカスタムパスを使用してリクエストを行います。この関数は、ウェブサイトに含まれる複数のパスを管理するのに役立ちます。

import cf from 'cloudfront'; ​ // Declare the ID of the key value store that you have associated with this function // The import fails at runtime if the specified key value store is not associated with the function const kvsId = "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"; ​ const kvsHandle = cf.kvs(kvsId); ​ async function handler(event) { const request = event.request; // Use the first segment of the pathname as key // For example http(s)://domain/<key>/something/else const pathSegments = request.uri.split('/') const key = pathSegments[1] try { // Replace the first path of the pathname with the value of the key // For example http(s)://domain/<value>/something/else pathSegments[1] = await kvsHandle.get(key); const newUri = pathSegments.join('/'); console.log(`${request.uri} -> ${newUri}`) request.uri = newUri; } catch (err) { // No change to the pathname if the key is not found console.log(`${request.uri} | ${err}`); } return request; }