Jiří ProcházkaArticles

Jiří Procházka Articles

VueNuxt#frontend

Welcome Prisma Monorepo!

2 months ago - 12 min read #prisma, #backend

On my simple projects I'm using Prisma for querying database. My current project is set of web applications supported by shared libraries, all that running on Nuxt with layers using NPM workspaces.

Prisma Schemas

Prisma is defining database schemas in prisma.schema files, like this:

...
model User {
  id        Int      @id @default(autoincrement())
  title     String   @db.VarChar(255)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

It makes sense to have models defined along the lib code (in each particular layer).

Problem is Prisma is not handle multiple schema files.

Prisma Monorepo

The solution is Prisma Monorepo. Imagine following project structure:

my-project
  - packages
    - app
      ...
      - prisma/schema.prisma
      ...
    - lib
      ...
      - prisma/lib.prisma
      ...

First install the package as a dev dependency to the web app project and initializing project:

$ npm i -D prisma-monorepo
$ npx prisma-monorepo init // this will create prisma-monorepo.json file in the root folder

The only configuration is set the relative paths in the prisma-monorepo.json file in the root folder of the web app directory.

Usage

The rest is simple, just instead of npx prisma generate you run npx prisma-monorepo generate.
And that's it.

How it works

It takes all the models, enums, types and views from the merged schema files (in the example above ./packages/lib/prisma/lib.schema and merge them in to the project standard prisma.schema file.

You can notice that in the merge models there is on the position of the first field a comment with a @@source attribute:

model Subscription {
  // @@source("../../packages/lib/prisma/lib.prisma")
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  User      User?
}

This is telling Prisma Monorepo to regenerate the model when generating next time and gives you a visual hint where it came from.

Do not edit models marked with @@souce attribute! They will be regenerated when generating next time! The rest of the file is safe to be edited as you wish. For example you can add a relation to Subscription on the Post model like this:

model Post {
  id             String       @id @default(uuid())
  ...
  subscriptionId Int
  subscription   Subscription @relation(fields: [subscriptionId], references: [id])
}

Now when you run npx prisma-monorepo format or regenerate with npx prisma-monorepo generate it will add the counterpart field to the Car model.
(Or in Visual Studio Code with a Prisma extension you can just save the file and it will do the same)

Jiří Procházka Newsletter

Want to get new tips for Vue & Nuxt?