콘텐츠로 이동

Astro 세션 드라이버 API

Astro 세션을 사용하면 온디맨드로 렌더링된 페이지의 요청 간에 데이터를 공유할 수 있습니다. 세션 데이터를 저장하려면 Astro 세션 드라이버가 필요합니다.

Astro는 astro/config에서 기본 제공 세션 드라이버를 내보냅니다.

import { sessionDrivers } from 'astro/config'

모든 unstorage 드라이버를 사용할 수 있습니다. 예를 들면 다음과 같습니다.

astro.config.mjs
import { defineConfig, sessionDrivers } from 'astro/config'
export default defineConfig({
session: {
driver: sessionDrivers.redis({
url: process.env.REDIS_URL
}),
}
})

세션 드라이버는 두 부분으로 구성됩니다.

  • 드라이버 설정: Astro가 런타임에 어떤 구현을 사용할지, 어떤 설정을 전달할지 알려줍니다.
  • 드라이버 구현: 런타임에 스토리지 로직을 처리합니다.

SessionDriverConfig는 필수 런타임 entrypoint와 선택적 config를 포함하는 객체입니다. 이를 구현하는 선호되는 방법은 이 객체를 반환하고 설정을 선택적 매개변수로 받는 함수를 내보내는 것입니다.

다음 예시는 메모리 드라이버 설정을 정의합니다.

driver/config.ts
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 설정에 등록합니다.

astro.config.ts
import { defineConfig } from 'astro/config'
import { memoryDriver } from './driver/config'
export default defineConfig({
session: {
driver: memoryDriver({
max: 500
})
}
})

타입: string | URL

추가된 버전: astro@6.0.0 새로운 기능

드라이버 구현을 위한 진입점을 정의합니다.

타입: Record<string, any> | undefined

추가된 버전: astro@6.0.0 새로운 기능

런타임에 드라이버 구현으로 전달되는 직렬화 가능한 설정을 정의합니다.

SessionDriver런타임에 세션을 사용할 때 (예: context.session.set()) 데이터를 저장, 조회삭제하는 역할을 담당하는 객체입니다. 세션 드라이버 모듈에서 드라이버 설정을 매개변수로 받는 기본 함수를 내보내어 구현할 수 있습니다.

다음 예시는 메모리 드라이버를 구현합니다.

driver/runtime.ts
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)
},
}
}

타입: (key: string, value: any) => Promise<void>

추가된 버전: astro@6.0.0 새로운 기능

키별로 세션 데이터를 설정하는 함수를 정의합니다.

타입: (key: string) => Promise<any>

추가된 버전: astro@6.0.0 새로운 기능

키별로 세션 데이터를 조회하는 함수를 정의합니다.

타입: (key: string) => Promise<void>

추가된 버전: astro@6.0.0 새로운 기능

키별로 세션 데이터를 제거하는 함수를 정의합니다.

Unstorage 드라이버 타입은 Astro의 SessionDriver 타입과 호환됩니다.

즉, unstorage 패키지 내보내기를 진입점으로 사용할 수 있습니다. 예를 들면 다음과 같습니다.

driver/config.ts
import type { SessionDriverConfig } from 'astro'
export function configuredRedisDriver(): SessionDriverConfig {
return {
entrypoint: 'unstorage/drivers/redis',
config: {
tls: true
}
}
}

또는 구현부에서 unstorage 드라이버를 직접 가져와서 사용할 수도 있습니다. 예를 들면 다음과 같습니다.

driver/runtime.ts
import type { SessionDriver } from 'astro'
import redisDriver from "unstorage/drivers/redis";
export default function(config): SessionDriver {
return redisDriver({
...config,
tls: true
})
}
기여하기 커뮤니티 후원하기