Astro 세션 드라이버 API
Astro 세션을 사용하면 온디맨드로 렌더링된 페이지의 요청 간에 데이터를 공유할 수 있습니다. 세션 데이터를 저장하려면 Astro 세션 드라이버가 필요합니다.
기본 제공 드라이버
섹션 제목: “기본 제공 드라이버”Astro는 astro/config에서 기본 제공 세션 드라이버를 내보냅니다.
import { sessionDrivers } from 'astro/config'모든 unstorage 드라이버를 사용할 수 있습니다. 예를 들면 다음과 같습니다.
import { defineConfig, sessionDrivers } from 'astro/config'
export default defineConfig({ session: { driver: sessionDrivers.redis({ url: process.env.REDIS_URL }), }})일부 드라이버는 추가 패키지를 설치해야 할 수도 있습니다. 또한 일부 드라이버는 환경 변수나 자격 증명을 설정해야 할 수도 있습니다. 자세한 내용은 Unstorage 문서를 참조하세요.
세션 드라이버 빌드하기
섹션 제목: “세션 드라이버 빌드하기”세션 드라이버는 두 부분으로 구성됩니다.
세션 드라이버 설정
섹션 제목: “세션 드라이버 설정”SessionDriverConfig는 필수 런타임 entrypoint와 선택적 config를 포함하는 객체입니다. 이를 구현하는 선호되는 방법은 이 객체를 반환하고 설정을 선택적 매개변수로 받는 함수를 내보내는 것입니다.
다음 예시는 메모리 드라이버 설정을 정의합니다.
import type { SessionDriverConfig } from 'astro'
export interface Config { max?: number;}
export function memoryDriver(config: Config = {}): SessionDriverConfig { return { entrypoint: new URL('./runtime.js', import.meta.url), config, }}그 다음 Astro 설정에 등록합니다.
import { defineConfig } from 'astro/config'import { memoryDriver } from './driver/config'
export default defineConfig({ session: { driver: memoryDriver({ max: 500 }) }})entrypoint
섹션 제목: “entrypoint”타입: string | URL
astro@6.0.0
새로운 기능
드라이버 구현을 위한 진입점을 정의합니다.
config
섹션 제목: “config”타입: Record<string, any> | undefined
astro@6.0.0
새로운 기능
런타임에 드라이버 구현으로 전달되는 직렬화 가능한 설정을 정의합니다.
세션 드라이버 구현
섹션 제목: “세션 드라이버 구현”SessionDriver는 런타임에 세션을 사용할 때 (예: context.session.set()) 데이터를 저장, 조회 및 삭제하는 역할을 담당하는 객체입니다. 세션 드라이버 모듈에서 드라이버 설정을 매개변수로 받는 기본 함수를 내보내어 구현할 수 있습니다.
다음 예시는 메모리 드라이버를 구현합니다.
import type { SessionDriver } from 'astro'import type { Config } from './config'import { LRUCache } from 'lru-cache'
export default function(config: Config): SessionDriver { const cache = new LRUCache({ max: config.max }) return { setItem: async (key, value) => { cache.set(key, value) }, getItem: async (key) => { return cache.get(key) }, removeItem: async (key) => { cache.delete(key) }, }}setItem()
섹션 제목: “setItem()”타입: (key: string, value: any) => Promise<void>
astro@6.0.0
새로운 기능
키별로 세션 데이터를 설정하는 함수를 정의합니다.
getItem()
섹션 제목: “getItem()”타입: (key: string) => Promise<any>
astro@6.0.0
새로운 기능
키별로 세션 데이터를 조회하는 함수를 정의합니다.
removeItem()
섹션 제목: “removeItem()”타입: (key: string) => Promise<void>
astro@6.0.0
새로운 기능
키별로 세션 데이터를 제거하는 함수를 정의합니다.
Unstorage 호환성
섹션 제목: “Unstorage 호환성”Unstorage 드라이버 타입은 Astro의 SessionDriver 타입과 호환됩니다.
즉, unstorage 패키지 내보내기를 진입점으로 사용할 수 있습니다. 예를 들면 다음과 같습니다.
import type { SessionDriverConfig } from 'astro'
export function configuredRedisDriver(): SessionDriverConfig { return { entrypoint: 'unstorage/drivers/redis', config: { tls: true } }}또는 구현부에서 unstorage 드라이버를 직접 가져와서 사용할 수도 있습니다. 예를 들면 다음과 같습니다.
import type { SessionDriver } from 'astro'import redisDriver from "unstorage/drivers/redis";
export default function(config): SessionDriver { return redisDriver({ ...config, tls: true })}