Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: dynamic initialState #435

Merged
merged 3 commits into from
Jul 24, 2024
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
8 changes: 8 additions & 0 deletions .changeset/twelve-rocks-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"frog": patch
---

Implemented a feature where `initialState` can be a callback receiving Hono's `Context`.

This is particularly useful when dealing with path parameters to dynamically initiate state.
This state will also be accessible in `c.previousState` in the Image Handler.
20 changes: 16 additions & 4 deletions src/frog-base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,10 @@ export type FrogConstructorParameters<
* }
* ```
*/
initialState?: _state | undefined
initialState?:
| ((c: Context<env>) => _state | Promise<_state>)
| _state
| undefined
/**
* Origin URL of the server instance.
*
Expand Down Expand Up @@ -264,7 +267,10 @@ export class FrogBase<
> {
// Note: not using native `private` fields to avoid tslib being injected
// into bundled code.
_initialState: env['State'] = undefined as env['State']
_initialState:
| ((c: Context<env>) => _state | Promise<_state>)
| _state
| undefined = undefined
/** Path for assets. */
assetsPath: string
/** Base path of the server instance. */
Expand Down Expand Up @@ -585,7 +591,10 @@ export class FrogBase<
secret: this.secret,
verify,
}),
initialState: this._initialState,
initialState:
typeof this._initialState === 'function'
? await (this._initialState as any)(c)
: this._initialState,
origin,
})

Expand Down Expand Up @@ -989,7 +998,10 @@ export class FrogBase<
context: await requestBodyToImageContext(c, {
secret: this.secret,
}),
initialState: this._initialState,
initialState:
typeof this._initialState === 'function'
? await (this._initialState as any)(c)
: this._initialState,
})

const response = await handler(context)
Expand Down
2 changes: 1 addition & 1 deletion src/frog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export class Frog<
//
_state = env['State'],
> extends FrogBase<env, schema, basePath, _state> {
constructor(params: FrogConstructorParameters) {
constructor(params: FrogConstructorParameters<env, basePath, _state>) {
super(params as any)

const frame = this.frame
Expand Down
Loading