(
model: string,
fields: Record<string, unknown>,
optionsOrCallback:
| UniquenessValidatorOptions
| ((tx: PrismaClient) => Promise<any>),
callback?: (tx: PrismaClient) => Promise<any>,
)
| 690 | callback?: (tx: PrismaClient) => Promise<any>, |
| 691 | ): Promise<any> |
| 692 | export async function validateUniqueness( |
| 693 | model: string, |
| 694 | fields: Record<string, unknown>, |
| 695 | optionsOrCallback: |
| 696 | | UniquenessValidatorOptions |
| 697 | | ((tx: PrismaClient) => Promise<any>), |
| 698 | callback?: (tx: PrismaClient) => Promise<any>, |
| 699 | ): Promise<any> { |
| 700 | const { $self, $scope, ...rest } = fields |
| 701 | let options: UniquenessValidatorOptions = {} |
| 702 | let validCallback: (tx: PrismaClient) => Promise<any> |
| 703 | let db = null |
| 704 | |
| 705 | if (typeof optionsOrCallback === 'function') { |
| 706 | validCallback = optionsOrCallback |
| 707 | } else { |
| 708 | options = optionsOrCallback |
| 709 | validCallback = callback as (tx: PrismaClient) => Promise<any> |
| 710 | } |
| 711 | |
| 712 | if (options.db) { |
| 713 | const { db: customDb, ...restOptions } = options |
| 714 | options = restOptions |
| 715 | db = customDb |
| 716 | } else { |
| 717 | db = new PrismaClient() |
| 718 | } |
| 719 | |
| 720 | const where: UniquenessWhere = { |
| 721 | AND: [rest], |
| 722 | NOT: [], |
| 723 | } |
| 724 | if ($scope) { |
| 725 | where.AND.push($scope as Record<string, unknown>) |
| 726 | } |
| 727 | if ($self) { |
| 728 | where.NOT.push($self as Record<string, unknown>) |
| 729 | } |
| 730 | |
| 731 | return await db.$transaction(async (tx: PrismaClient) => { |
| 732 | const found = await tx[model].findFirst({ where }) |
| 733 | |
| 734 | if (found) { |
| 735 | validationError('uniqueness', fieldsToString(fields), options) |
| 736 | } |
| 737 | |
| 738 | return validCallback(tx) |
| 739 | }) |
| 740 | } |
no test coverage detected