tinyplex / tinybase

The reactive data store for local‑first apps.
https://tinybase.org
MIT License
3.39k stars 67 forks source link

Use a prisma schema with TinyBase so you can sync with a hosted postgres db #56

Open dillondotzip opened 1 year ago

dillondotzip commented 1 year ago

I'd like to have a single prisma schema that can be used with the inside setTablesSchema().

An example schema.primsa file:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

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

// --------------------------------------

model User {
  id             Int          @id @default(cuid())
  createdAt      DateTime     @default(now())
  updatedAt      DateTime     @updatedAt
  email          String       @unique
  hashedPassword String?
  role           String       @default("USER")
  avatar         Json?
  tokens         Token[]
  sessions       Session[]
  todos            Todo[]
}

model Session {
  id                 Int       @id @default(cuid())
  createdAt          DateTime  @default(now())
  updatedAt          DateTime  @updatedAt
  expiresAt          DateTime?
  handle             String    @unique
  hashedSessionToken String?
  antiCSRFToken      String?
  publicData         String?
  privateData        String?
  user   User? @relation(fields: [userId], references: [id])
  userId Int?
}

model Token {
  id          Int       @id @default(cuid())
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt
  hashedToken String
  lastFour String?
  type        TokenType
  expiresAt   DateTime
  sentTo      String?
  user   User? @relation(fields: [userId], references: [id])
  userId Int?
  @@unique([hashedToken, type])
}

enum TokenType {
  RESET_PASSWORD
  INVITE_TOKEN
  PUBLIC_KEY
  SECRET_KEY
}

model Todo {
  id         String   @id @default(cuid())
  createdAt  DateTime @default(now())
  modifiedAt DateTime @default(now())
  name String
  slug String @unique
  user   User @relation(fields: [userId], references: [id])
  userId Int
}

Notice the @unqiue & @relation helpers

andrictham commented 5 months ago

As a start, it would be helpful if we could type our Tinybase tables by passing in generated Prisma types as a type parameter to Tinybase’s setTablesSchema function.

Alternatively, an officially-supported Prisma generator which auto-generates Tinybase schemas would be extremely helpful to DRY up types.

Right now, it’s a pain to write a schema twice: once in Prisma, and another time when setting up Tinybase using setSchema or setTablesSchema. Getting them to sync up is a pain.

Even if the data doesn’t sync up, having the types sync up with Prisma would be a massive DX improvement.

jamesgpearce commented 3 weeks ago

I am going to focus on schemas in 5.1 and 5.2. Hang in there!