@prisma/client#Prisma TypeScript Examples

The following examples show how to use @prisma/client#Prisma. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: entity.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
/**
   * Gets the fields associated with an entity version. This function assumes
   * the given entity ID is of a non-deleted entity. If it is used on a deleted
   * entity it may return fields even though the entity is deleted.
   * @param entityId The entity ID to find fields for
   * @param versionNumber the entity version number to find fields for
   * @param args find many entity fields arguments
   * @returns fields of the given entity at the given version that match given arguments
   */
  async getVersionFields(
    entityId: string,
    versionNumber: number,
    args: Prisma.EntityFieldFindManyArgs
  ): Promise<EntityField[]> {
    return await this.prisma.entityField.findMany({
      ...args,
      where: {
        ...args.where,
        entityVersion: {
          entityId: entityId,
          versionNumber: versionNumber
        }
      }
    });
  }
Example #2
Source File: pool.ts    From backend with MIT License 6 votes vote down vote up
getViableUsers = (toggles: string[]) => {
    const viableUsers: Prisma.studentWhereInput & Prisma.pupilWhereInput = {
        active: true
    };

    if (!toggles.includes("allow-unverified")) {
        viableUsers.verification = null; // require verification to be unset
    }

    /* On production we want to avoid that our testusers [email protected]
    are accidentally matched to real users */
    if (!isDev) {
        viableUsers.email = { not: { startsWith: "test", endsWith: "@lern-fair.de" }};
    }

    return viableUsers;
}
Example #3
Source File: constants.ts    From amplication with Apache License 2.0 6 votes vote down vote up
DEFAULT_PERMISSIONS: Prisma.EntityPermissionCreateWithoutEntityVersionInput[] = [
  {
    action: EnumEntityAction.Create,
    type: EnumEntityPermissionType.AllRoles
  },
  {
    action: EnumEntityAction.Update,
    type: EnumEntityPermissionType.AllRoles
  },
  {
    action: EnumEntityAction.View,
    type: EnumEntityPermissionType.AllRoles
  },
  {
    action: EnumEntityAction.Delete,
    type: EnumEntityPermissionType.AllRoles
  },
  {
    action: EnumEntityAction.Search,
    type: EnumEntityPermissionType.AllRoles
  }
]
Example #4
Source File: TodoListDatabaseQuery.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
private fetchTotalNumberOfDoingTodos(todoListsIds: TodoListId[]) {
    return this.prisma.$queryRaw<{ totalNumberOfDoingTodos: number }[]>`
      SELECT count(*) as "totalNumberOfDoingTodos"
      FROM "Todo" T
      WHERE T."isComplete" IS false AND T."todoListId" IN (${Prisma.join(
        todoListsIds
      )});
    `.then((rows) => rows[0].totalNumberOfDoingTodos);
  }
Example #5
Source File: entity.service.spec.ts    From amplication with Apache License 2.0 6 votes vote down vote up
prismaEntityFieldFindFirstMock = jest.fn(
  (args: Prisma.EntityFieldFindUniqueArgs) => {
    if (args?.include?.entityVersion) {
      return {
        ...EXAMPLE_ENTITY_FIELD,
        entityVersion: EXAMPLE_CURRENT_ENTITY_VERSION
      };
    }
    return EXAMPLE_ENTITY_FIELD;
  }
)
Example #6
Source File: TodoListDatabaseQuery.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
private fetchTodoLists(todoListsIds: TodoListId[]) {
    return this.prisma.$queryRaw<any[]>`
      SELECT TL.id, TL.title, TL."createdAt", count(T.id) as "numberOfTodos"
      FROM "TodoList" TL
      LEFT JOIN "Todo" T ON TL.id = T."todoListId" AND T."isComplete" IS false
      WHERE TL."id" IN (${Prisma.join(todoListsIds)})
      GROUP BY TL.id;
    `;
  }
