在函數中使用鍵值對 - Amazon CloudFront

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

在函數中使用鍵值對

您可以在函數中使用鍵值存儲中的鍵值對。

此範例顯示的函數會使用HTTP要求URL中的內容來查詢索引鍵值存放區中的自訂路徑。 CloudFront 然後使用該自定義路徑發出請求。此函數有助於管理屬於網站一部分的多個路徑。

例如,如果先前的部落格具有來源路徑,/blog-v1而新的部落格具有來源路徑/blog-v2,則此函數可以查詢傳入要求的路URL徑,並(/blog-v1)將URL路徑重新寫入新版本的部落格(/blog-v2)

注意

下列程式碼範例必須使用 JavaScript 執行階段 2.0。

import cf from 'cloudfront'; // This fails if there is no key value store associated with the function const kvsHandle = cf.kvs(); // Remember to associate the KVS with your function before referencing KVS in your code. // https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/kvs-with-functions-associate.html 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; }