| 192 | |
| 193 | /** @internal */ |
| 194 | export 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 keyPath = (key: string) => path.join(directory, encodeURIComponent(key)) |
| 201 | |
| 202 | if (!(yield* fs.exists(directory))) { |
| 203 | yield* fs.makeDirectory(directory, { recursive: true }) |
| 204 | } |
| 205 | |
| 206 | return make({ |
| 207 | get: (key: string) => |
| 208 | pipe( |
| 209 | Effect.map(fs.readFileString(keyPath(key)), Option.some), |
| 210 | Effect.catchTag( |
| 211 | "SystemError", |
| 212 | (sysError) => sysError.reason === "NotFound" ? Effect.succeed(Option.none()) : Effect.fail(sysError) |
| 213 | ) |
| 214 | ), |
| 215 | getUint8Array: (key: string) => |
| 216 | pipe( |
| 217 | Effect.map(fs.readFile(keyPath(key)), Option.some), |
| 218 | Effect.catchTag( |
| 219 | "SystemError", |
| 220 | (sysError) => sysError.reason === "NotFound" ? Effect.succeed(Option.none()) : Effect.fail(sysError) |
| 221 | ) |
| 222 | ), |
| 223 | set: (key: string, value: string | Uint8Array) => |
| 224 | typeof value === "string" ? fs.writeFileString(keyPath(key), value) : fs.writeFile(keyPath(key), value), |
| 225 | remove: (key: string) => fs.remove(keyPath(key)), |
| 226 | has: (key: string) => fs.exists(keyPath(key)), |
| 227 | clear: Effect.zipRight( |
| 228 | fs.remove(directory, { recursive: true }), |
| 229 | fs.makeDirectory(directory, { recursive: true }) |
| 230 | ), |
| 231 | size: Effect.map( |
| 232 | fs.readDirectory(directory), |
| 233 | (files) => files.length |
| 234 | ) |
| 235 | }) |
| 236 | }) |
| 237 | ) |
| 238 | |
| 239 | /** @internal */ |
| 240 | export const layerSchema = <A, I, R>( |