Example #7
Source File: entity.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async entities(args: Prisma.EntityFindManyArgs): Promise<Entity[]> {
    return this.prisma.entity.findMany({
      ...args,
      where: {
        ...args.where,
        deletedAt: null
      }
    });
  }
Example #8
Source File: notification.ts    From backend with MIT License 6 votes vote down vote up
export async function create(notification: Prisma.notificationCreateInput) {
    if (notification.recipient !== NotificationRecipient.USER) {
        throw new Error("For now, the recipient of a notification must be USER");
    }

    if (notification.active !== false) {
        throw new Error("Notifications must be created in inactive state");
    }

    if (!notification.mailjetTemplateId) {
        throw new Error("As long as Mailjet is our main channel, it is required to set the mailjetTemplateId");
    }

    // To keep DEV and PROD parity, notifications are inserted with their id (see "importNotifications")
    // Unfortunately this creates inconsistency between the ids present and the sequence used to generate new ids
    // Thus the id is manually calculated and does not rely on the DEFAULT value
    const result = await prisma.notification.create({
        data: {
            ...notification,
            id: await prisma.notification.count() + 1
        }
    });

    logger.info(`Notification(${result.id}) created\n`);

    invalidateCache();
}
Example #9
Source File: workspace.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
/**
   * Creates a workspace and a user within it for the provided account with workspace admin role
   * @param accountId the account to create the user in the created workspace
   * @param args arguments to pass to workspace creations
   * @returns the created workspace
   */
  async createWorkspace(
    accountId: string,
    args: Prisma.WorkspaceCreateArgs
  ): Promise<Workspace> {
    // Create workspace
    // Create a new user and link it to the account
    // Assign the user an "ORGANIZATION_ADMIN" role
    const workspace = await this.prisma.workspace.create({
      ...args,
      data: {
        ...args.data,
        users: {
          create: {
            account: { connect: { id: accountId } },
            isOwner: true,
            userRoles: {
              create: {
                role: Role.OrganizationAdmin
              }
            }
          }
        }
      },
      include: {
        ...args.include,
        // Include users by default, allow to bypass it for including additional user links
        users: args?.include?.users || true
      }
    });

    return workspace;
  }
Example #10
Source File: adapter.ts    From prisma-adapter with Apache License 2.0 6 votes vote down vote up
async removeFilteredPolicy(
    sec: string,
    ptype: string,
    fieldIndex: number,
    ...fieldValues: string[]
  ): Promise<void> {
    const line: Prisma.CasbinRuleCreateInput = { ptype };

    const idx = fieldIndex + fieldValues.length;
    if (fieldIndex <= 0 && 0 < idx) {
      line.v0 = fieldValues[0 - fieldIndex];
    }
    if (fieldIndex <= 1 && 1 < idx) {
      line.v1 = fieldValues[1 - fieldIndex];
    }
    if (fieldIndex <= 2 && 2 < idx) {
      line.v2 = fieldValues[2 - fieldIndex];
    }
    if (fieldIndex <= 3 && 3 < idx) {
      line.v3 = fieldValues[3 - fieldIndex];
    }
    if (fieldIndex <= 4 && 4 < idx) {
      line.v4 = fieldValues[4 - fieldIndex];
    }
    if (fieldIndex <= 5 && 5 < idx) {
      line.v5 = fieldValues[5 - fieldIndex];
    }

    await this.#prisma.casbinRule.deleteMany({ where: line });
  }
Example #11
Source File: account.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async createAccount(args: Prisma.AccountCreateArgs): Promise<Account> {
    const account = await this.prisma.account.create(args);
    await this.analytics.identify({
      userId: account.id,
      createdAt: account.createdAt,
      email: account.email,
      firstName: account.firstName,
      lastName: account.lastName
    });
    await this.analytics.track({
      userId: account.id,
      event: EnumEventType.Signup
    });
    return account;
  }
Example #12
Source File: adapter.ts    From prisma-adapter with Apache License 2.0 6 votes vote down vote up
/**
   * @param option It should be PrismaClientOptions or PrismaClient.
   * You should later call open() to activate it.
   */
  constructor(option?: Prisma.PrismaClientOptions | PrismaClient) {
    if (option instanceof PrismaClient) {
      this.#prisma = option;
    } else {
      this.#option = option;
    }
  }
Example #13
Source File: action.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
/**
   * Gets action steps for given action identifier
   * @param actionId action identifier to get steps for
   * @returns array of the steps of the action with ordered logs
   */
  async getSteps(actionId: string): Promise<ActionStep[]> {
    return this.prisma.actionStep.findMany({
      where: {
        actionId: actionId
      },
      orderBy: {
        createdAt: Prisma.SortOrder.asc
      },
      include: {
        logs: {
          orderBy: {
            createdAt: Prisma.SortOrder.asc
          }
        }
      }
    });
  }
Example #14
Source File: adapter.ts    From prisma-adapter with Apache License 2.0 6 votes vote down vote up
#loadPolicyLine = (
    line: Prisma.CasbinRuleCreateInput,
    model: Model
  ): void => {
    const result =
      line.ptype +
      ', ' +
      [line.v0, line.v1, line.v2, line.v3, line.v4, line.v5]
        .filter((n) => n)
        .join(', ');
    Helper.loadPolicyLine(result, model);
  };
Example #15
Source File: block.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
/**
   * Checks if the block has any meaningful changes (some generated properties are ignored : id, createdAt...)
   * between its current and last version.
   * @param blockId The block to check for changes
   * @returns whether the block's current version has changes
   */
  async hasPendingChanges(blockId: string): Promise<boolean> {
    const blockVersions = await this.prisma.blockVersion.findMany({
      where: {
        blockId
      },
      orderBy: {
        versionNumber: Prisma.SortOrder.asc
      }
    });

    // If there's only one version, lastVersion will be undefined
    const currentVersion = blockVersions.shift();
    const lastVersion = last(blockVersions);

    if (currentVersion.deleted && !lastVersion) {
      // The block was created than deleted => there are no changes
      return false;
    }

    return this.diffService.areDifferent(
      currentVersion,
      lastVersion,
      NON_COMPARABLE_PROPERTIES
    );
  }
Example #16
Source File: dummy.resolver.ts    From prisma-nestjs-graphql with MIT License 6 votes vote down vote up
/**
   * Query for single user.
   */
  @Query(() => [Dummy])
  dummies() {
    const dummy = new Dummy();
    dummy.json = {
      a: 1,
    };
    dummy.decimal = new Prisma.Decimal(1.002);
    return [dummy];
  }
Example #17
Source File: block.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async discardPendingChanges(blockId: string, userId: string): Promise<Block> {
    const blockVersions = await this.prisma.blockVersion.findMany({
      where: {
        block: { id: blockId }
      },
      orderBy: {
        versionNumber: Prisma.SortOrder.asc
      },
      include: {
        block: true
      }
    });

    const firstBlockVersion = head(blockVersions);
    const lastBlockVersion = last(blockVersions);

    if (!firstBlockVersion || !lastBlockVersion) {
      throw new Error(`Block ${blockId} has no versions `);
    }

    if (firstBlockVersion.block.lockedByUserId !== userId) {
      throw new Error(
        `Cannot discard pending changes on block ${blockId} since it is not currently locked by the requesting user `
      );
    }

    await this.cloneVersionData(lastBlockVersion.id, firstBlockVersion.id);

    return this.releaseLock(blockId);
  }
Example #18
Source File: transactions.service.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
private async getTransactionsData(
    orderBy: { id: SortOrder },
    limit: number,
    where: Prisma.TransactionWhereInput,
    includeBlocks: boolean,
  ): Promise<Transaction[] | (Transaction & { blocks: Block[] })[]> {
    const transactions = await this.prisma.transaction.findMany({
      orderBy,
      take: limit,
      where,
    });

    if (includeBlocks) {
      const transactionsWithBlocks = [];
      for (const transaction of transactions) {
        const blocks =
          await this.blocksTransactionsService.findBlocksByTransaction(
            transaction,
          );
        transactionsWithBlocks.push({
          ...transaction,
          blocks,
        });
      }
      return transactionsWithBlocks;
    }

    return transactions;
  }
Example #19
Source File: media.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
/**
     * @desc gets the details of a specific production company in the database
     * @param prodCompany - the id of the production company to query
     */
    public async getProductionCompany(prodCompany: string): Promise<ProductionCompanyInterface | null> {
        const media: Pick<SpringMedia, 'id' | 'type' | 'name' | 'background' | 'poster'>[] = await this.prisma.$queryRaw(Prisma.sql`SELECT id, name, type, poster, background FROM "Media",jsonb_array_elements(production) with ordinality arr(production) WHERE arr.production->>'id' = ${prodCompany} ORDER BY name asc;`)

        const confirm = prodCompany.charAt(0) === "s";
        const id = prodCompany.replace(/[ms]/, '');
        const type = confirm ? CompType.NETWORK : CompType.COMPANY;
        const company = await this.tmdb?.getProductionCompany(+id, type);

        if (company) {
            const movies = media.filter(item => item.type === MediaType.MOVIE);
            const shows = media.filter(item => item.type === MediaType.SHOW);
            const images = media.map(e => e.poster);

            return {
                images,
                name: company.name,
                type,
                id: prodCompany,
                movies,
                shows,
                logo: 'https://image.tmdb.org/t/p/original' + company.logo_path,
            }
        }

        return null;
    }
Example #20
Source File: UnbanCommand.ts    From Mandroc with GNU General Public License v3.0 6 votes vote down vote up
static getOrigin(user: string, type: InfractionType): Prisma.Prisma__InfractionClient<{ id: number; messageId: string | null; } | null> {
    return Database.PRISMA.infraction.findFirst({
      where: {
        type: type,
        offenderId: user
      },
      select: {
        id: true,
        messageId: true
      },
      orderBy: {
        id: "desc"
      }
    });
  }
Example #21
Source File: user_repository.ts    From ts-oauth2-server with MIT License 5 votes vote down vote up
constructor(private readonly repo: Prisma.UserDelegate<"rejectOnNotFound">) {}
Example #22
Source File: user.service.spec.ts    From amplication with Apache License 2.0 5 votes vote down vote up
prismaUserRoleFindManyMock = jest.fn(
  (args: Prisma.UserRoleFindManyArgs) => {
    if (args.where.role === EXISTING_ROLE || args.where.role === undefined) {
      return [EXAMPLE_USER_ROLE];
    }
    return [];
  }
)
Example #23
Source File: adapter.ts    From prisma-adapter with Apache License 2.0 5 votes vote down vote up
#option?: Prisma.PrismaClientOptions;
Example #24
Source File: token_repository.ts    From ts-oauth2-server with MIT License 5 votes vote down vote up
constructor(private readonly repo: Prisma.OAuthTokenDelegate<"rejectOnNotFound">) {}
Example #25
Source File: fields.ts    From backend with MIT License 5 votes vote down vote up
@Query(returns => [Subcourse])
    @Authorized(Role.UNAUTHENTICATED)
    @LimitedQuery()
    @PublicCache()
    async subcoursesPublic(
        @Arg("take", { nullable: true }) take?: number,
        @Arg("skip", { nullable: true }) skip?: number,
        @Arg("search", { nullable: true }) search?: string,
        @Arg("onlyJoinable", { nullable: true }) onlyJoinable?: boolean
    ) {

        const filters: Prisma.subcourseWhereInput[] = [{
            published: { equals: true },
            cancelled: { equals: false },
            course: {
                is: {
                    courseState: { equals: CourseState.ALLOWED }
                }
            }
        }];

        if (search) {
            filters.push({
                course: { is: { OR: [
                    { outline: { contains: search, mode: "insensitive" }},
                    { name: { contains: search, mode: "insensitive" }}
                ] }}
            });
        }

        if (onlyJoinable) {
            filters.push({ OR: [
                { joinAfterStart: { equals: false }, lecture: { every: { start: { gt: new Date() }}} },
                { joinAfterStart: { equals: true }, lecture: { some: { start: { gt: new Date() }}} }
            ] });
        }

        return await prisma.subcourse.findMany({
            where: { AND: filters },
            take,
            skip,
            orderBy: { updatedAt: "desc" }
        });
    }
Example #26
Source File: GqlResolverExceptions.filter.spec.ts    From amplication with Apache License 2.0 5 votes vote down vote up
EXAMPLE_PRISMA_UNKNOWN_ERROR = new Prisma.PrismaClientKnownRequestError(
  'Example Prisma unknown error message',
  'UNKNOWN_CODE',
  Prisma.prismaVersion.client
)
Example #27
Source File: token_repository.ts    From ts-oauth2-server with MIT License 5 votes vote down vote up
constructor(private readonly repo: Prisma.OAuthTokenDelegate<"rejectOnNotFound">) {}
Example #28
Source File: pool.ts    From backend with MIT License 5 votes vote down vote up
pools: MatchPool[] = [
    {
        name: "lern-fair-now",
        toggles: ["skip-interest-confirmation"],
        pupilsToMatch: (toggles) => {
            const query: Prisma.pupilWhereInput = {
                isPupil: true,
                openMatchRequestCount: { gt: 0 },
                subjects: { not: "[]"},
                registrationSource: { notIn: ["plus"] }
            };

            if (!toggles.includes("skip-interest-confirmation")) {
                query.OR = [
                    { registrationSource: "cooperation" },
                    { pupil_tutoring_interest_confirmation_request: { status: "confirmed" }}
                ];
            }
            return query;
        },
        studentsToMatch: (toggles) => ({
            isStudent: true,
            openMatchRequestCount: { gt: 0},
            subjects: { not: "[]" },
            screening: { success: true },
            registrationSource: { notIn: ["plus"]}
        }),
        createMatch,
        settings: { balancingCoefficients }
    },
    {
        name: "lern-fair-plus",
        toggles: ["allow-unverified"],
        pupilsToMatch: (toggles) => ({
            isPupil: true,
            openMatchRequestCount: { gt: 0 },
            subjects: { not: "[]"},
            registrationSource: { equals: "plus" }
        }),
        studentsToMatch: (toggles) => ({
            isStudent: true,
            openMatchRequestCount: { gt: 0},
            subjects: { not: "[]" },
            screening: { success: true },
            registrationSource: { equals: "plus" }
        }),
        createMatch,
        settings: { balancingCoefficients }
    },
    {
        name: "TEST-DO-NOT-USE",
        toggles: ["allow-unverified"],
        pupilsToMatch: (toggles) => ({
            isPupil: true,
            openMatchRequestCount: { gt: 0 }
        }),
        studentsToMatch: (toggles) => ({
            isStudent: true,
            openMatchRequestCount: { gt: 0 }
        }),
        createMatch(pupil, student) {
            if (!isDev) {
                throw new Error(`The Test Pool may not be run in production!`);
            }
            return createMatch(pupil, student, this);
        },
        settings: { balancingCoefficients }
    }
]
Example #29
Source File: seed.ts    From telefunc with MIT License 5 votes vote down vote up
todoData: Prisma.TodoCreateInput[] = [
  { title: 'Milk', content: 'Buy milk', completed: false },
  { title: 'Bananas', content: 'Buy bananas', completed: false }
]