DavidHancu / prisma-util

Merge multiple Prisma schema files, model inheritance, resolving name conflicts and timings reports, all in a simple tool.
Apache License 2.0
40 stars 1 forks source link

[v1.4.0] Creating schemas using JavaScript #1

Closed DavidHancu closed 2 years ago

DavidHancu commented 2 years ago

Creating schemas with JavaScript and TypeScript

Hey everyone! I've recently got an idea from seeing how many people requested this, so here is my proposal.

Design

My aim is to make this system as easy as possible and as such I thought about this feature as a perfect fit for the Experimental tag. To use it, you'd have to add 2 more keys in your configuration file:

{
    "codeSchemas": true,
    "codeGenerators": ["file.generator.js"]
}

As with any experimental feature, you have to add codeSchemas to enable the feature. The codeGenerators array provides a list of relative paths for the config generators.

Code

This is an example of how I thought the code part could work:

import { SchemaCreator, Constraints } from "@prisma-util/schema-creator";

export default async function createSchema()
{
    SchemaCreator.model("User")
                             .column("id", "Int", Constraints.ID, Constraints.DEFAULT("autoincrement"))
                             .column("name", "String", Constraints.UNIQUE)
                             .column("posts", "Post[]");
    SchemaCreator.model("Post")
                             .column("id", "Int", Constraints.ID, Constraints.DEFAULT("autoincrement"))
                             .column("title", "String", Constraints.UNIQUE)
                             .column("userId", "Int")
                             .column("user", "User", Constraints.RELATION(["userId"], ["id"]);             
    return SchemaCreator.build();
}

This would create the schema:

model User {
    id Int @id @default(autoincrement())
    name String @unique
    posts Post[]
}

model Post {
    id Int @id @default(autoincrement())
    title String @unique
    userId Int
    user User @relation(fields: [userId], references: [id])
}

As you can see, everything you need is under the Constraints object. Some values (like DEFAULT and RELATION in this example) are callable, and the value you provide will be passed as an argument in your schema.

Wrapping Up

Let me know what you think about this proposal and any improvements you'd like to see!

DavidHancu commented 2 years ago

Confirmed coming in v1.4.0.

DavidHancu commented 2 years ago

Implemented in v1.3.0.