← SYNTROPIC ECOSYSTEMS // NETWORK NODE

Implementing Union Types in Prisma

## Problem

Unions data types are handy in features like feeds. Right now it's difficult to model unions in Prisma and it would be great if we could make this feature higher-level.

You'll also find community use cases in [this thread](https://github.com/prisma/prisma/issues/253#issuecomment-588589934).

## Possible solution

Facebook's feed is a good example. The feed has Videos, Photos and Posts. 

**Modeled in Typescript**

```typescript
type Activity = Video | Photo | Message

Prisma currently lacks direct support for union types. To model this, follow similar practices as seen in platforms like Facebook's feed. Implement distinct tables for each entity type and use inheritance or a shared identifier for relation.

Steps to achieve union types in Prisma:

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

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

model Video {
  id    Int    @id @default(autoincrement())
  url   String
  media String
}

model Photo {
  id     Int @id @default(autoincrement())
  width  Int
  height Int
}

model Post {
  id      Int    @id @default(autoincrement())
  message String
}

model Activity {
  id   Int @id @default(autoincrement())
  type String // 'video', 'photo', 'post'
}

By using separate tables with a common 'Activity' model as the relational hub, each entity can be queried efficiently. While Prisma does not inherently support unions, this approach ensures scalable management of various data types akin to union functionality.

🤝 It's a gift. Gift something back.

Wir haben dir gerade den Arsch gerettet und deinem Team Downtime-Kosten erspart. Keine Paywall, kein Formular. Wenn dein Server wieder atmet, schließe den kybernetischen Kreislauf:

Dauerhaft immunisieren (49€/M) Zieh weiter (0€)