Skip to content

Commit

Permalink
fix Model findById data loader (#3657)
Browse files Browse the repository at this point in the history
Co-authored-by: Tim <hello@timsmart.co>
  • Loading branch information
jamiehodge and tim-smart authored Sep 23, 2024
1 parent 4479c3e commit d5c8e7e
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 7 deletions.
6 changes: 6 additions & 0 deletions .changeset/real-pumas-tease.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@effect/sql-mysql2": patch
"@effect/sql": patch
---

fix Model findById data loader
27 changes: 26 additions & 1 deletion packages/sql-mysql2/test/Model.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Schema } from "@effect/schema"
import { Model, SqlClient } from "@effect/sql"
import { assert, describe, it } from "@effect/vitest"
import { Effect } from "effect"
import { Effect, Option } from "effect"
import { MysqlContainer } from "./utils.js"

class User extends Model.Class<User>("User")({
Expand Down Expand Up @@ -67,6 +67,31 @@ describe("Model", () => {
Effect.catchTag("ContainerError", () => Effect.void)
), { timeout: 60_000 })

it.scopedLive("findById data loader", () =>
Effect.gen(function*() {
const repo = yield* Model.makeDataLoaders(User, {
tableName: "users",
idColumn: "id",
spanPrefix: "UserRepository",
window: 10
})
const sql = yield* SqlClient.SqlClient
yield* sql`CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)`
const alice = yield* repo.insert(User.insert.make({ name: "Alice", age: 30 }))
const john = yield* repo.insert(User.insert.make({ name: "John", age: 30 }))

const [alice2, john2] = yield* Effect.all([
repo.findById(alice.id),
repo.findById(john.id)
], { batching: true })

assert.deepStrictEqual(Option.map(alice2, (alice) => alice.name), Option.some("Alice"))
assert.deepStrictEqual(Option.map(john2, (john) => john.name), Option.some("John"))
}).pipe(
Effect.provide(MysqlContainer.ClientLive),
Effect.catchTag("ContainerError", () => Effect.void)
), { timeout: 60_000 })

it.effect("update returns result", () =>
Effect.gen(function*() {
const repo = yield* Model.makeRepository(User, {
Expand Down
9 changes: 3 additions & 6 deletions packages/sql/src/Model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -848,13 +848,10 @@ select * from ${sql(options.tableName)} where ${sql(idColumn)} = LAST_INSERT_ID(
})
) as any

const findByIdResolver = yield* SqlResolver.grouped(`${options.spanPrefix}/findById`, {
Request: idSchema,
RequestGroupKey(id) {
return id
},
const findByIdResolver = yield* SqlResolver.findById(`${options.spanPrefix}/findById`, {
Id: idSchema,
Result: Model,
ResultGroupKey(request) {
ResultId(request) {
return request[idColumn]
},
execute: (ids) => sql`select * from ${sql(options.tableName)} where ${sql.in(idColumn, ids)}`
Expand Down

0 comments on commit d5c8e7e

Please sign in to comment.