키 값 저장소의 키 값 페어를 함수에 사용할 수 있습니다.
이 예제는 HTTP 요청의 URL 콘텐츠를 사용하여 키 값 저장소에서 사용자 지정 경로를 조회하는 함수를 보여줍니다. 그런 다음 CloudFront는 해당 사용자 지정 경로를 사용하여 요청을 만듭니다. 이 함수는 웹사이트에 속하는 여러 경로를 관리하는 데 도움이 됩니다.
예를 들어 이전 블로그의 오리진 경로가 /blog-v1
이었고 새 블로그의 오리진 경로가 /blog-v2
인 경우, 이 함수는 수신 요청의 URL 경로를 조회하여 해당 URL 경로 (/blog-v1)
을 새 버전의 블로그 (/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;
}