valtyr / prisma-kysely

🪄 Generate Kysely types directly from your Prisma schema!
https://www.npmjs.com/package/prisma-kysely
MIT License
951 stars 36 forks source link

Feature Request: External typescript types #83

Closed fauh45 closed 6 months ago

fauh45 commented 1 year ago

While it is already possible to set typescript type declaration for columns in prisma schema using /// @kyselyType( ... ). I don't think there's a way to set the column type with typescript definition outside of the schema. This will be so useful for JSON column types, as sometimes it does contains a complex metadata structure, that's usually opaque to the programmer.

I suppose it'll be great to have something like,

types.ts

export type Metadata = {
    tracking_id: string,
    userLocation: {
        ...
    },
    ...
}

prisma.schema

model User {
    id String @id

    // Import would be based on the root of the project, or maybe the output of the file. This part might be the most complex part, resolving the module
    /// @kyselyType( import('./types.ts').Metadata )
   module Json
}
valtyr commented 1 year ago

Hey there @fauh45, this is a valid point. There's a solution on the roadmap which is tracked in #61. The idea is to allow users to include a "prelude", basically a string prepended to the generated file. This prelude could include import statements etc.

The funny thing is though is that we already support the exact syntax you suggested by total accident! If you make the import relative to the directory the generated file ends up in, it works great. This was absolutely unintentional which is hilarious, but actually a pretty powerful feature.

valtyr commented 1 year ago

I might just add this to the README to be fair 😆

valtyr commented 1 year ago

The schema:

datasource db {
    provider = "mysql"
    url      = "mysql://root:mysql@localhost:22332/test"
}

generator kysely {
    provider = "node ./dist/bin.js"
}

model User {
    id String @id

    /// @kyselyType( import('./jsonTypes.ts').Metadata )
    module Json
}

Gives the following result:

CleanShot 2023-11-01 at 10 50 03@2x

With the file jsonTypes.ts located in the output directory.

fauh45 commented 1 year ago

Ups I didn't see #61 sorry!

And somehow the syntax I wrote just works with kysely-prisma? I should've tried generating what I made first lol. Well this revelation fixes my problem then, I could just import my types relative to output folder, which should be easy.

Also, you should absolutely put this to README haha, or if you want i can shoot a PR as well.

valtyr commented 6 months ago

Hey @fauh45 if you still want to create a PR that adds this to the README that would be great :) Otherwise, I'm closing this issue for now.