Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validateUniquess optional prismaClient parameter #5763

Merged
25 changes: 25 additions & 0 deletions packages/api/src/validations/__tests__/validations.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1144,4 +1144,29 @@ describe('validateUniqueness', () => {
}
expect.assertions(1)
})

it('uses the given prisma client', async () => {
const mockFindFirstOther = jest.fn()
const mockPrismaClient = {
$transaction: async (func) =>
func({
user: {
findFirst: mockFindFirstOther,
},
}),
}
mockFindFirstOther.mockImplementation(() => null)

expect(mockFindFirstOther).not.toBeCalled()
await validateUniqueness(
'user',
{ email: '[email protected]' },
{ prismaClient: mockPrismaClient },
() => {
expect(true).toEqual(true)
}
)
expect(mockFindFirstOther).toBeCalled()
expect(mockFindFirst).not.toBeCalled()
})
})
16 changes: 13 additions & 3 deletions packages/api/src/validations/validations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,9 @@ interface PresenceValidatorOptions extends WithOptionalMessage {
allowEmptyString?: boolean
}

interface UniquenessValidatorOptions extends WithRequiredMessage {}
interface UniquenessValidatorOptions extends WithOptionalMessage {
cannikin marked this conversation as resolved.
Show resolved Hide resolved
prismaClient?: PrismaClient
cannikin marked this conversation as resolved.
Show resolved Hide resolved
}
type UniquenessWhere = Record<'AND' | 'NOT', Array<Record<string, unknown>>>

interface ValidationRecipe {
Expand Down Expand Up @@ -632,10 +634,10 @@ export async function validateUniqueness(
| ((tx: PrismaClient) => Promise<any>),
callback?: (tx: PrismaClient) => Promise<any>
): Promise<any> {
const db = new PrismaClient()
const { $self, $scope, ...rest } = fields
let options = {}
let options: UniquenessValidatorOptions = {}
let validCallback: (tx: PrismaClient) => Promise<any>
let db = null

if (typeof optionsOrCallback === 'function') {
validCallback = optionsOrCallback
Expand All @@ -644,6 +646,14 @@ export async function validateUniqueness(
validCallback = callback as (tx: PrismaClient) => Promise<any>
}

if (options.prismaClient) {
const { prismaClient, ...restOptions } = options
options = restOptions
db = prismaClient
} else {
db = new PrismaClient()
}

const where: UniquenessWhere = {
AND: [rest],
NOT: [],
Expand Down