Astro Session Driver API
Astroのセッションを使用すると、オンデマンドでレンダリングされるページの型間でデータを共有できます。これには、セッションデータを保存するためのAstroセッションドライバーが必要です。
ビルトインドライバー
Section titled “ビルトインドライバー”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のドキュメントを参照してください。
セッションドライバーの構築
Section titled “セッションドライバーの構築”セッションドライバーは、次の2つの要素で構成されます。
セッションドライバーの設定
Section titled “セッションドライバーの設定”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
Section titled “entrypoint”型: string | URL
astro@6.0.0
ドライバーの実装のためのエントリポイントを定義します。
config
Section titled “config”型: Record<string, any> | undefined
astro@6.0.0
実行時にドライバーの実装に渡される、シリアライズ可能な設定を定義します。
セッションドライバーの実装
Section titled “セッションドライバーの実装”SessionDriverは、実行時にセッションを使用する (EN)際(例: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()
Section titled “setItem()”型: (key: string, value: any) => Promise<void>
astro@6.0.0
キーによってセッションデータを設定する関数を定義します。
getitem()
Section titled “getitem()”型: (key: string) => Promise<any>
astro@6.0.0
キーによってセッションデータを取得する関数を定義します。
removeItem()
Section titled “removeItem()”型: (key: string) => Promise<void>
astro@6.0.0
キーによってセッションデータを削除する関数を定義します。
Unstorageとの互換性
Section titled “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 })}