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

Function layerFileSystem

packages/platform/src/internal/keyValueStore.ts:194–255  ·  view source on GitHub ↗
(directory: string)

Source from the content-addressed store, hash-verified

192
193/** @internal */
194export const layerFileSystem = (directory: string) =>
195 Layer.effect(
196 keyValueStoreTag,
197 Effect.gen(function*() {
198 const fs = yield* FileSystem.FileSystem
199 const path = yield* Path.Path
200 const withKeyPath = <A>(
201 method: string,
202 key: string,
203 f: (path: string) => Effect.Effect<A, PlatformError.PlatformError>
204 ): Effect.Effect<A, PlatformError.PlatformError> =>
205 key.length === 0 || key === "." || key === ".."
206 ? Effect.fail(
207 new PlatformError.BadArgument({
208 module: "KeyValueStore",
209 method,
210 description: "Key must not be empty, . or .."
211 })
212 )
213 : f(path.join(directory, encodeURIComponent(key)))
214
215 if (!(yield* fs.exists(directory))) {
216 yield* fs.makeDirectory(directory, { recursive: true })
217 }
218
219 return make({
220 get: (key: string) =>
221 withKeyPath("get", key, (path) =>
222 pipe(
223 Effect.map(fs.readFileString(path), Option.some),
224 Effect.catchTag(
225 "SystemError",
226 (sysError) => sysError.reason === "NotFound" ? Effect.succeed(Option.none()) : Effect.fail(sysError)
227 )
228 )),
229 getUint8Array: (key: string) =>
230 withKeyPath("getUint8Array", key, (path) =>
231 pipe(
232 Effect.map(fs.readFile(path), Option.some),
233 Effect.catchTag(
234 "SystemError",
235 (sysError) => sysError.reason === "NotFound" ? Effect.succeed(Option.none()) : Effect.fail(sysError)
236 )
237 )),
238 set: (key: string, value: string | Uint8Array) =>
239 withKeyPath("set", key, (path) =>
240 typeof value === "string" ? fs.writeFileString(path, value) : fs.writeFile(path, value)),
241 remove: (key: string) =>
242 withKeyPath("remove", key, fs.remove),
243 has: (key: string) =>
244 withKeyPath("has", key, fs.exists),
245 clear: Effect.zipRight(
246 fs.remove(directory, { recursive: true }),
247 fs.makeDirectory(directory, { recursive: true })
248 ),
249 size: Effect.map(
250 fs.readDirectory(directory),
251 (files) => files.length

Callers

nothing calls this directly

Calls 6

withKeyPathFunction · 0.85
makeFunction · 0.70
pipeFunction · 0.70
mapMethod · 0.65
failMethod · 0.65
removeMethod · 0.65

Tested by

no test coverage detected