Skip to content

Commit

Permalink
feat: dynamic initialState (#435)
Browse files Browse the repository at this point in the history
* feat: `initialState` to be derived from `Context`

Useful with path parameters.

* chore: changesets

* nit: support async too
  • Loading branch information
dalechyn authored Jul 24, 2024
1 parent 6ff12c3 commit 43f4205
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
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 @@ -270,7 +273,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 @@ -596,7 +602,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 @@ -1000,7 +1009,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

0 comments on commit 43f4205

Please sign in to comment.