Compare commits
1 Commits
948de593f0
...
9d35e8eef3
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d35e8eef3 |
5
bun.lock
5
bun.lock
@@ -17,9 +17,6 @@
|
||||
"packages/effect-fc": {
|
||||
"name": "effect-fc",
|
||||
"version": "0.2.1",
|
||||
"devDependencies": {
|
||||
"@effect/platform-browser": "^0.74.0",
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^19.2.0",
|
||||
"effect": "^3.19.0",
|
||||
@@ -658,8 +655,6 @@
|
||||
|
||||
"anymatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"effect-fc/@effect/platform-browser": ["@effect/platform-browser@0.74.0", "", { "dependencies": { "multipasta": "^0.2.7" }, "peerDependencies": { "@effect/platform": "^0.94.0", "effect": "^3.19.13" } }, "sha512-PAgkg5L5cASQpScA0SZTSy543MVA4A9kmpVCjo2fCINLRpTeuCFAOQHgPmw8dKHnYS0yGs2TYn7AlrhhqQ5o3g=="],
|
||||
|
||||
"readdirp/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"recast/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "effect-fc",
|
||||
"description": "Write React function components with Effect",
|
||||
"version": "0.2.2",
|
||||
"version": "0.2.1",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"./README.md",
|
||||
@@ -37,9 +37,6 @@
|
||||
"clean:dist": "rm -rf dist",
|
||||
"clean:modules": "rm -rf node_modules"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/platform-browser": "^0.74.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^19.2.0",
|
||||
"effect": "^3.19.0",
|
||||
|
||||
@@ -35,8 +35,6 @@ extends Pipeable.Pipeable {
|
||||
field<const P extends PropertyPath.Paths<I>>(
|
||||
path: P
|
||||
): Effect.Effect<FormField<PropertyPath.ValueFromPath<A, P>, PropertyPath.ValueFromPath<I, P>>>
|
||||
|
||||
readonly run: Effect.Effect<void>
|
||||
readonly submit: Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>, Cause.NoSuchElementException>
|
||||
}
|
||||
|
||||
@@ -70,7 +68,7 @@ extends Pipeable.Class() implements Form<A, I, R, MA, ME, MR, MP> {
|
||||
Option.isSome(value) &&
|
||||
Option.isNone(error) &&
|
||||
Option.isNone(validationFiber) &&
|
||||
!(Result.isRunning(result) || Result.hasRefreshingFlag(result))
|
||||
!(Result.isRunning(result) || Result.isRefreshing(result))
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -91,49 +89,7 @@ extends Pipeable.Class() implements Form<A, I, R, MA, ME, MR, MP> {
|
||||
)
|
||||
}
|
||||
|
||||
readonly canSubmit: Subscribable.Subscribable<boolean>
|
||||
|
||||
get run(): Effect.Effect<void> {
|
||||
return this.runSemaphore.withPermits(1)(Stream.runForEach(
|
||||
this.encodedValue.changes.pipe(
|
||||
Option.isSome(this.debounce) ? Stream.debounce(this.debounce.value) : identity
|
||||
),
|
||||
|
||||
encodedValue => this.validationFiber.pipe(
|
||||
Effect.andThen(Option.match({
|
||||
onSome: Fiber.interrupt,
|
||||
onNone: () => Effect.void,
|
||||
})),
|
||||
Effect.andThen(
|
||||
Effect.forkScoped(Effect.onExit(
|
||||
Schema.decode(this.schema, { errors: "all" })(encodedValue),
|
||||
exit => Effect.andThen(
|
||||
Exit.matchEffect(exit, {
|
||||
onSuccess: v => Effect.andThen(
|
||||
Ref.set(this.value, Option.some(v)),
|
||||
Ref.set(this.error, Option.none()),
|
||||
),
|
||||
onFailure: c => Option.match(Chunk.findFirst(Cause.failures(c), e => e._tag === "ParseError"), {
|
||||
onSome: e => Ref.set(this.error, Option.some(e)),
|
||||
onNone: () => Effect.void,
|
||||
}),
|
||||
}),
|
||||
Ref.set(this.validationFiber, Option.none()),
|
||||
),
|
||||
)).pipe(
|
||||
Effect.tap(fiber => Ref.set(this.validationFiber, Option.some(fiber))),
|
||||
Effect.andThen(Fiber.join),
|
||||
Effect.andThen(value => this.autosubmit
|
||||
? Effect.asVoid(Effect.forkScoped(this.submitValue(value)))
|
||||
: Effect.void
|
||||
),
|
||||
Effect.forkScoped,
|
||||
)
|
||||
),
|
||||
Effect.provide(this.context),
|
||||
),
|
||||
))
|
||||
}
|
||||
readonly canSubmit: Subscribable.Subscribable<boolean, never, never>
|
||||
|
||||
get submit(): Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>, Cause.NoSuchElementException> {
|
||||
return this.value.pipe(
|
||||
@@ -141,7 +97,6 @@ extends Pipeable.Class() implements Form<A, I, R, MA, ME, MR, MP> {
|
||||
Effect.andThen(value => this.submitValue(value)),
|
||||
)
|
||||
}
|
||||
|
||||
submitValue(value: A): Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>> {
|
||||
return Effect.whenEffect(
|
||||
Effect.tap(
|
||||
@@ -203,6 +158,51 @@ export const make = Effect.fnUntraced(function* <A, I = A, R = never, MA = void,
|
||||
)
|
||||
})
|
||||
|
||||
export const run = <A, I, R, MA, ME, MR, MP>(
|
||||
self: Form<A, I, R, MA, ME, MR, MP>
|
||||
): Effect.Effect<void> => {
|
||||
const _self = self as FormImpl<A, I, R, MA, ME, MR, MP>
|
||||
return _self.runSemaphore.withPermits(1)(Stream.runForEach(
|
||||
_self.encodedValue.changes.pipe(
|
||||
Option.isSome(_self.debounce) ? Stream.debounce(_self.debounce.value) : identity
|
||||
),
|
||||
|
||||
encodedValue => _self.validationFiber.pipe(
|
||||
Effect.andThen(Option.match({
|
||||
onSome: Fiber.interrupt,
|
||||
onNone: () => Effect.void,
|
||||
})),
|
||||
Effect.andThen(
|
||||
Effect.forkScoped(Effect.onExit(
|
||||
Schema.decode(_self.schema, { errors: "all" })(encodedValue),
|
||||
exit => Effect.andThen(
|
||||
Exit.matchEffect(exit, {
|
||||
onSuccess: v => Effect.andThen(
|
||||
Ref.set(_self.value, Option.some(v)),
|
||||
Ref.set(_self.error, Option.none()),
|
||||
),
|
||||
onFailure: c => Option.match(Chunk.findFirst(Cause.failures(c), e => e._tag === "ParseError"), {
|
||||
onSome: e => Ref.set(_self.error, Option.some(e)),
|
||||
onNone: () => Effect.void,
|
||||
}),
|
||||
}),
|
||||
Ref.set(_self.validationFiber, Option.none()),
|
||||
),
|
||||
)).pipe(
|
||||
Effect.tap(fiber => Ref.set(_self.validationFiber, Option.some(fiber))),
|
||||
Effect.andThen(Fiber.join),
|
||||
Effect.andThen(value => _self.autosubmit
|
||||
? Effect.asVoid(Effect.forkScoped(_self.submitValue(value)))
|
||||
: Effect.void
|
||||
),
|
||||
Effect.forkScoped,
|
||||
)
|
||||
),
|
||||
Effect.provide(_self.context),
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
export declare namespace service {
|
||||
export interface Options<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
|
||||
extends make.Options<A, I, R, MA, ME, MR, MP> {}
|
||||
@@ -216,7 +216,7 @@ export const service = <A, I = A, R = never, MA = void, ME = never, MR = never,
|
||||
Scope.Scope | R | Result.forkEffect.OutputContext<MA, ME, MR, MP>
|
||||
> => Effect.tap(
|
||||
make(options),
|
||||
form => Effect.forkScoped(form.run),
|
||||
form => Effect.forkScoped(run(form)),
|
||||
)
|
||||
|
||||
|
||||
@@ -271,21 +271,22 @@ export const makeFormField = <A, I, R, MA, ME, MR, MP, const P extends PropertyP
|
||||
self: Form<A, I, R, MA, ME, MR, MP>,
|
||||
path: P,
|
||||
): FormField<PropertyPath.ValueFromPath<A, P>, PropertyPath.ValueFromPath<I, P>> => {
|
||||
const _self = self as FormImpl<A, I, R, MA, ME, MR, MP>
|
||||
return new FormFieldImpl(
|
||||
Subscribable.mapEffect(self.value, Option.match({
|
||||
Subscribable.mapEffect(_self.value, Option.match({
|
||||
onSome: v => Option.map(PropertyPath.get(v, path), Option.some),
|
||||
onNone: () => Option.some(Option.none()),
|
||||
})),
|
||||
SubscriptionSubRef.makeFromPath(self.encodedValue, path),
|
||||
Subscribable.mapEffect(self.error, Option.match({
|
||||
SubscriptionSubRef.makeFromPath(_self.encodedValue, path),
|
||||
Subscribable.mapEffect(_self.error, Option.match({
|
||||
onSome: flow(
|
||||
ParseResult.ArrayFormatter.formatError,
|
||||
Effect.map(Array.filter(issue => PropertyPath.equivalence(issue.path, path))),
|
||||
),
|
||||
onNone: () => Effect.succeed([]),
|
||||
})),
|
||||
Subscribable.map(self.validationFiber, Option.isSome),
|
||||
Subscribable.map(self.mutation.result, result => Result.isRunning(result) || Result.hasRefreshingFlag(result)),
|
||||
Subscribable.map(_self.validationFiber, Option.isSome),
|
||||
Subscribable.map(_self.mutation.result, result => Result.isRunning(result) || Result.isRefreshing(result)),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ extends Pipeable.Pipeable {
|
||||
readonly latestKey: Subscribable.Subscribable<Option.Option<K>>
|
||||
readonly fiber: Subscribable.Subscribable<Option.Option<Fiber.Fiber<A, E>>>
|
||||
readonly result: Subscribable.Subscribable<Result.Result<A, E, P>>
|
||||
readonly latestFinalResult: Subscribable.Subscribable<Option.Option<Result.Final<A, E, P>>>
|
||||
|
||||
mutate(key: K): Effect.Effect<Result.Final<A, E, P>>
|
||||
mutateSubscribable(key: K): Effect.Effect<Subscribable.Subscribable<Result.Result<A, E, P>>>
|
||||
@@ -31,30 +30,27 @@ extends Pipeable.Class() implements Mutation<K, A, E, R, P> {
|
||||
readonly [MutationTypeId]: MutationTypeId = MutationTypeId
|
||||
|
||||
constructor(
|
||||
readonly context: Context.Context<Scope.Scope | R>,
|
||||
readonly context: Context.Context<Scope.Scope | NoInfer<R>>,
|
||||
readonly f: (key: K) => Effect.Effect<A, E, R>,
|
||||
readonly initialProgress: P,
|
||||
|
||||
readonly latestKey: SubscriptionRef.SubscriptionRef<Option.Option<K>>,
|
||||
readonly fiber: SubscriptionRef.SubscriptionRef<Option.Option<Fiber.Fiber<A, E>>>,
|
||||
readonly result: SubscriptionRef.SubscriptionRef<Result.Result<A, E, P>>,
|
||||
readonly latestFinalResult: SubscriptionRef.SubscriptionRef<Option.Option<Result.Final<A, E, P>>>,
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
mutate(key: K): Effect.Effect<Result.Final<A, E, P>> {
|
||||
return SubscriptionRef.set(this.latestKey, Option.some(key)).pipe(
|
||||
Effect.andThen(this.start(key)),
|
||||
Effect.andThen(Effect.provide(this.start(key), this.context)),
|
||||
Effect.andThen(sub => this.watch(sub)),
|
||||
Effect.provide(this.context),
|
||||
)
|
||||
}
|
||||
mutateSubscribable(key: K): Effect.Effect<Subscribable.Subscribable<Result.Result<A, E, P>>> {
|
||||
return SubscriptionRef.set(this.latestKey, Option.some(key)).pipe(
|
||||
Effect.andThen(this.start(key)),
|
||||
Effect.tap(sub => Effect.forkScoped(this.watch(sub))),
|
||||
Effect.provide(this.context),
|
||||
return Effect.andThen(
|
||||
SubscriptionRef.set(this.latestKey, Option.some(key)),
|
||||
Effect.provide(this.start(key), this.context)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -63,8 +59,12 @@ extends Pipeable.Class() implements Mutation<K, A, E, R, P> {
|
||||
never,
|
||||
Scope.Scope | R
|
||||
> {
|
||||
return this.latestFinalResult.pipe(
|
||||
Effect.andThen(initial => Result.unsafeForkEffect(
|
||||
return this.result.pipe(
|
||||
Effect.map(previous => Result.isFinal(previous)
|
||||
? previous
|
||||
: undefined
|
||||
),
|
||||
Effect.andThen(previous => Result.unsafeForkEffect(
|
||||
Effect.onExit(this.f(key), () => Effect.andThen(
|
||||
Effect.all([Effect.fiberId, this.fiber]),
|
||||
([currentFiberId, fiber]) => Option.match(fiber, {
|
||||
@@ -72,12 +72,12 @@ extends Pipeable.Class() implements Mutation<K, A, E, R, P> {
|
||||
? SubscriptionRef.set(this.fiber, Option.none())
|
||||
: Effect.void,
|
||||
onNone: () => Effect.void,
|
||||
}),
|
||||
})
|
||||
)),
|
||||
|
||||
{
|
||||
initial: Option.isSome(initial) ? Result.willFetch(initial.value) : Result.initial(),
|
||||
initialProgress: this.initialProgress,
|
||||
previous,
|
||||
} as Result.unsafeForkEffect.Options<A, E, P>,
|
||||
)),
|
||||
Effect.tap(([, fiber]) => SubscriptionRef.set(this.fiber, Option.some(fiber))),
|
||||
@@ -88,14 +88,14 @@ extends Pipeable.Class() implements Mutation<K, A, E, R, P> {
|
||||
watch(
|
||||
sub: Subscribable.Subscribable<Result.Result<A, E, P>>
|
||||
): Effect.Effect<Result.Final<A, E, P>> {
|
||||
return sub.get.pipe(
|
||||
Effect.andThen(initial => Stream.runFoldEffect(
|
||||
sub.changes,
|
||||
return Effect.andThen(
|
||||
sub.get,
|
||||
initial => Stream.runFoldEffect(
|
||||
Stream.filter(sub.changes, Predicate.not(Result.isInitial)),
|
||||
initial,
|
||||
(_, result) => Effect.as(SubscriptionRef.set(this.result, result), result),
|
||||
) as Effect.Effect<Result.Final<A, E, P>>),
|
||||
Effect.tap(result => SubscriptionRef.set(this.latestFinalResult, Option.some(result))),
|
||||
)
|
||||
),
|
||||
) as Effect.Effect<Result.Final<A, E, P>>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +123,5 @@ export const make = Effect.fnUntraced(function* <const K extends Mutation.AnyKey
|
||||
yield* SubscriptionRef.make(Option.none<K>()),
|
||||
yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, E>>()),
|
||||
yield* SubscriptionRef.make(Result.initial<A, E, P>()),
|
||||
yield* SubscriptionRef.make(Option.none<Result.Final<A, E, P>>()),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type Cause, type Context, DateTime, type Duration, Effect, Equal, Equivalence, Fiber, HashMap, identity, Option, Pipeable, Predicate, type Scope, Stream, Subscribable, SubscriptionRef } from "effect"
|
||||
import { type Cause, type Context, DateTime, type Duration, Effect, Exit, Fiber, HashMap, identity, Option, Pipeable, Predicate, type Scope, Stream, Subscribable, SubscriptionRef } from "effect"
|
||||
import * as QueryClient from "./QueryClient.js"
|
||||
import * as Result from "./Result.js"
|
||||
|
||||
@@ -16,21 +16,18 @@ extends Pipeable.Pipeable {
|
||||
readonly initialProgress: P
|
||||
|
||||
readonly staleTime: Duration.DurationInput
|
||||
readonly refreshOnWindowFocus: boolean
|
||||
|
||||
readonly latestKey: Subscribable.Subscribable<Option.Option<K>>
|
||||
readonly fiber: Subscribable.Subscribable<Option.Option<Fiber.Fiber<A, E>>>
|
||||
readonly result: Subscribable.Subscribable<Result.Result<A, E, P>>
|
||||
readonly latestFinalResult: Subscribable.Subscribable<Option.Option<Result.Final<A, E, P>>>
|
||||
|
||||
readonly run: Effect.Effect<void>
|
||||
fetch(key: K): Effect.Effect<Result.Final<A, E, P>>
|
||||
fetchSubscribable(key: K): Effect.Effect<Subscribable.Subscribable<Result.Result<A, E, P>>>
|
||||
readonly refetch: Effect.Effect<Result.Final<A, E, P>, Cause.NoSuchElementException>
|
||||
readonly refetchSubscribable: Effect.Effect<Subscribable.Subscribable<Result.Result<A, E, P>>, Cause.NoSuchElementException>
|
||||
readonly refresh: Effect.Effect<Result.Final<A, E, P>, Cause.NoSuchElementException>
|
||||
readonly refreshSubscribable: Effect.Effect<Subscribable.Subscribable<Result.Result<A, E, P>>, Cause.NoSuchElementException>
|
||||
|
||||
readonly invalidateCache: Effect.Effect<void>
|
||||
invalidateCacheEntry(key: K): Effect.Effect<void>
|
||||
}
|
||||
|
||||
export declare namespace Query {
|
||||
@@ -48,12 +45,10 @@ extends Pipeable.Class() implements Query<K, A, E, R, P> {
|
||||
readonly initialProgress: P,
|
||||
|
||||
readonly staleTime: Duration.DurationInput,
|
||||
readonly refreshOnWindowFocus: boolean,
|
||||
|
||||
readonly latestKey: SubscriptionRef.SubscriptionRef<Option.Option<K>>,
|
||||
readonly fiber: SubscriptionRef.SubscriptionRef<Option.Option<Fiber.Fiber<A, E>>>,
|
||||
readonly result: SubscriptionRef.SubscriptionRef<Result.Result<A, E, P>>,
|
||||
readonly latestFinalResult: SubscriptionRef.SubscriptionRef<Option.Option<Result.Final<A, E, P>>>,
|
||||
|
||||
readonly runSemaphore: Effect.Semaphore,
|
||||
) {
|
||||
@@ -61,23 +56,13 @@ extends Pipeable.Class() implements Query<K, A, E, R, P> {
|
||||
}
|
||||
|
||||
get run(): Effect.Effect<void> {
|
||||
return Effect.all([
|
||||
Stream.runForEach(this.key, key => this.fetchSubscribable(key)),
|
||||
|
||||
Effect.promise(() => import("@effect/platform-browser")).pipe(
|
||||
Effect.andThen(({ BrowserStream }) => this.refreshOnWindowFocus
|
||||
? Stream.runForEach(
|
||||
BrowserStream.fromEventListenerWindow("focus"),
|
||||
() => this.refreshSubscribable,
|
||||
)
|
||||
: Effect.void
|
||||
),
|
||||
Effect.catchAllDefect(() => Effect.void),
|
||||
),
|
||||
], { concurrency: "unbounded" }).pipe(
|
||||
Effect.ignore,
|
||||
return Stream.runForEach(this.key, key => this.interrupt.pipe(
|
||||
Effect.andThen(SubscriptionRef.set(this.latestKey, Option.some(key))),
|
||||
Effect.andThen(this.startCached(key, Result.initial(), false)),
|
||||
Effect.andThen(sub => Effect.forkScoped(this.watch(sub))),
|
||||
Effect.provide(this.context),
|
||||
this.runSemaphore.withPermits(1),
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
get interrupt(): Effect.Effect<void, never, never> {
|
||||
@@ -90,136 +75,111 @@ extends Pipeable.Class() implements Query<K, A, E, R, P> {
|
||||
fetch(key: K): Effect.Effect<Result.Final<A, E, P>> {
|
||||
return this.interrupt.pipe(
|
||||
Effect.andThen(SubscriptionRef.set(this.latestKey, Option.some(key))),
|
||||
Effect.andThen(this.latestFinalResult),
|
||||
Effect.andThen(previous => this.startCached(key, Option.isSome(previous)
|
||||
? Result.willFetch(previous.value) as Result.Final<A, E, P>
|
||||
: Result.initial()
|
||||
)),
|
||||
Effect.andThen(sub => this.watch(key, sub)),
|
||||
Effect.provide(this.context),
|
||||
Effect.andThen(Effect.provide(this.startCached(key, Result.initial(), false), this.context)),
|
||||
Effect.andThen(sub => this.watch(sub)),
|
||||
)
|
||||
}
|
||||
|
||||
fetchSubscribable(key: K): Effect.Effect<Subscribable.Subscribable<Result.Result<A, E, P>>> {
|
||||
return this.interrupt.pipe(
|
||||
Effect.andThen(SubscriptionRef.set(this.latestKey, Option.some(key))),
|
||||
Effect.andThen(this.latestFinalResult),
|
||||
Effect.andThen(previous => this.startCached(key, Option.isSome(previous)
|
||||
? Result.willFetch(previous.value) as Result.Final<A, E, P>
|
||||
: Result.initial()
|
||||
)),
|
||||
Effect.tap(sub => Effect.forkScoped(this.watch(key, sub))),
|
||||
Effect.provide(this.context),
|
||||
Effect.andThen(Effect.provide(this.startCached(key, Result.initial(), false), this.context)),
|
||||
)
|
||||
}
|
||||
get refetch(): Effect.Effect<Result.Final<A, E, P>, Cause.NoSuchElementException> {
|
||||
return this.interrupt.pipe(
|
||||
Effect.andThen(this.latestKey),
|
||||
Effect.andThen(identity),
|
||||
Effect.andThen(key => Effect.provide(this.start(key, Result.initial(), false), this.context)),
|
||||
Effect.andThen(sub => this.watch(sub)),
|
||||
)
|
||||
}
|
||||
get refetchSubscribable(): Effect.Effect<Subscribable.Subscribable<Result.Result<A, E, P>>, Cause.NoSuchElementException> {
|
||||
return this.interrupt.pipe(
|
||||
Effect.andThen(this.latestKey),
|
||||
Effect.andThen(identity),
|
||||
Effect.andThen(key => Effect.provide(this.start(key, Result.initial(), false), this.context)),
|
||||
)
|
||||
}
|
||||
|
||||
get refresh(): Effect.Effect<Result.Final<A, E, P>, Cause.NoSuchElementException> {
|
||||
return this.interrupt.pipe(
|
||||
Effect.andThen(Effect.Do),
|
||||
Effect.bind("latestKey", () => Effect.andThen(this.latestKey, identity)),
|
||||
Effect.bind("latestFinalResult", () => this.latestFinalResult),
|
||||
Effect.bind("subscribable", ({ latestKey, latestFinalResult }) =>
|
||||
this.startCached(latestKey, Option.isSome(latestFinalResult)
|
||||
? Result.willRefresh(latestFinalResult.value) as Result.Final<A, E, P>
|
||||
: Result.initial()
|
||||
)
|
||||
),
|
||||
Effect.andThen(({ latestKey, subscribable }) => this.watch(latestKey, subscribable)),
|
||||
Effect.provide(this.context),
|
||||
Effect.andThen(this.latestKey),
|
||||
Effect.andThen(identity),
|
||||
Effect.andThen(key => Effect.provide(this.start(key, Result.initial(), true), this.context)),
|
||||
Effect.andThen(sub => this.watch(sub)),
|
||||
)
|
||||
}
|
||||
|
||||
get refreshSubscribable(): Effect.Effect<
|
||||
Subscribable.Subscribable<Result.Result<A, E, P>>,
|
||||
Cause.NoSuchElementException
|
||||
> {
|
||||
get refreshSubscribable(): Effect.Effect<Subscribable.Subscribable<Result.Result<A, E, P>>, Cause.NoSuchElementException> {
|
||||
return this.interrupt.pipe(
|
||||
Effect.andThen(Effect.Do),
|
||||
Effect.bind("latestKey", () => Effect.andThen(this.latestKey, identity)),
|
||||
Effect.bind("latestFinalResult", () => this.latestFinalResult),
|
||||
Effect.bind("subscribable", ({ latestKey, latestFinalResult }) =>
|
||||
this.startCached(latestKey, Option.isSome(latestFinalResult)
|
||||
? Result.willRefresh(latestFinalResult.value) as Result.Final<A, E, P>
|
||||
: Result.initial()
|
||||
)
|
||||
),
|
||||
Effect.tap(({ latestKey, subscribable }) => Effect.forkScoped(this.watch(latestKey, subscribable))),
|
||||
Effect.map(({ subscribable }) => subscribable),
|
||||
Effect.provide(this.context),
|
||||
Effect.andThen(this.latestKey),
|
||||
Effect.andThen(identity),
|
||||
Effect.andThen(key => Effect.provide(this.start(key, Result.initial(), true), this.context)),
|
||||
)
|
||||
}
|
||||
|
||||
startCached(
|
||||
key: K,
|
||||
initial: Result.Initial | Result.Final<A, E, P>,
|
||||
initial: Result.Result<A, E, P>,
|
||||
refresh: boolean,
|
||||
): Effect.Effect<
|
||||
Subscribable.Subscribable<Result.Result<A, E, P>>,
|
||||
never,
|
||||
Scope.Scope | QueryClient.QueryClient | R
|
||||
> {
|
||||
return Effect.andThen(this.getCacheEntry(key), Option.match({
|
||||
onSome: entry => Effect.andThen(
|
||||
QueryClient.isQueryClientCacheEntryStale(entry, this.staleTime),
|
||||
isStale => isStale
|
||||
? this.start(key, Result.willRefresh(entry.result) as Result.Final<A, E, P>)
|
||||
: Effect.succeed(Subscribable.make({
|
||||
onSome: entry => QueryClient.isQueryClientCacheEntryStale(entry, this.staleTime)
|
||||
? Effect.map(
|
||||
SubscriptionRef.set(this.result, entry.result as Result.Result<A, E, P>),
|
||||
() => Subscribable.make({
|
||||
get: Effect.succeed(entry.result as Result.Result<A, E, P>),
|
||||
get changes() { return Stream.make(entry.result as Result.Result<A, E, P>) },
|
||||
})),
|
||||
),
|
||||
onNone: () => this.start(key, initial),
|
||||
get changes() { return Stream.empty },
|
||||
}),
|
||||
)
|
||||
: this.start(key, Result.optimistic(entry.result) as Result.Result<A, E, P>, false),
|
||||
onNone: () => this.start(key, initial, refresh),
|
||||
}))
|
||||
}
|
||||
|
||||
start(
|
||||
key: K,
|
||||
initial: Result.Initial | Result.Final<A, E, P>,
|
||||
initial: Result.Result<A, E, P>,
|
||||
refresh: boolean,
|
||||
): Effect.Effect<
|
||||
Subscribable.Subscribable<Result.Result<A, E, P>>,
|
||||
never,
|
||||
Scope.Scope | R
|
||||
Scope.Scope | QueryClient.QueryClient | R
|
||||
> {
|
||||
return Result.unsafeForkEffect(
|
||||
Effect.onExit(this.f(key), () => Effect.andThen(
|
||||
Effect.all([Effect.fiberId, this.fiber]),
|
||||
([currentFiberId, fiber]) => Option.match(fiber, {
|
||||
onSome: v => Equal.equals(currentFiberId, v.id())
|
||||
? SubscriptionRef.set(this.fiber, Option.none())
|
||||
return this.result.pipe(
|
||||
Effect.map(previous => Result.isFinal(previous) ? previous : undefined),
|
||||
Effect.andThen(previous => Result.unsafeForkEffect(
|
||||
Effect.onExit(this.f(key), exit => Effect.andThen(
|
||||
Exit.isSuccess(exit)
|
||||
? this.updateCacheEntry(key, Result.succeed(exit.value))
|
||||
: Effect.void,
|
||||
onNone: () => Effect.void,
|
||||
}),
|
||||
SubscriptionRef.set(this.fiber, Option.none()),
|
||||
)),
|
||||
|
||||
{
|
||||
initial,
|
||||
initialProgress: this.initialProgress,
|
||||
refresh: refresh && previous,
|
||||
previous,
|
||||
} as Result.unsafeForkEffect.Options<A, E, P>,
|
||||
).pipe(
|
||||
)),
|
||||
Effect.tap(([, fiber]) => SubscriptionRef.set(this.fiber, Option.some(fiber))),
|
||||
Effect.map(([sub]) => sub),
|
||||
)
|
||||
}
|
||||
|
||||
watch(
|
||||
key: K,
|
||||
sub: Subscribable.Subscribable<Result.Result<A, E, P>>
|
||||
): Effect.Effect<Result.Final<A, E, P>, never, QueryClient.QueryClient> {
|
||||
return sub.get.pipe(
|
||||
Effect.andThen(initial => Stream.runFoldEffect(
|
||||
sub.changes,
|
||||
): Effect.Effect<Result.Final<A, E, P>> {
|
||||
return Effect.andThen(
|
||||
sub.get,
|
||||
initial => Stream.runFoldEffect(
|
||||
Stream.filter(sub.changes, Predicate.not(Result.isInitial)),
|
||||
initial,
|
||||
(_, result) => Effect.as(SubscriptionRef.set(this.result, result), result),
|
||||
) as Effect.Effect<Result.Final<A, E, P>>),
|
||||
Effect.tap(result => SubscriptionRef.set(this.latestFinalResult, Option.some(result))),
|
||||
Effect.tap(result => Result.isSuccess(result)
|
||||
? this.updateCacheEntry(key, result)
|
||||
: Effect.void
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
makeCacheKey(key: K): QueryClient.QueryClientCacheKey {
|
||||
return new QueryClient.QueryClientCacheKey(key, this.f as (key: Query.AnyKey) => Effect.Effect<unknown, unknown, unknown>)
|
||||
) as Effect.Effect<Result.Final<A, E, P>>
|
||||
}
|
||||
|
||||
getCacheEntry(
|
||||
@@ -227,7 +187,7 @@ extends Pipeable.Class() implements Query<K, A, E, R, P> {
|
||||
): Effect.Effect<Option.Option<QueryClient.QueryClientCacheEntry>, never, QueryClient.QueryClient> {
|
||||
return QueryClient.QueryClient.pipe(
|
||||
Effect.andThen(client => client.cache),
|
||||
Effect.map(HashMap.get(this.makeCacheKey(key))),
|
||||
Effect.map(HashMap.get(new QueryClient.QueryClientCacheKey(key, this.f as (key: Query.AnyKey) => Effect.Effect<unknown, unknown, unknown>))),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -241,31 +201,11 @@ extends Pipeable.Class() implements Query<K, A, E, R, P> {
|
||||
Effect.let("entry", ({ now }) => new QueryClient.QueryClientCacheEntry(result, now)),
|
||||
Effect.tap(({ client, entry }) => SubscriptionRef.update(
|
||||
client.cache,
|
||||
HashMap.set(this.makeCacheKey(key), entry),
|
||||
HashMap.set(new QueryClient.QueryClientCacheKey(key, this.f as (key: Query.AnyKey) => Effect.Effect<unknown, unknown, unknown>), entry),
|
||||
)),
|
||||
Effect.map(({ entry }) => entry),
|
||||
)
|
||||
}
|
||||
|
||||
get invalidateCache(): Effect.Effect<void> {
|
||||
return QueryClient.QueryClient.pipe(
|
||||
Effect.andThen(client => SubscriptionRef.update(
|
||||
client.cache,
|
||||
HashMap.filter((_, key) => !Equivalence.strict()(key.f, this.f)),
|
||||
)),
|
||||
Effect.provide(this.context),
|
||||
)
|
||||
}
|
||||
|
||||
invalidateCacheEntry(key: K): Effect.Effect<void> {
|
||||
return QueryClient.QueryClient.pipe(
|
||||
Effect.andThen(client => SubscriptionRef.update(
|
||||
client.cache,
|
||||
HashMap.remove(this.makeCacheKey(key)),
|
||||
)),
|
||||
Effect.provide(this.context),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export const isQuery = (u: unknown): u is Query<readonly unknown[], unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, QueryTypeId)
|
||||
@@ -276,7 +216,6 @@ export declare namespace make {
|
||||
readonly f: (key: NoInfer<K>) => Effect.Effect<A, E, Result.forkEffect.InputContext<R, NoInfer<P>>>
|
||||
readonly initialProgress?: P
|
||||
readonly staleTime?: Duration.DurationInput
|
||||
readonly refreshOnWindowFocus?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,12 +235,10 @@ export const make = Effect.fnUntraced(function* <K extends Query.AnyKey, A, E =
|
||||
options.initialProgress as P,
|
||||
|
||||
options.staleTime ?? client.defaultStaleTime,
|
||||
options.refreshOnWindowFocus ?? client.defaultRefreshOnWindowFocus,
|
||||
|
||||
yield* SubscriptionRef.make(Option.none<K>()),
|
||||
yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, E>>()),
|
||||
yield* SubscriptionRef.make(Result.initial<A, E, P>()),
|
||||
yield* SubscriptionRef.make(Option.none<Result.Final<A, E, P>>()),
|
||||
|
||||
yield* Effect.makeSemaphore(1),
|
||||
)
|
||||
|
||||
@@ -11,7 +11,6 @@ export interface QueryClientService extends Pipeable.Pipeable {
|
||||
readonly cache: SubscriptionRef.SubscriptionRef<HashMap.HashMap<QueryClientCacheKey, QueryClientCacheEntry>>
|
||||
readonly gcTime: Duration.DurationInput
|
||||
readonly defaultStaleTime: Duration.DurationInput
|
||||
readonly defaultRefreshOnWindowFocus: boolean
|
||||
}
|
||||
|
||||
export class QueryClient extends Effect.Service<QueryClient>()("@effect-fc/QueryClient/QueryClient", {
|
||||
@@ -27,7 +26,6 @@ implements QueryClientService {
|
||||
readonly cache: SubscriptionRef.SubscriptionRef<HashMap.HashMap<QueryClientCacheKey, QueryClientCacheEntry>>,
|
||||
readonly gcTime: Duration.DurationInput,
|
||||
readonly defaultStaleTime: Duration.DurationInput,
|
||||
readonly defaultRefreshOnWindowFocus: boolean,
|
||||
readonly runSemaphore: Effect.Semaphore,
|
||||
) {
|
||||
super()
|
||||
@@ -40,7 +38,6 @@ export declare namespace make {
|
||||
export interface Options {
|
||||
readonly gcTime?: Duration.DurationInput
|
||||
readonly defaultStaleTime?: Duration.DurationInput
|
||||
readonly defaultRefreshOnWindowFocus?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +46,6 @@ export const make = Effect.fnUntraced(function* (options: make.Options = {}): Ef
|
||||
yield* SubscriptionRef.make(HashMap.empty<QueryClientCacheKey, QueryClientCacheEntry>()),
|
||||
options.gcTime ?? "5 minutes",
|
||||
options.defaultStaleTime ?? "0 minutes",
|
||||
options.defaultRefreshOnWindowFocus ?? true,
|
||||
yield* Effect.makeSemaphore(1),
|
||||
)
|
||||
})
|
||||
@@ -115,5 +111,5 @@ export const isQueryClientCacheEntryStale = (
|
||||
staleTime: Duration.DurationInput,
|
||||
): Effect.Effect<boolean> => Effect.andThen(
|
||||
DateTime.now,
|
||||
now => Duration.greaterThanOrEqualTo(DateTime.distanceDuration(self.createdAt, now), staleTime),
|
||||
now => Duration.lessThan(DateTime.distanceDuration(self.createdAt, now), staleTime),
|
||||
)
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
import { Cause, Context, Data, Effect, Equal, Exit, type Fiber, Hash, Layer, Match, Pipeable, Predicate, PubSub, pipe, Ref, type Scope, Stream, Subscribable } from "effect"
|
||||
import { Cause, Context, Data, Effect, Equal, Exit, type Fiber, Hash, Layer, Match, Option, Pipeable, Predicate, PubSub, pipe, Ref, type Scope, Stream, Subscribable } from "effect"
|
||||
|
||||
|
||||
export const ResultTypeId: unique symbol = Symbol.for("@effect-fc/Result/Result")
|
||||
export type ResultTypeId = typeof ResultTypeId
|
||||
|
||||
export type Result<A, E = never, P = never> = (
|
||||
| Initial
|
||||
// biome-ignore lint/complexity/noBannedTypes: "{}" is relevant here
|
||||
| (Initial & ({} | WillFetch))
|
||||
| Running<P>
|
||||
| Final<A, E, P>
|
||||
)
|
||||
|
||||
export type Final<A, E = never, P = never> = (
|
||||
& (Success<A> | Failure<A, E>)
|
||||
// biome-ignore lint/complexity/noBannedTypes: "{}" is relevant here
|
||||
export type Final<A, E = never, P = never> = (Success<A> | Failure<E>) & ({} | Flags<P>)
|
||||
export type Flags<P = never> = WillFetch | WillRefresh | Refreshing<P>
|
||||
& ({} | WillFetch | WillRefresh | Refreshing<P>)
|
||||
)
|
||||
|
||||
export declare namespace Result {
|
||||
export namespace Result {
|
||||
export interface Prototype extends Pipeable.Pipeable, Equal.Equal {
|
||||
readonly [ResultTypeId]: ResultTypeId
|
||||
}
|
||||
@@ -24,10 +27,6 @@ export declare namespace Result {
|
||||
export type Progress<R extends Result<any, any, any>> = [R] extends [Result<infer _A, infer _E, infer P>] ? P : never
|
||||
}
|
||||
|
||||
export declare namespace Flags {
|
||||
export type Keys = keyof WillFetch & WillRefresh & Refreshing<any>
|
||||
}
|
||||
|
||||
export interface Initial extends Result.Prototype {
|
||||
readonly _tag: "Initial"
|
||||
}
|
||||
@@ -42,21 +41,22 @@ export interface Success<A> extends Result.Prototype {
|
||||
readonly value: A
|
||||
}
|
||||
|
||||
export interface Failure<E = never> extends Result.Prototype {
|
||||
export interface Failure<A, E = never> extends Result.Prototype {
|
||||
readonly _tag: "Failure"
|
||||
readonly cause: Cause.Cause<E>
|
||||
readonly previousSuccess: Option.Option<Success<A>>
|
||||
}
|
||||
|
||||
export interface WillFetch {
|
||||
readonly _flag: "WillFetch"
|
||||
export interface WillFetch extends Result.Prototype {
|
||||
readonly willFetch: true
|
||||
}
|
||||
|
||||
export interface WillRefresh {
|
||||
readonly _flag: "WillRefresh"
|
||||
export interface WillRefresh extends Result.Prototype {
|
||||
readonly willRefresh: true
|
||||
}
|
||||
|
||||
export interface Refreshing<P = never> {
|
||||
readonly _flag: "Refreshing"
|
||||
export interface Refreshing<P = never> extends Result.Prototype {
|
||||
readonly refreshing: true
|
||||
readonly progress: P
|
||||
}
|
||||
|
||||
@@ -66,32 +66,41 @@ const ResultPrototype = Object.freeze({
|
||||
[ResultTypeId]: ResultTypeId,
|
||||
|
||||
[Equal.symbol](this: Result<any, any, any>, that: Result<any, any, any>): boolean {
|
||||
if (this._tag !== that._tag || (this as Flags)._flag !== (that as Flags)._flag)
|
||||
return false
|
||||
if (hasRefreshingFlag(this) && !Equal.equals(this.progress, (that as Refreshing<any>).progress))
|
||||
if (this._tag !== that._tag)
|
||||
return false
|
||||
|
||||
return Match.value(this).pipe(
|
||||
Match.tag("Initial", () => true),
|
||||
Match.tag("Running", self => Equal.equals(self.progress, (that as Running<any>).progress)),
|
||||
Match.tag("Success", self => Equal.equals(self.value, (that as Success<any>).value)),
|
||||
Match.tag("Failure", self => Equal.equals(self.cause, (that as Failure<any>).cause)),
|
||||
Match.tag("Success", self =>
|
||||
Equal.equals(self.value, (that as Success<any>).value) &&
|
||||
(isRefreshing(self) ? self.refreshing : false) === (isRefreshing(that) ? that.refreshing : false) &&
|
||||
Equal.equals(isRefreshing(self) ? self.progress : undefined, isRefreshing(that) ? that.progress : undefined)
|
||||
),
|
||||
Match.tag("Failure", self =>
|
||||
Equal.equals(self.cause, (that as Failure<any, any>).cause) &&
|
||||
(isRefreshing(self) ? self.refreshing : false) === (isRefreshing(that) ? that.refreshing : false) &&
|
||||
Equal.equals(isRefreshing(self) ? self.progress : undefined, isRefreshing(that) ? that.progress : undefined)
|
||||
),
|
||||
Match.exhaustive,
|
||||
)
|
||||
},
|
||||
|
||||
[Hash.symbol](this: Result<any, any, any>): number {
|
||||
return pipe(Hash.string(this._tag),
|
||||
tagHash => Match.value(this).pipe(
|
||||
const tagHash = Hash.string(this._tag)
|
||||
|
||||
return Match.value(this).pipe(
|
||||
Match.tag("Initial", () => tagHash),
|
||||
Match.tag("Running", self => Hash.combine(Hash.hash(self.progress))(tagHash)),
|
||||
Match.tag("Success", self => Hash.combine(Hash.hash(self.value))(tagHash)),
|
||||
Match.tag("Failure", self => Hash.combine(Hash.hash(self.cause))(tagHash)),
|
||||
Match.tag("Success", self => pipe(tagHash,
|
||||
Hash.combine(Hash.hash(self.value)),
|
||||
Hash.combine(Hash.hash(isRefreshing(self) ? self.progress : undefined)),
|
||||
)),
|
||||
Match.tag("Failure", self => pipe(tagHash,
|
||||
Hash.combine(Hash.hash(self.cause)),
|
||||
Hash.combine(Hash.hash(isRefreshing(self) ? self.progress : undefined)),
|
||||
)),
|
||||
Match.exhaustive,
|
||||
),
|
||||
Hash.combine(Hash.hash((this as Flags)._flag)),
|
||||
hash => hasRefreshingFlag(this)
|
||||
? Hash.combine(Hash.hash(this.progress))(hash)
|
||||
: hash,
|
||||
Hash.cached(this),
|
||||
)
|
||||
},
|
||||
@@ -103,11 +112,10 @@ export const isFinal = (u: unknown): u is Final<unknown, unknown, unknown> => is
|
||||
export const isInitial = (u: unknown): u is Initial => isResult(u) && u._tag === "Initial"
|
||||
export const isRunning = (u: unknown): u is Running<unknown> => isResult(u) && u._tag === "Running"
|
||||
export const isSuccess = (u: unknown): u is Success<unknown> => isResult(u) && u._tag === "Success"
|
||||
export const isFailure = (u: unknown): u is Failure<unknown> => isResult(u) && u._tag === "Failure"
|
||||
export const hasFlag = (u: unknown): u is Flags => isResult(u) && Predicate.hasProperty(u, "_flag")
|
||||
export const hasWillFetchFlag = (u: unknown): u is WillFetch => isResult(u) && Predicate.hasProperty(u, "_flag") && u._flag === "WillFetch"
|
||||
export const hasWillRefreshFlag = (u: unknown): u is WillRefresh => isResult(u) && Predicate.hasProperty(u, "_flag") && u._flag === "WillRefresh"
|
||||
export const hasRefreshingFlag = (u: unknown): u is Refreshing<unknown> => isResult(u) && Predicate.hasProperty(u, "_flag") && u._flag === "Refreshing"
|
||||
export const isFailure = (u: unknown): u is Failure<unknown, unknown> => isResult(u) && u._tag === "Failure"
|
||||
export const isWillFetch = (u: unknown): u is WillFetch => isResult(u) && Predicate.hasProperty(u, "willFetch")
|
||||
export const isWillRefresh = (u: unknown): u is WillRefresh => isResult(u) && Predicate.hasProperty(u, "willRefresh")
|
||||
export const isRefreshing = (u: unknown): u is Refreshing<unknown> => isResult(u) && Predicate.hasProperty(u, "refreshing")
|
||||
|
||||
export const initial: {
|
||||
(): Initial
|
||||
@@ -115,42 +123,48 @@ export const initial: {
|
||||
} = (): Initial => Object.setPrototypeOf({ _tag: "Initial" }, ResultPrototype)
|
||||
export const running = <P = never>(progress?: P): Running<P> => Object.setPrototypeOf({ _tag: "Running", progress }, ResultPrototype)
|
||||
export const succeed = <A>(value: A): Success<A> => Object.setPrototypeOf({ _tag: "Success", value }, ResultPrototype)
|
||||
export const fail = <E>(cause: Cause.Cause<E> ): Failure<E> => Object.setPrototypeOf({ _tag: "Failure", cause }, ResultPrototype)
|
||||
|
||||
export const willFetch = <R extends Final<any, any, any>>(
|
||||
export const fail = <E, A = never>(
|
||||
cause: Cause.Cause<E>,
|
||||
previousSuccess?: Success<NoInfer<A>>,
|
||||
): Failure<A, E> => Object.setPrototypeOf({
|
||||
_tag: "Failure",
|
||||
cause,
|
||||
previousSuccess: Option.fromNullable(previousSuccess),
|
||||
}, ResultPrototype)
|
||||
|
||||
export const willFetch = <R extends Initial | Final<any, any, any>>(
|
||||
result: R
|
||||
): Omit<R, keyof Flags.Keys> & WillFetch => Object.setPrototypeOf(
|
||||
Object.assign({}, result, { _flag: "WillFetch" }),
|
||||
): Omit<R, keyof WillFetch> & WillFetch => Object.setPrototypeOf(
|
||||
Object.assign({}, result, { willFetch: true }),
|
||||
Object.getPrototypeOf(result),
|
||||
)
|
||||
|
||||
export const willRefresh = <R extends Final<any, any, any>>(
|
||||
result: R
|
||||
): Omit<R, keyof Flags.Keys> & WillRefresh => Object.setPrototypeOf(
|
||||
Object.assign({}, result, { _flag: "WillRefresh" }),
|
||||
): Omit<R, keyof WillRefresh> & WillRefresh => Object.setPrototypeOf(
|
||||
Object.assign({}, result, { willRefresh: true }),
|
||||
Object.getPrototypeOf(result),
|
||||
)
|
||||
|
||||
export const refreshing = <R extends Final<any, any, any>, P = never>(
|
||||
result: R,
|
||||
progress?: P,
|
||||
): Omit<R, keyof Flags.Keys> & Refreshing<P> => Object.setPrototypeOf(
|
||||
Object.assign({}, result, { _flag: "Refreshing", progress }),
|
||||
): Omit<R, keyof Refreshing<Result.Progress<R>>> & Refreshing<P> => Object.setPrototypeOf(
|
||||
Object.assign({}, result, { refreshing: true, progress }),
|
||||
Object.getPrototypeOf(result),
|
||||
)
|
||||
|
||||
export const fromExit: {
|
||||
<A, E>(exit: Exit.Success<A, E>): Success<A>
|
||||
<A, E>(exit: Exit.Failure<A, E>): Failure<E>
|
||||
<A, E>(exit: Exit.Exit<A, E>): Success<A> | Failure<E>
|
||||
} = exit => (exit._tag === "Success" ? succeed(exit.value) : fail(exit.cause)) as any
|
||||
export const fromExit = <A, E>(
|
||||
exit: Exit.Exit<A, E>,
|
||||
previousSuccess?: Success<NoInfer<A>>,
|
||||
): Success<A> | Failure<A, E> => exit._tag === "Success"
|
||||
? succeed(exit.value)
|
||||
: fail(exit.cause, previousSuccess)
|
||||
|
||||
export const toExit: {
|
||||
<A>(self: Success<A>): Exit.Success<A, never>
|
||||
<E>(self: Failure<E>): Exit.Failure<never, E>
|
||||
<A, E, P>(self: Final<A, E, P>): Exit.Exit<A, E>
|
||||
<A, E, P>(self: Result<A, E, P>): Exit.Exit<A, E | Cause.NoSuchElementException>
|
||||
} = <A, E, P>(self: Result<A, E, P>): any => {
|
||||
export const toExit = <A, E, P>(
|
||||
self: Result<A, E, P>
|
||||
): Exit.Exit<A, E | Cause.NoSuchElementException> => {
|
||||
switch (self._tag) {
|
||||
case "Success":
|
||||
return Exit.succeed(self.value)
|
||||
@@ -189,17 +203,17 @@ export const makeProgressLayer = <A, E, P = never>(): Layer.Layer<
|
||||
const state = yield* State<A, E, P>()
|
||||
|
||||
return {
|
||||
update: <FE, FR>(f: (previous: P) => Effect.Effect<P, FE, FR>) => Effect.Do.pipe(
|
||||
update: <E, R>(f: (previous: P) => Effect.Effect<P, E, R>) => Effect.Do.pipe(
|
||||
Effect.bind("previous", () => Effect.andThen(state.get, previous =>
|
||||
(isRunning(previous) || hasRefreshingFlag(previous))
|
||||
isRunning(previous) || isRefreshing(previous)
|
||||
? Effect.succeed(previous)
|
||||
: Effect.fail(new PreviousResultNotRunningNorRefreshing({ previous })),
|
||||
)),
|
||||
Effect.bind("progress", ({ previous }) => f(previous.progress)),
|
||||
Effect.let("next", ({ previous, progress }) => isRunning(previous)
|
||||
? running(progress)
|
||||
: refreshing(previous, progress) as Final<A, E, P> & Refreshing<P>
|
||||
),
|
||||
Effect.let("next", ({ previous, progress }) => Object.setPrototypeOf(
|
||||
Object.assign({}, previous, { progress }),
|
||||
Object.getPrototypeOf(previous),
|
||||
)),
|
||||
Effect.andThen(({ next }) => state.set(next)),
|
||||
),
|
||||
}
|
||||
@@ -209,10 +223,19 @@ export const makeProgressLayer = <A, E, P = never>(): Layer.Layer<
|
||||
export namespace unsafeForkEffect {
|
||||
export type OutputContext<A, E, R, P> = Exclude<R, State<A, E, P> | Progress<P> | Progress<never>>
|
||||
|
||||
export interface Options<A, E, P> {
|
||||
readonly initial?: Initial | Final<A, E, P>
|
||||
export type Options<A, E, P> = {
|
||||
readonly initial?: Result<A, E, P>
|
||||
readonly initialProgress?: P
|
||||
readonly previous?: Final<A, E, P>
|
||||
} & (
|
||||
| {
|
||||
readonly refresh: true
|
||||
readonly previous: Final<A, E, P>
|
||||
}
|
||||
| {
|
||||
readonly refresh?: false
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export const unsafeForkEffect = <A, E, R, P = never>(
|
||||
@@ -226,14 +249,13 @@ export const unsafeForkEffect = <A, E, R, P = never>(
|
||||
Effect.bind("ref", () => Ref.make(options?.initial ?? initial<A, E, P>())),
|
||||
Effect.bind("pubsub", () => PubSub.unbounded<Result<A, E, P>>()),
|
||||
Effect.bind("fiber", ({ ref, pubsub }) => Effect.forkScoped(State<A, E, P>().pipe(
|
||||
Effect.andThen(state => state.set(
|
||||
(isFinal(options?.initial) && hasWillRefreshFlag(options?.initial))
|
||||
? refreshing(options.initial, options?.initialProgress) as Result<A, E, P>
|
||||
Effect.andThen(state => state.set(options?.refresh
|
||||
? refreshing(options.previous, options?.initialProgress) as Result<A, E, P>
|
||||
: running(options?.initialProgress)
|
||||
).pipe(
|
||||
Effect.andThen(effect),
|
||||
Effect.onExit(exit => Effect.andThen(
|
||||
state.set(fromExit(exit)),
|
||||
state.set(fromExit(exit, (options?.previous && isSuccess(options.previous)) ? options.previous : undefined)),
|
||||
Effect.forkScoped(PubSub.shutdown(pubsub)),
|
||||
)),
|
||||
)),
|
||||
@@ -264,7 +286,7 @@ export const unsafeForkEffect = <A, E, R, P = never>(
|
||||
export namespace forkEffect {
|
||||
export type InputContext<R, P> = R extends Progress<infer X> ? [X] extends [P] ? R : never : R
|
||||
export type OutputContext<A, E, R, P> = unsafeForkEffect.OutputContext<A, E, R, P>
|
||||
export interface Options<A, E, P> extends unsafeForkEffect.Options<A, E, P> {}
|
||||
export type Options<A, E, P> = unsafeForkEffect.Options<A, E, P>
|
||||
}
|
||||
|
||||
export const forkEffect: {
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
"globals": "^17.0.0",
|
||||
"globals": "^16.5.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"type-fest": "^5.2.0",
|
||||
|
||||
@@ -18,16 +18,16 @@ const ResultView = Component.makeUntraced("Result")(function*() {
|
||||
|
||||
const [idRef, query, mutation] = yield* Component.useOnMount(() => Effect.gen(function*() {
|
||||
const idRef = yield* SubscriptionRef.make(1)
|
||||
const key = Stream.zipLatest(Stream.make("posts" as const), idRef.changes)
|
||||
|
||||
const query = yield* Query.service({
|
||||
key: Stream.zipLatest(Stream.make("posts" as const), idRef.changes),
|
||||
key,
|
||||
f: ([, id]) => HttpClient.HttpClient.pipe(
|
||||
Effect.tap(Effect.sleep("500 millis")),
|
||||
Effect.andThen(client => client.get(`https://jsonplaceholder.typicode.com/posts/${ id }`)),
|
||||
Effect.andThen(response => response.json),
|
||||
Effect.andThen(Schema.decodeUnknown(Post)),
|
||||
),
|
||||
staleTime: "10 seconds",
|
||||
})
|
||||
|
||||
const mutation = yield* Mutation.make({
|
||||
@@ -74,7 +74,7 @@ const ResultView = Component.makeUntraced("Result")(function*() {
|
||||
Match.tag("Success", result => <>
|
||||
<Heading>{result.value.title}</Heading>
|
||||
<Text>{result.value.body}</Text>
|
||||
{Result.hasRefreshingFlag(result) && <Text>Refreshing...</Text>}
|
||||
{Result.isRefreshing(result) && <Text>Refreshing...</Text>}
|
||||
</>),
|
||||
Match.tag("Failure", result =>
|
||||
<Text>An error has occured: {result.cause.toString()}</Text>
|
||||
@@ -85,7 +85,7 @@ const ResultView = Component.makeUntraced("Result")(function*() {
|
||||
|
||||
<Flex direction="row" justify="center" align="center" gap="1">
|
||||
<Button onClick={() => runPromise(query.refresh)}>Refresh</Button>
|
||||
<Button onClick={() => runPromise(query.invalidateCache)}>Invalidate cache</Button>
|
||||
<Button onClick={() => runPromise(query.refetch)}>Refetch</Button>
|
||||
</Flex>
|
||||
|
||||
<div>
|
||||
@@ -94,7 +94,7 @@ const ResultView = Component.makeUntraced("Result")(function*() {
|
||||
Match.tag("Success", result => <>
|
||||
<Heading>{result.value.title}</Heading>
|
||||
<Text>{result.value.body}</Text>
|
||||
{Result.hasRefreshingFlag(result) && <Text>Refreshing...</Text>}
|
||||
{Result.isRefreshing(result) && <Text>Refreshing...</Text>}
|
||||
</>),
|
||||
Match.tag("Failure", result =>
|
||||
<Text>An error has occured: {result.cause.toString()}</Text>
|
||||
|
||||
Reference in New Issue
Block a user