Skip to content

Instantly share code, notes, and snippets.

@yanisurbis
Created March 29, 2024 13:39
Show Gist options
  • Save yanisurbis/fa2db89e0143a9a3fda1108eb3b1f715 to your computer and use it in GitHub Desktop.
Save yanisurbis/fa2db89e0143a9a3fda1108eb3b1f715 to your computer and use it in GitHub Desktop.
import { Effect } from 'effect'
import { PrismaClientTx } from 'server/modules/prisma-client-tx/interface'
import { runInsideTransaction } from 'server/modules/prisma-client-tx/live'
import { PrismaClient } from 'server/modules/prisma-client/interface'
import { PrismaClientLayerLive } from 'server/modules/prisma-client/live'
import { testHelpers } from 'lib/tests'
const { it, beforeAll, afterEach } = testHelpers(PrismaClientLayerLive)
const tokens = ['foo', 'bar']
const firstVerificationToken = Effect.gen(function* (_) {
const prisma = yield* _(PrismaClient)
return yield* _(
prisma.wrap(_ =>
_.verificationToken.findFirst({
where: {
token: tokens[0],
},
}),
),
)
})
const removeVerificationTokens = Effect.gen(function* (_) {
const prisma = yield* _(PrismaClient)
yield* _(
prisma.wrap(_ =>
_.verificationToken.deleteMany({
where: {
OR: tokens.map(id => ({ identifier: id })),
},
}),
),
)
})
const addVerificationToken = (prisma: PrismaClient | PrismaClientTx, id: string) =>
prisma.wrap(_ =>
_.verificationToken.create({
data: {
identifier: id,
token: id,
expires: new Date(),
},
}),
)
const addVerificationTokensWithoutTransaction = Effect.gen(function* (_) {
const prisma = yield* _(PrismaClient)
yield* _(addVerificationToken(prisma, tokens[0]))
yield* _(Effect.fail({ _tag: 'TestError' as const }))
yield* _(addVerificationToken(prisma, tokens[1]))
})
const addVerificationTokensWithTransaction = Effect.gen(function* (_) {
const prisma = yield* _(PrismaClientTx)
yield* _(addVerificationToken(prisma, tokens[0]))
yield* _(Effect.fail({ _tag: 'TestError' as const }))
yield* _(addVerificationToken(prisma, tokens[1]))
})
describe('transaction management', () => {
beforeAll(removeVerificationTokens)
afterEach(removeVerificationTokens)
it(
'should have no verification tokens after operation failed inside transaction',
Effect.gen(function* (_) {
yield* _(
Effect.ignore(runInsideTransaction(addVerificationTokensWithTransaction)),
)
const vt = yield* _(firstVerificationToken)
expect(vt).toBeNull()
}),
)
it(
'should have one verification token after operation failed without transaction',
Effect.gen(function* (_) {
yield* _(Effect.ignore(addVerificationTokensWithoutTransaction))
const vt = yield* _(firstVerificationToken)
expect(vt).toMatchObject({ identifier: tokens[0] })
}),
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment