Как реализовать отношение дружбы-как-взаимной-подписки в схеме Prisma ORM?

Я начал с такой схемы, где пользователи связаны отношением многие ко многим:

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id              String   @id @default(auto()) @map("_id") @db.ObjectId
  followers       User[]   @relation("UserFollows", fields: [followerIds], references: [id])
  followerIds     String[] @map("follower_ids") @db.ObjectId
  subscriptions   User[]   @relation("UserFollows", fields: [subscriptionIds], references: [id])
  subscriptionIds String[] @map("subscription_ids") @db.ObjectId
}

И эти связи поддерживать довольно легко:

export class UsersService {
  constructor(private readonly prisma: PrismaService) {}

  async subscribeUser(followerId: string, subscriptionId: string) {
    await this.prisma.user.update({
      where: { id: followerId },
      data: { subscriptions: { connect: { id: subscriptionId } } },
    });

    return {
      message: 'User successfully subscribed',
    };
  }
}

Но как, в таком случае, реализовать и поддерживать между ними отношение дружбы-как-взаимной-подписки?

Как лучше решить эту проблему без постоянного перерасчёта взаимного пересечения этих списков?


Ответы (0 шт):