Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ When you need more control over the pipeline order, or want to omit certain feat
```ts title="src/app.ts"
import {
FetchState,
sessions,
actions,
middleware,
pages,
Expand All @@ -125,16 +124,12 @@ import {
export default {
async fetch(request: Request): Promise<Response> {
const state = new FetchState(request);
await sessions(state);
try {
const actionResponse = await actions(state);
if (actionResponse) return actionResponse;

const response = await middleware(state, (s) => pages(s));
return i18n(state, response);
} finally {
await state.finalizeAll();
}

const actionResponse = await actions(state);
if (actionResponse) return actionResponse;

const response = await middleware(state, (s) => pages(s));
return i18n(state, response);
},
};
```
Expand Down Expand Up @@ -172,20 +167,6 @@ export default {
};
```

## Typing custom providers with `App.Providers`

When you register custom context providers with [`state.provide()`](#stateprovide), you can declare their types using the `App.Providers` interface so that `Astro` and `ctx` are fully typed in your components and middleware:

```ts title="src/env.d.ts"
declare namespace App {
interface Providers {
oauth: import('./lib/oauth').OAuthSession;
}
}
```

After declaring a provider, `ctx.oauth` (and `Astro.oauth` in `.astro` files) will be typed automatically.

## `astro/fetch` handler reference

All handler functions are imported from `astro/fetch` and operate on a `FetchState` object.
Expand Down Expand Up @@ -286,54 +267,6 @@ Triggers a [rewrite](/en/guides/routing/#rewrites) to a different route. The `pa
const response = await state.rewrite('/other-page');
```

##### `state.provide()`

<p>

**Type:** `(key: string, provider: ContextProvider<T>) => void`
</p>

Registers a context provider under the given key. The provider's `create()` function is called lazily on the first [`state.resolve()`](#stateresolve), and its optional `finalize()` callback runs during [`state.finalizeAll()`](#statefinalizeall):

```ts
state.provide('myService', {
create: () => new MyService(),
finalize: (service) => service.close(),
});
```

##### `state.resolve()`

<p>

**Type:** `(key: string) => T | undefined`
</p>

Returns the value for a previously registered provider, calling its `create` function on first access. Returns `undefined` if no provider was registered for the key:

```ts
const service = state.resolve('myService');
```

##### `state.finalizeAll()`

<p>

**Type:** `() => Promise<void> | void`
</p>

Runs all registered provider `finalize` callbacks. Call this after the response is produced, typically in a `finally` block, to persist session data and clean up resources:

```ts
await sessions(state);
try {
// ...render pipeline...
return response;
} finally {
await state.finalizeAll();
}
```

### `astro()`

<p>
Expand Down Expand Up @@ -401,15 +334,11 @@ if (actionResponse) return actionResponse;
**Type:** <code>(state: <a href="#fetchstate">FetchState</a>) => Promise\<void\> | void</code>
</p>

Registers the [session](/en/guides/sessions/) provider. Sessions are created lazily when your code accesses `ctx.session` and persisted when `state.finalizeAll()` is called. Call this early in the pipeline, and call `finalizeAll()` in a `finally` block:
Registers the [session](/en/guides/sessions/) provider. Sessions are created lazily when your code accesses `ctx.session` and persisted automatically at the end of the request. Call this early in the pipeline (before middleware runs):

```ts
await sessions(state);
try {
// ...render pipeline...
} finally {
await state.finalizeAll();
}
// ...render pipeline...
```

### `i18n()`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ Lorsque vous avez besoin de plus de contrôle sur l'ordre du pipeline, ou si vou
```ts title="src/app.ts"
import {
FetchState,
sessions,
actions,
middleware,
pages,
Expand All @@ -125,16 +124,12 @@ import {
export default {
async fetch(request: Request): Promise<Response> {
const state = new FetchState(request);
await sessions(state);
try {
const actionResponse = await actions(state);
if (actionResponse) return actionResponse;

const response = await middleware(state, (s) => pages(s));
return i18n(state, response);
} finally {
await state.finalizeAll();
}

const actionResponse = await actions(state);
if (actionResponse) return actionResponse;

const response = await middleware(state, (s) => pages(s));
return i18n(state, response);
},
};
```
Expand Down Expand Up @@ -172,20 +167,6 @@ export default {
};
```

## Définition du type des fournisseurs personnalisés avec `App.Providers`

Lorsque vous enregistrez des fournisseurs de contexte personnalisés avec [`state.provide()`](#stateprovide), vous pouvez déclarer leurs types en utilisant l'interface `App.Providers` afin que `Astro` et `ctx` soient entièrement typés dans vos composants et middleware :

```ts title="src/env.d.ts"
declare namespace App {
interface Providers {
oauth: import('./lib/oauth').OAuthSession;
}
}
```

Après avoir déclaré un fournisseur, `ctx.oauth` (et `Astro.oauth` dans les fichiers `.astro`) sera typé automatiquement.

## Référence des gestionnaires d'`astro/fetch`

Toutes les fonctions de gestion sont importées depuis `astro/fetch` et opèrent sur un objet `FetchState`.
Expand Down Expand Up @@ -286,54 +267,6 @@ Déclenche une [réécriture](/fr/guides/routing/#réécritures) vers une autre
const response = await state.rewrite('/autre-page');
```

##### `state.provide()`

<p>

**Type :** `(key: string, provider: ContextProvider<T>) => void`
</p>

Enregistre un fournisseur de contexte sous le nom de propriété donné. La fonction `create()` du fournisseur est appelée de manière paresseuse lors du premier [`state.resolve()`](#stateresolve), et son rappel optionnel `finalize()` s'exécute lors de [`state.finalizeAll()`](#statefinalizeall) :

```ts
state.provide('monService', {
create: () => new MonService(),
finalize: (service) => service.close(),
});
```

##### `state.resolve()`

<p>

**Type :** `(key: string) => T | undefined`
</p>

Renvoie la valeur d'un fournisseur précédemment enregistré, en appelant sa fonction `create` lors du premier accès. Renvoie `undefined` si aucun fournisseur n'a été enregistré pour le nom de propriété :

```ts
const service = state.resolve('monService');
```

##### `state.finalizeAll()`

<p>

**Type :** `() => Promise<void> | void`
</p>

Exécute tous les rappels `finalize` des fournisseurs enregistrés. Appelez ceci après que la réponse a été produite, généralement dans un bloc `finally`, pour persister les données de session et nettoyer les ressources :

```ts
await sessions(state);
try {
// ...pipeline de rendu...
return response;
} finally {
await state.finalizeAll();
}
```

### `astro()`

<p>
Expand Down Expand Up @@ -401,15 +334,11 @@ if (actionResponse) return actionResponse;
**Type :** <code>(state: <a href="#fetchstate">FetchState</a>) => Promise\<void\> | void</code>
</p>

Enregistre le fournisseur de [sessions](/fr/guides/sessions/). Les sessions sont créées de manière paresseuse lorsque votre code accède à `ctx.session` et sont persistées lorsque `state.finalizeAll()` est appelé. Appelez ceci tôt dans le pipeline, et appelez `finalizeAll()` dans un bloc `finally` :
Enregistre le fournisseur de [sessions](/fr/guides/sessions/). Les sessions sont créées de manière paresseuse lorsque votre code accède à `ctx.session` et sont persistées automatiquement à la fin de la requête. Appelez ceci tôt dans le pipeline (avant l'exécution du middleware) :

```ts
await sessions(state);
try {
// ...pipeline de rendu...
} finally {
await state.finalizeAll();
}
// ...pipeline de rendu...
```

### `i18n()`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ export default {
```ts title="src/app.ts"
import {
FetchState,
sessions,
actions,
middleware,
pages,
Expand All @@ -125,16 +124,12 @@ import {
export default {
async fetch(request: Request): Promise<Response> {
const state = new FetchState(request);
await sessions(state);
try {
const actionResponse = await actions(state);
if (actionResponse) return actionResponse;

const response = await middleware(state, (s) => pages(s));
return i18n(state, response);
} finally {
await state.finalizeAll();
}

const actionResponse = await actions(state);
if (actionResponse) return actionResponse;

const response = await middleware(state, (s) => pages(s));
return i18n(state, response);
},
};
```
Expand Down Expand Up @@ -172,20 +167,6 @@ export default {
};
```

## `App.Providers`를 사용하여 사용자 정의 프로바이더 타입 지정하기

[`state.provide()`](#stateprovide)를 사용하여 사용자 정의 컨텍스트 프로바이더를 등록할 때, `App.Providers` 인터페이스를 사용하여 해당 타입을 선언할 수 있습니다. 이를 통해 컴포넌트와 미들웨어에서 `Astro`와 `ctx`의 타입이 완벽하게 지정됩니다:

```ts title="src/env.d.ts"
declare namespace App {
interface Providers {
oauth: import('./lib/oauth').OAuthSession;
}
}
```

프로바이더를 선언하면 `ctx.oauth` (및 `.astro` 파일의 `Astro.oauth`)의 타입이 자동으로 지정됩니다.

## `astro/fetch` 핸들러 참조

모든 핸들러 함수는 `astro/fetch`에서 가져오며 `FetchState` 객체를 기반으로 동작합니다.
Expand Down Expand Up @@ -286,54 +267,6 @@ const response = await middleware(state, (s) => pages(s));
const response = await state.rewrite('/other-page');
```

##### `state.provide()`

<p>

**타입:** `(key: string, provider: ContextProvider<T>) => void`
</p>

지정된 키 아래에 컨텍스트 프로바이더를 등록합니다. 프로바이더의 `create()` 함수는 [`state.resolve()`](#stateresolve)가 처음 호출될 때 지연 호출되며, 선택적인 `finalize()` 콜백은 [`state.finalizeAll()`](#statefinalizeall) 실행 중 호출됩니다:

```ts
state.provide('myService', {
create: () => new MyService(),
finalize: (service) => service.close(),
});
```

##### `state.resolve()`

<p>

**타입:** `(key: string) => T | undefined`
</p>

이전에 등록된 프로바이더의 값을 반환하며, 첫 접근 시 `create` 함수를 호출합니다. 해당 키로 등록된 프로바이더가 없으면 `undefined`를 반환합니다:

```ts
const service = state.resolve('myService');
```

##### `state.finalizeAll()`

<p>

**타입:** `() => Promise<void> | void`
</p>

등록된 모든 프로바이더의 `finalize` 콜백을 실행합니다. 세션 데이터를 저장하고 리소스를 정리하기 위해 일반적으로 `finally` 블록에서 응답 생성 후 이 메서드를 호출합니다:

```ts
await sessions(state);
try {
// ...렌더 파이프라인...
return response;
} finally {
await state.finalizeAll();
}
```

### `astro()`

<p>
Expand Down Expand Up @@ -401,15 +334,11 @@ if (actionResponse) return actionResponse;
**타입:** <code>(state: <a href="#fetchstate">FetchState</a>) => Promise\<void\> | void</code>
</p>

[세션](/ko/guides/sessions/) 프로바이더를 등록합니다. 세션은 코드에서 `ctx.session`에 접근할 때 지연 생성되며, `state.finalizeAll()`이 호출될 때 저장됩니다. 파이프라인 초기에 이를 호출하고, `finally` 블록에서 `finalizeAll()`을 호출하세요:
[세션](/ko/guides/sessions/) 프로바이더를 등록합니다. 세션은 코드에서 `ctx.session`에 접근할 때 지연 생성되며, 요청이 끝날 때 자동으로 저장됩니다. 미들웨어가 실행되기 전에 파이프라인 초기에 이를 호출하세요:

```ts
await sessions(state);
try {
// ...렌더 파이프라인...
} finally {
await state.finalizeAll();
}
// ...렌더 파이프라인...
```

### `i18n()`
Expand Down
Loading