MCPcopy Create free account
hub / github.com/Effect-TS/effect / toSchemaStore

Function toSchemaStore

packages/effect/src/unstable/persistence/KeyValueStore.ts:768–811  ·  view source on GitHub ↗
(self: KeyValueStore, schema: S)

Source from the content-addressed store, hash-verified

766 * @since 4.0.0
767 */
768export const toSchemaStore = <S extends Schema.Constraint>(self: KeyValueStore, schema: S): SchemaStore<S> => {
769 const serializer = Schema.toCodecJson(schema)
770 const jsonSchema = Schema.fromJsonString(serializer)
771 const decode = Schema.decodeEffect(jsonSchema)
772 const encode = Schema.encodeEffect(jsonSchema)
773
774 const get = (key: string) =>
775 Effect.flatMap(
776 self.get(key),
777 UndefinedOr.match({
778 onUndefined: () => Effect.succeedNone,
779 onDefined: (value) => Effect.asSome(decode(value))
780 })
781 )
782
783 const set = (key: string, value: S["Type"]) => Effect.flatMap(encode(value), (json) => self.set(key, json))
784
785 const modify = (key: string, f: (value: S["Type"]) => S["Type"]) =>
786 Effect.flatMap(
787 get(key),
788 (o) => {
789 if (Option.isNone(o)) {
790 return Effect.succeedNone
791 }
792 const newValue = f(o.value)
793 return Effect.as(
794 set(key, newValue),
795 Option.some(newValue)
796 )
797 }
798 )
799
800 return {
801 [SchemaStoreTypeId]: SchemaStoreTypeId,
802 get,
803 set,
804 modify,
805 remove: self.remove,
806 clear: self.clear,
807 size: self.size,
808 has: self.has,
809 isEmpty: self.isEmpty
810 }
811}
812
813/**
814 * Provides a `KeyValueStore` backed by a Web `Storage` instance such as

Callers

nothing calls this directly

Calls 1

toCodecJsonMethod · 0.45

Tested by

no test coverage detected