| 38 | } |
| 39 | |
| 40 | class UserStore extends Context.Service<UserStore, UserStoreShape>()("@opencode/example/UserStore") { |
| 41 | static layer = Layer.effect( |
| 42 | UserStore, |
| 43 | Effect.gen(function* () { |
| 44 | const db = yield* Database |
| 45 | |
| 46 | return UserStore.of({ |
| 47 | migrate: Effect.fn("UserStore.migrate")(function* () { |
| 48 | yield* EffectDrizzleSqlite.migrate(db, { migrationsFolder: `${import.meta.dirname}/migrations` }).pipe( |
| 49 | Effect.mapError((cause) => new UserStoreError({ message: "Failed to migrate users", cause })), |
| 50 | ) |
| 51 | }), |
| 52 | create: Effect.fn("UserStore.create")(function* (name: string) { |
| 53 | yield* db |
| 54 | .insert(users) |
| 55 | .values({ name }) |
| 56 | .pipe(Effect.asVoid, Effect.mapError(mapStoreError("Failed to create user"))) |
| 57 | }), |
| 58 | rename: Effect.fn("UserStore.rename")(function* (from: string, to: string) { |
| 59 | yield* db |
| 60 | .transaction( |
| 61 | Effect.fnUntraced(function* (tx) { |
| 62 | yield* tx.insert(users).values({ name: from }) |
| 63 | yield* tx.update(users).set({ name: to }).where(eq(users.name, from)) |
| 64 | }), |
| 65 | { behavior: "immediate" }, |
| 66 | ) |
| 67 | .pipe(Effect.asVoid, Effect.mapError(mapStoreError("Failed to rename user"))) |
| 68 | }), |
| 69 | list: Effect.fn("UserStore.list")(function* () { |
| 70 | return yield* db |
| 71 | .select() |
| 72 | .from(users) |
| 73 | .pipe(Effect.mapError(mapStoreError("Failed to list users"))) |
| 74 | }), |
| 75 | }) |
| 76 | }), |
| 77 | ).pipe(Layer.provide(Database.layer)) |
| 78 | } |
| 79 | |
| 80 | const program = Effect.gen(function* () { |
| 81 | const userStore = yield* UserStore |