chrishoermann / zod-prisma-types

Generator creates zod types for your prisma models with advanced validation
Other
579 stars 43 forks source link

ERR_UNSUPPORTED_DIR_IMPORT #149

Closed TamirCode closed 1 year ago

TamirCode commented 1 year ago

when starting the server I have this error

$ npx nodemon
[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node index.ts`
C:\Users\pathToProject\server\node_modules\ts-node\dist-raw\node-internal-modules-esm-resolve.js:362
    const err = new ERR_UNSUPPORTED_DIR_IMPORT(path, fileURLToPath(base));
                ^
CustomError: ERR_UNSUPPORTED_DIR_IMPORT C:\Users\pathToProject\server\prisma\generated\zod C:\Users\pathToProject\server\index.ts
    at finalizeResolution (C:\Users\pathToProject\server\node_modules\ts-node\dist-raw\node-internal-modules-esm-resolve.js:362:17)
    at moduleResolve (C:\Users\pathToProject\server\node_modules\ts-node\dist-raw\node-internal-modules-esm-resolve.js:801:10)
    at Object.defaultResolve (C:\Users\pathToProject\server\node_modules\ts-node\dist-raw\node-internal-modules-esm-resolve.js:912:11)
    at C:\Users\pathToProject\server\node_modules\ts-node\src\esm.ts:218:35
    at entrypointFallback (C:\Users\pathToProject\server\node_modules\ts-node\src\esm.ts:168:34)
    at C:\Users\pathToProject\server\node_modules\ts-node\src\esm.ts:217:14
    at addShortCircuitFlag (C:\Users\pathToProject\server\node_modules\ts-node\src\esm.ts:409:21)
    at resolve (C:\Users\pathToProject\server\node_modules\ts-node\src\esm.ts:197:12)
    at resolve (C:\Users\pathToProject\server\node_modules\ts-node\src\child\child-loader.ts:15:39)
    at nextResolve (node:internal/modules/esm/loader:163:28) {
  url: 'file:///C:/Users/pathToProject/server/prisma/generated/zod'
}
[nodemon] app crashed - waiting for file changes before starting...

There are also typescript errors in the generated file: image

environment:

vscode 1.79.0 windows 10 node latest stable version v18.16.0 npm version 9.7.1 standard nodejs express typescript server, not using NextJS

tsconfig.json

{
    "compilerOptions": {
        "target": "ESNext",
        "module": "ESNext",
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "strict": true,
        "esModuleInterop": true,
        "lib": [
            "ESNext"
        ],
    },
    "ts-node": {
        "esm": true
    },
}

package.json

{
    "name": "server",
    "version": "1.0.0",
    "description": "",
    "main": "index.ts",
    "type": "module",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "@prisma/client": "^4.8.0",
        "@trpc/server": "^10.29.1",
        "@types/cors": "^2.8.13",
        "cors": "^2.8.5",
        "express": "^4.18.2",
        "zod": "^3.21.1",
        "zod-prisma-types": "^2.7.1"
    },
    "devDependencies": {
        "@types/express": "^4.17.15",
        "@types/node": "^18.11.18",
        "nodemon": "^2.0.20",
        "prisma": "^4.8.0",
        "ts-node": "^10.9.1",
        "typescript": "^4.9.4"
    }
}

schema.prisma

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

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

generator zod {
    provider = "zod-prisma-types"
}

model User {
    id        Int      @id @default(autoincrement())
    /// @zod.string.min(2, { message: "Must be between 2-12 characters" }).max(12, { message: "Must be between 2-12 characters" })
    username  String   @unique
    password  String
    settings  Json?
    role      Role     @default(USER)
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt

    // one to many
    posts    Post[]    @relation("posts")
    comments Comment[] @relation("comments")

    // many to many
    likedPosts       Post[]    @relation("likedPosts")
    dislikedPosts    Post[]    @relation("dislikedPosts")
    likedComments    Comment[] @relation("likedComments")
    dislikedComments Comment[] @relation("dislikedComments")
}

model Post {
    id        Int      @id @default(autoincrement())
    content   String
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt

    // many to one
    user     User      @relation("posts", fields: [userId], references: [id])
    userId   Int
    comments Comment[]

    // many to many
    likes    User[] @relation("likedPosts")
    dislikes User[] @relation("dislikedPosts")
}

model Comment {
    id        Int      @id @default(autoincrement())
    content   String
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt

    // one to many
    user   User  @relation("comments", fields: [userId], references: [id])
    userId Int
    post   Post? @relation(fields: [postId], references: [id])
    postId Int?

    // many to many
    likes    User[] @relation("likedComments")
    dislikes User[] @relation("dislikedComments")

    // one to many self-reference
    childComments   Comment[] @relation("replies")
    // many to one self-reference
    parentComment   Comment?  @relation("replies", fields: [parentCommentId], references: [id])
    parentCommentId Int?
}

enum Role {
    USER
    ADMIN
}

in my index.ts, im importing UserCreateInputSchema and it auto imports succesfully. index.ts

import { PrismaClient, Prisma } from "@prisma/client"
import exp from "express"
import cors from "cors"
import { initTRPC } from '@trpc/server'
import * as trpcExpress from '@trpc/server/adapters/express'
import { UserCreateInputSchema } from './prisma/generated/zod'

const app = exp()
// app.use(exp.json())
app.use(cors())
const prisma = new PrismaClient()

const t = initTRPC.create()

const appRouter = t.router({
    getUsers:
        t.procedure
            .query(() => prisma.user.findMany()),
    createUser:
        t.procedure
            .input(UserCreateInputSchema)
            .mutation(async (opts) => {
                const { input } = opts
                console.log("OPTS =====================================")
                console.log(opts)
                const user = await prisma.user.create({ data: input })
                return user
            }),
})

export type AppRouter = typeof appRouter

app.use('/trpc', trpcExpress.createExpressMiddleware({
    router: appRouter,
    // createContext: createContext,
}))

app.listen(3001, () => console.log("localhost:3001"))

things I've tried:

TamirCode commented 1 year ago

tried updating dependencies as well

"dependencies": {
    "@prisma/client": "^4.8.0",
    "@trpc/server": "^10.29.1",
    "@types/cors": "^2.8.13",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "zod": "^3.21.1",
    "zod-prisma-types": "^2.7.1"
},
"devDependencies": {
    "@types/express": "^4.17.17",
    "@types/node": "^20.3.0",
    "nodemon": "^2.0.20",
    "prisma": "^4.8.0",
    "ts-node": "^10.9.1",
    "typescript": "^5.0.2"
}
chrishoermann commented 1 year ago

please try updating prisma, @prisma/client to the latest version (4.15) and zod-prisma-types to 2.7.4 and see if the error still occures

TamirCode commented 1 year ago

please try updating prisma, @prisma/client to the latest version (4.15) and zod-prisma-types to 2.7.4 and see if the error still occures

this has resolved the original issue. The typescript errors are still there , even if I remove Comments table from the schema (which has a self reference foreign key so I thought it might be causing problems) But that will be separate issue and it doesn't bother me right now maybe in the future when i deploy or something it will be problematic idk. thanks!

TamirCode commented 1 year ago

yea i cant start the server cuz of the typescript errors, they come with delay haha i thought i was clear. I'll open new issue for that