Giter Site home page Giter Site logo

arthurfiorette / prisma-json-types-generator Goto Github PK

View Code? Open in Web Editor NEW
320.0 320.0 16.0 664 KB

⚒️ Changes JsonValues to your custom typescript type.

Home Page: https://npm.im/prisma-json-types-generator

License: MIT License

JavaScript 1.48% TypeScript 97.25% Shell 1.27%
json prisma types

prisma-json-types-generator's Introduction


I'm a passionate software engineer from Brazil 🇧🇷. My enthusiasm for open-source projects brings people together globally and propels us toward a brighter future. When I'm not coding, you'll catch me indulging in mountain biking, playing Counter-Strike, volleyball, or assisting beginners with coding.

My focus is on full-stack development. I embarked on my coding journey in late 2018 with Java, initially experimenting with Minecraft plugins. Since then, I've expanded my skills to develop a range of applications, from SaaS enterprise projects to a TypeScript framework, and even my own programming language.




Twitter Instagram Twitch Discord Mail Steam Reddit LinkedIn


prisma-json-types-generator's People

Contributors

413n avatar andrewsouthpaw avatar arthurfiorette avatar dependabot[bot] avatar emroot avatar jackall3n avatar janpio avatar thibaultleouay avatar yarmeli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

prisma-json-types-generator's Issues

Generated `client/index.d.ts` file has type errors

Tested on prisma 4.10.1 and 4.11.0 with prisma-json-types-generator 2.4.0.

There are type errors like:

Namespace '".../prisma/client/index".Prisma' has no exported member 'StringNullableFilter'

'".../prisma/client/index".Prisma' has no exported member named 'StringNullableWithAggregatesFilter'. Did you mean 'StringWithAggregatesFilter'?

and so on.

Can you have a look at this?

[Docker] /bin/sh: 1: prisma-json-types-generator: not found

Hi,
I'm having trouble generating prisma client inside Docker image.

I'm running a monorepo setup, with 2 apps using database package.

packages/database/package.json

{
  "dependencies": {
    "@prisma/client": "4.15.0"
  },
  "devDependencies": {
    "prisma": "4.15.0",
    "prisma-json-types-generator": "2.4.0"
  }
}

packages/database/prisma/schema.prisma

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["fullTextSearch", "filteredRelationCount", "extendedWhereUnique"]
  binaryTargets   = ["native", "darwin-arm64"]
}

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

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

model Site {
  id        String   @id @default(cuid())
  name      String
  slug      String   @unique @default("")
  /// [Settings]
  settings  Json     @default("{}")
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Dockerfile

# ...

FROM base AS production-deps
WORKDIR /app
RUN corepack enable
# ENV NODE_ENV production
RUN pnpm install --prod --no-frozen-lockfile
COPY --from=pruner /app/out/full/packages/database/prisma /app/packages/database/prisma
RUN pnpx prisma generate --schema /app/packages/database/prisma/schema.prisma

# ...

Error log:

#29 [production-deps 5/5] RUN pnpx prisma generate --schema /app/packages/database/prisma/schema.prisma
#29 1.350 .../.local/share/pnpm/store/v3/tmp/dlx-7 | Progress: resolved 1, reused 0, downloaded 0, added 0
#29 2.188 .../.local/share/pnpm/store/v3/tmp/dlx-7 |   +2 +
#29 2.256 .../dlx-7/node_modules/@prisma/engines postinstall$ node scripts/postinstall.js
#29 2.352 .../.local/share/pnpm/store/v3/tmp/dlx-7 | Progress: resolved 2, reused 0, downloaded 2, added 2, done
#29 3.356 .../dlx-7/node_modules/@prisma/engines postinstall: Done
#29 3.709 .../v3/tmp/dlx-7/node_modules/prisma preinstall$ node scripts/preinstall-entry.js
#29 3.787 .../v3/tmp/dlx-7/node_modules/prisma preinstall: Done
#29 6.295 Prisma schema loaded from packages/database/prisma/schema.prisma
#29 6.802 warn Preview feature "filteredRelationCount" is deprecated. The functionality can be used without specifying it as a preview feature.
#29 7.065 Error: Generator "prisma-json-types-generator" failed:
#29 7.065 
#29 7.065 /bin/sh: 1: prisma-json-types-generator: not found
#29 7.065 
#29 7.080  ERROR  Command failed with exit code 1: prisma generate --schema /app/packages/database/prisma/schema.prisma

Could be related to #82 but I've tried removing NODE_ENV without any luck.

Is there anything I'm missing to make it work inside docker container?
It's working locally without any issues.

Potential improvements to docs

Hey @arthurfiorette, great work here! It's very exciting to have a way to provide TS type definitions, it was a huge sticking point to working with JSON columns in Prisma.

While setting it up for $WORK, I ran into a few stumbling blocks:

  1. It wasn't obvious to me that index.ts was just a demo file, and didn't have specific significance of being called index.ts to the plugin. All that matters is that it's included in the tsconfig.json
  2. In a monorepo, simply having the file in include isn't sufficient to get types, you also need to ensure the file is imported at runtime if it's separated out, e.g.
// package1/prisma/jsonTypes.ts
declare global { ... }

// package1/src/client.ts
import '../prisma/jsonTypes.ts' // if this is omitted, types are silently `any`

export const client = new PrismaClient(...)

// package2/src/index.ts
import { client } from 'package1/src/client.ts'

// now types will be correct

If you think these notes would add clarity and you'd like them in the docs, I'm happy to throw together a quick PR.

untyped fields used to be Prisma.JsonValue and now are unknown

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

"prisma-json-types-generator": "3.0.3",
"@prisma/client": "5.4.2",
"prisma": "5.4.2",

A minimal reproducible example

n/a

Description

In previous versions of this plugin, untyped fields would be left alone (as if the plugin wasn't used), which meant they would be of type Prisma.JsonValue, in the current version the choice seems to be between unknown and any.

Is there any option to type the fields which have the necessary triple-slash comment, but let prisma use its default Prisma.JsonValue for the fields which don't?

Steps to Reproduce

in schema:

model TestModel {
  untypedJson: Json
  /// [MyJsonType]
  typedJson: Json
}

and in code:

declare global {
  namespace PrismaJson {
    type MyJsonType = { foo: string }
  }
}

generated prisma client:

untypedJson: unknown
typedJson: MyJsonType

Expected Behavior

I'd prefer the following if possible:

generated prisma client:

untypedJson: Prisma.JsonValue
typedJson: MyJsonType

StringNullableListFilter not defined

Hey!

I'm getting these typing issues when I'm running tsc:

node_modules/.prisma/client/index.d.ts:143:70 - error TS2724: '"../node_modules/.prisma/client/index".Prisma' has no exported member named 'StringNullableListFilter'. Did you mean 'StringNullableFilter'?

143 export type TypedStringNullableListFilter<S extends string> = Prisma.StringNullableListFilter & {
                                                                         ~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/.prisma/client/index.d.ts:144:12 - error TS2304: Cannot find name 'Enumerable'.

144   equals?: Enumerable<S> | null
               ~~~~~~~~~~

node_modules/.prisma/client/index.d.ts:146:14 - error TS2304: Cannot find name 'Enumerable'.

146   hasEvery?: Enumerable<S>
                 ~~~~~~~~~~

node_modules/.prisma/client/index.d.ts:147:13 - error TS2304: Cannot find name 'Enumerable'.

147   hasSome?: Enumerable<S>
                ~~~~~~~~~~

node_modules/.prisma/client/index.d.ts:154:9 - error TS2304: Cannot find name 'Enumerable'.

154   set?: Enumerable<S>
            ~~~~~~~~~~

node_modules/.prisma/client/index.d.ts:155:14 - error TS2304: Cannot find name 'Enumerable'.

155   push?: S | Enumerable<S>
                 ~~~~~~~~~~

node_modules/.prisma/client/index.d.ts:162:9 - error TS2304: Cannot find name 'Enumerable'.

162   set?: Enumerable<S>
            ~~~~~~~~~~

If I omit this in schema.prisma

generator json {
  provider = "prisma-json-types-generator"
  // namespace = "PrismaJson"
  // clientOutput = "<finds it automatically>"
  // (./ -> relative to schema, or an importable path to require() it)
}

tsc builds everything without issue.

Allow integers to be typed as enums

Hey! Thanks for the library, it works great.

I think the following would be a cool feature.

/// [PaymentStatus]
status        Int       @default(0) @db.TinyInt
enum PaymentStatus {
  Unpaid = 0,
  Paid = 1,
}

Inconsistent behavior when generating in parallel

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

[email protected]
[email protected]

Description

I have a prisma-generate script in my package.json for 3 different prisma packages (each with different schemas/databases/etc.)

When I run pnpm run -r prisma-generate, it runs the generate script for all my database packages in parallel. Sometimes, it leads to issues where the custom types from prisma-json-types-generator don't get defined properly. It seems like there is some sort of collision/race condition going on here.

My suspicion is there is some shared resource that has a race condition.

Steps to Reproduce

I described above, but it's kind of hard to reliably reproduce. I see this occur in CI like 5% of the time. The issue I get is something like:

// prismaJsonTypesNamespace.ts
interface MyCustomInterface {
  name: string
}
/// [MyCustomInterface]
dataField  Json

Then my CI fails with some type error trying to access a property:

`name` does not exist on property `dataField`

Expected Behavior

It doesn't do this.

[Best practice] Should I add a version to my json schemas for future changes?

I read that it is prefered to add a version number to the jsonb data to represent which schema we are using. Is this a good practice with this extention? I'm looking for best practice for future migrations and all but I couldn't find much informations other than an old blog post about Json in RDBMS

Not an issue per se but quite important so users don't regret later down the road I guess :P

export {};
declare global {
	namespace PrismaJson {
		// you can use typical basic types
		type MyType = boolean;
		// or you can use classes, interfaces, object types, etc.
		export type MyJsonV1 = {
			schemaV: number;
			foo: string;
			bar: number;
		}
	}

}

feat: convert untyped json from `any` to `unknown`

Discussed in #110

Add a strictJson property to when Json fields are found without any /// [Type] comment, they should be changed to unknown. Also need to discuss whether it should be enabled by default, breaking change but increases type safety (which kind is what this package is aiming to help with), or not.

Implementation details:

Probably start with:

These two IFs ignores the field type in case the model comment could not be found (a.k.a json field without type comment), probably there you'll also need to call the function to change the types, but this time, using 'unknown' if the strictJson property is enabled.

How does this work?

Hi, I have spent an hour trying to figure this out but still can't understand how it should work.

I have this schema

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

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

model UserHouseInfo {
  id     Int  @id @default(autoincrement())
  userId Int
  user   User @relation(fields: [userId], references: [id])
  /// [HouseInfo]
  info   Json

  @@index([userId])
}

and then generate. I will only have this

declare global {
  namespace PrismaJson {}
}

export type UserHouseInfo = {
  id: number
  userId: number
  /**
   * [HouseInfo]
   */
  info: PrismaJson.HouseInfo
}

where PrismaJson.HouseInfo is just any.

I have another type file that include HouseInfo like this

export type HouseInfo = {
	name: string;
	address: string;
};

but I'm uncertain how it's linked together. Can someone walk me through it? Or update the readme for better steps? Thanks :)

Document when `declare global` is needed

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

3.0.3

A minimal reproducible example

N/A

Description

Some users report that they must remove declare global from the types.ts file in order to make the JSON types work with Prisma. I also experienced this.

Do we know in which cases declare global is needed and not? Can it be documented in the README?

Steps to Reproduce

N/A

Expected Behavior

No response

Found unsupported required field type - `InputJsonValue | null`

versions:

"@prisma/client": "5.1.1",
"prisma-json-types-generator": "^3.0.0-beta.4",

Description:

model sample {
   metadata Json?
}

if you try to run generate with an optional json field you will get the following error

PrismaJsonTypesGeneratorError: Found unsupported required field type
    at findNewSignature (...monorepo/node_modules/prisma-json-types-generator/src/helpers/find-signature.ts:161:15)
    at replaceObject (...monorepo/node_modules/prisma-json-types-generator/src/handler/replace-object.ts:52:44)
    at handleStatement (...monorepo/node_modules/prisma-json-types-generator/src/handler/statement.ts:41:29)
    at handlePrismaModule (...monorepo/node_modules/prisma-json-types-generator/src/handler/module.ts:38:22)
    at ...monorepo/node_modules/prisma-json-types-generator/src/on-generate.ts:41:27
    at visitNodes (...monorepo/node_modules/typescript/lib/typescript.js:31214:30)
    at forEachChildInSourceFile (...monorepo/node_modules/typescript/lib/typescript.js:31573:20)
    at Object.forEachChild (...monorepo/node_modules/typescript/lib/typescript.js:31988:47)
    at SourceFileObject.NodeObject.forEachChild (...monorepo/node_modules/typescript/lib/typescript.js:168280:23)
    at Object.onGenerate (...monorepo/node_modules/prisma-json-types-generator/src/on-generate.ts:38:12) {
  signature: 'InputJsonValue | null',
  typeToChange: 'PrismaJson.SampleMetadata',
  type: 'sample',
  fieldName: 'metadata',
  throwOnNotFound: true
}

I know that it's still in beta but I saw your comment in prisma/prisma#3219 (comment) , and can be considered stable. so I thought it's worth mentioning this to maintainers attention .

thank you fro the great hack really life saving🙏

How do I access a global namespace from another file

I cant seem to be able to access the global namespace I created from another file.
I created the global namespace in a package(internal package) and I'm trying to access it where I imported the package.

I created the global namespace in globalNamespace.ts

import 'prisma-json-types-generator'
declare global {
  namespace PrismaJsonTypes {
    // Details
  }
}

Allow native types as comments

When using the /// [type] syntax, it gets replaced as PrismaJson.type.

We should allow a custom syntax like /// [!number] or /// (number) to just use it as a type and avoid having the always update the PrismaJson interface. Complex types like /// ((string | number | ({a: string} & number)[]) should also be supported.

Example:

model Model {
  /// (string | number)
  type Json

  /// ((string | number | ({a: string} & number)[])
  complex Json
}

Prisma 5.1.0 Support

It appears that Prisma 5.1.0 made various changes to type system, breaking prisma-json-types-generator completely.

See Prisma 5.1.0 Release Notes.

It would be awesome to upgrade this project to support 5.1.0, or otherwise let the community know if this extension cannot be made work with 5.1.0.

Support for generating string discriminated unions

Hey @arthurfiorette thank you for the awesome utility here! We're planning on using it at Replo to auto-generate types for the json models in our database. I was wondering if you'd be willing to accept a PR which implemented support for discriminated unions of strings as well as json (happy to help with the implementation if you can point me to the right place). Our use case is:

// schema.prisma
model MyModel {
    /// [ModelKind]
    kind                          String?          @db.VarChar(512)
    // ...
}

// index.ts
declare global {
  namespace PrismaJson {
    // ...
    type ModelKind =
      | "page"
      | "article"
      | "section";
  }
}

Ideally, we'd like the generated client to have all MyModel operations return types have the kind be typed as the ModelKind DU. Currently, this gives this not supported error, so I assume supporting this would involve handing the String type correctly there and outputting the alias.

Let me know what you think! If you're down to accept something like this, let me know if that implementation seems correct and we can start working on a prototype 👍

Improve CI to automatic test against multiple `clientExtension`s.

Currently, our CI just runs test agains a static example without any clientExtensions enabled. However, clearly a more robust CI with various extensions enabled is needed to avoid problems such as #93 and #91.

I'll leave this issue open for now in case someone wants to contribute. I do not have anything specific on mind, but having expect-type or alternatives would be a good start.

Does not seem to work anymore with prisma 4.16

Hi! Thanks a lot for this package, I love it and it helps me a lot!

Today, prisma asked to upgrade :

Update available 4.15.0 -> 4.16.1
Run the following to update
  yarn add --dev prisma@latest
  yarn add @prisma/client@latest

which I did. Now, prisma generate fails:

Prisma schema loaded from db/backend/schema.prisma
Error:
✔ Generated Prisma Client (4.16.1 | library) to ./node_modules/@prisma-db-backend/client in 71ms

Provided object is not a type literal: runtime.Types.DefaultSelection<ProfilePayload>

I tried going back to Prisma 4.15 and no issue.

can't use enum for String[] type

Since prisma doesn't support Enum Arrays as types, I'd like to map a String[] field to a typescript Enum array. Something like this:

declare global {
  enum UserPermission {
    CanCreateCourse = 'CanCreateCourse',
  }
}
model User {
  id             String            @id @default(cuid())
  /// [UserPermission]
  permissions    String[]          @default([])
}

While this works fine today during runtime, when I run npx prisma generate, I get these errors:

Running generate... - Prisma Json Types Generator
✘ Type UserPayload.permissions is not supported.
✘ Type UserGroupByOutputType.permissions is not supported.
✘ Type UserWhereInput.permissions is not supported.
✘ Type UserScalarWhereWithAggregatesInput.permissions is not supported.
✘ Type UserCreateInput.permissions is not supported.
✘ Type UserUncheckedCreateInput.permissions is not supported.
✘ Type UserUpdateInput.permissions is not supported.
✘ Type UserUncheckedUpdateInput.permissions is not supported.
✘ Type UserCreateManyInput.permissions is not supported.
✘ Type UserUpdateManyMutationInput.permissions is not supported.
✘ Type UserUncheckedUpdateManyInput.permissions is not supported.
✘ Type UserCreateWithoutPasswordInput.permissions is not supported.
✘ Type UserUncheckedCreateWithoutPasswordInput.permissions is not supported.
✘ Type UserUpdateWithoutPasswordInput.permissions is not supported.
✘ Type UserUncheckedUpdateWithoutPasswordInput.permissions is not supported.
✘ Type UserCreateWithoutActivityInput.permissions is not supported.
✘ Type UserUncheckedCreateWithoutActivityInput.permissions is not supported.
✘ Type UserUpdateWithoutActivityInput.permissions is not supported.
✘ Type UserUncheckedUpdateWithoutActivityInput.permissions is not supported.
✘ Type UserCreateWithoutCoursesInput.permissions is not supported.
✘ Type UserUncheckedCreateWithoutCoursesInput.permissions is not supported.
✘ Type UserUpdateWithoutCoursesInput.permissions is not supported.
✘ Type UserUncheckedUpdateWithoutCoursesInput.permissions is not supported.
✘ Type UserCreateWithoutInstitutionInput.permissions is not supported.
✘ Type UserUncheckedCreateWithoutInstitutionInput.permissions is not supported.
✘ Type UserScalarWhereInput.permissions is not supported.
✘ Type UserCreateWithoutRubricsInput.permissions is not supported.
✘ Type UserUncheckedCreateWithoutRubricsInput.permissions is not supported.
✘ Type UserUpdateWithoutRubricsInput.permissions is not supported.
✘ Type UserUncheckedUpdateWithoutRubricsInput.permissions is not supported.
✘ Type UserCreateWithoutStudentsInput.permissions is not supported.
✘ Type UserUncheckedCreateWithoutStudentsInput.permissions is not supported.
✘ Type UserUpdateWithoutStudentsInput.permissions is not supported.
✘ Type UserUncheckedUpdateWithoutStudentsInput.permissions is not supported.
✘ Type UserCreateWithoutTokensInput.permissions is not supported.
✘ Type UserUncheckedCreateWithoutTokensInput.permissions is not supported.
✘ Type UserUpdateWithoutTokensInput.permissions is not supported.
✘ Type UserUncheckedUpdateWithoutTokensInput.permissions is not supported.
✘ Type UserCreateWithoutCreationsInput.permissions is not supported.
✘ Type UserUncheckedCreateWithoutCreationsInput.permissions is not supported.
✘ Type UserUpdateWithoutCreationsInput.permissions is not supported.
✘ Type UserUncheckedUpdateWithoutCreationsInput.permissions is not supported.
✘ Type UserCreateManyInstitutionInput.permissions is not supported.
✘ Type UserUpdateWithoutInstitutionInput.permissions is not supported.
✔ Generated Prisma Client (4.11.0 | library) to ./node_modules/@prisma/client in 302ms
✔ Generated Prisma Json Types Generator (2.2.3) to ./prisma in 1.26s

I'm assuming it's somewhat related to #34, but wanted to create another issue since the end goal is different.

``Provided object is not a type literal`` with `clientExtensions` preview feature enabled

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["orderByNulls", "clientExtensions"]
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
> prisma generate

Environment variables loaded from .env
Prisma schema loaded from prisma\schema.prisma
Error: 
✔ Generated Prisma Client (4.9.0 | library) to .\..\..\node_modules\.pnpm\@[email protected][email protected]\node_modules\@prisma\client in 116ms

Provided object is not a type literal: AnimePayload['scalars']

Couldn't find package "@prisma/[email protected]"

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

3.0.2

Description

I am trying to install with yarn add prisma-json-types-generator but I get the following error:

Couldn't find package "@prisma/[email protected]" required by "prisma-json-types-generator" on the "npm" registry.

I checked the internet connection and it is fine. I was able to install other packages.

Steps to Reproduce

Just run yarn add prisma-json-types-generator

Expected Behavior

No response

Cannot install in npm project, forcing pnpm

Thanks for helping solve such a issue with Prisma!

I am using npm in my project. I didnt want to add another dep manager.

Doing npm i prisma-json-types-generator causes this error and fails to install:

image

Can't set `clientOuput` with an environment variable

Hi! First of all, thanks for making this patch available.

I have not so common requirement (I assume), which is setting prisma's output directory through an environment variable. e.g.

generator client {
  provider      = "prisma-client-js"
  output        = env("PRISMA_OUT_DIR")
  binaryTargets = ["native", "linux-musl"]
}

When I don't define clientOuput it fallbacks to .prisma/client

generator json {
  provider     = "prisma-json-types-generator"
}
Error: 
✔ Generated Prisma Client (4.7.1 | library) to ./apps/payments/node_modules/prisma-generated in 267ms
Cannot find module '/path/to/repo/apps/payments/.prisma/client'
Require stack:

When I define clientOutput as env("PRISMA_OUT_DIR") it looks like it doesn't evaluate the function

generator json {
  provider     = "prisma-json-types-generator"
  clientOutput        = env("PRISMA_OUT_DIR")
}
Error: 
✔ Generated Prisma Client (4.7.1 | library) to ./apps/payments/node_modules/prisma-generated in 259ms
ENOENT: no such file or directory, open '/path/to/repo/apps/payments/prisma/(function)/index.d.ts'

Finally if I harcode the same value as PRISMA_OUT_DIR it works

generator json {
  provider     = "prisma-json-types-generator"
  clientOutput = "../node_modules/prisma-generated"
}

Unfortunately I need the output to be set dynamically through the aforementioned variable. Any chance this is an easy fix?

Types are not replaced in generated files.

Hi,

I am using:

    "prisma": "^5.2.0",
    "prisma-json-types-generator": "^3.0.1",
    "typescript": "^5.2.2",

on mac. After build the result is still:

  /**
   * [VehicleLoanApplicationEntityPayload]
   */
  jsonData: Prisma.JsonValue

But that only happens on my machine. But other devs don't experience that issue. Maybe you have an idea of what can be the reason.

Array syntax missing bracket

Hi there, after doing generate, I'm seeing it's missing the 2nd bracket for the array, is this an issue?

image

My schema looks like:

  /// [TSlide[]]
  slides                  Json?

And I define this like this:


declare global {
  namespace PrismaJson {
    type TSlide = {
      photo: string;
      hidden?: boolean;
      widgetable?: boolean;
      slideshowable?: boolean;
    };
  }
}

Issues with pushing new values to a JSON object array

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

"prisma": "^5.4.2",
"@prisma/client": "^5.4.2",
"prisma-json-types-generator": "^3.0.2",

Description

Hey

I've been trying to add a simple JSON array to keep track of server logs on my Prisma Schema, but I keep getting the following TS error

Type '{ push: { message: string; timestamp: string; }; }' is not assignable to type 'UpdateManyInput<ServerLog> | undefined'.
  Types of property 'push' are incompatible.
    Type '{ message: string; timestamp: string; }' is not assignable to type 'ServerLog[] | ((...items: ServerLog[]) => number) | undefined'.
      Object literal may only specify known properties, and 'message' does not exist in type 'ServerLog[] | ((...items: ServerLog[]) => number)'.ts(2322)

Steps to Reproduce

This is my Prisma Schema:

generator json {
    provider = "prisma-json-types-generator"
}
...

model MyModel {
...
    /// [ServerLog]
    logs  Json[]
...
}

And my types.ts file

namespace PrismaJson {
  type ServerLog = {
    timestamp: string; // Date ISO
    message: string;
  };
}

The namespace and types are generated successfully, but it seems that pushing values into an array has the incorrect type.

The following code gives me the error:

await ctx.prisma.mymodel.update({
  where: {
    id: input.id,
  },
  data: {
    logs: {
      push: {
        message: "My Message Here",
        timestamp: new Date().toISOString(),
      },
    },
  },
});

To "remove" the error, I need to push an array instead of a single value like this:

await ctx.prisma.mymodel.update({
  where: {
    id: input.id,
  },
  data: {
    logs: {
     push: [
        {
          message: `My Message Here`,
          timestamp: new Date().toISOString(),
        },
      ],
    },
  },
});

Expected Behavior

I should be able to push a single value, similar to how scalar lists work in Prisma

"Cannot find module" without `outputs` generator config

Hey Arthur,

First off, thank you so much for the generator. It's a game-changer!

I tried using this in my personal Prisma + NextJS project but ran into a Cannot find module '/<PROJECT_ROOT_PATH>/prisma' error.

The following snippet assumes that when outputs is not specified in the generator config, then options.generator.output?.value will be undefined. However, in my case, even though I am not specifying outputs in generator config, the value of overrideTarget or options.generator.output?.value is "/<PROJECT_ROOT_PATH>/prisma"

declaration.sourcePath = overrideTarget
? overrideTarget.startsWith('.')
? path.resolve(schemaTarget!, overrideTarget)
: require.resolve(overrideTarget)
: path.resolve(
// prisma client directory
path.dirname(require.resolve('.prisma/client')),
'index.d.ts'
);

I console-logged the options object from onGenerate() and below is the full output.

$ npx prisma generate
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
options.generator =  {
  "name": "json_gen",
  "provider": {
    "fromEnvVar": null,
    "value": "prisma-json-types-generator"
  },
  "output": {
    "value": "/<PROJECT_ROOT_PATH>/prisma",
    "fromEnvVar": "null"
  },
  "config": {
    "namespace": "IO"
  },
  "binaryTargets": [],
  "previewFeatures": []
}
Error: 
✔ Generated Prisma Client (4.8.1 | library) to ./node_modules/@prisma/client in 148ms

Cannot find module '/<PROJECT_ROOT_PATH>/prisma'
Require stack:
- /<PROJECT_ROOT_PATH>/node_modules/prisma-json-types-generator/dist/file/reader.js
- /<PROJECT_ROOT_PATH>/node_modules/prisma-json-types-generator/dist/on-generate.js
- /<PROJECT_ROOT_PATH>/node_modules/prisma-json-types-generator/dist/generator.js
- /<PROJECT_ROOT_PATH>/node_modules/prisma-json-types-generator/dist/bin.js

When I hardcode the output = "/<PROJECT_ROOT_PATH>/node_modules/.prisma/client/index.d.ts", then everything works -- it essentially forces this execution branch

Set up

OS & Package Versions

$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 22.04.1 LTS
Release:	22.04
Codename:	jammy


$ yarn list --pattern prisma prisma-json-types-generator
yarn list v1.22.19
├─ @prisma/[email protected]
├─ @prisma/[email protected]
├─ @prisma/[email protected]
├─ @prisma/engines-version@4.8.0-61.d6e67a83f971b175a593ccc12e15c4a757f93ffe
├─ @prisma/[email protected]
├─ @prisma/[email protected]
│  └─ @prisma/[email protected]
├─ @prisma/[email protected]
├─ @prisma/[email protected]
│  └─ @prisma/[email protected]
├─ @prisma/[email protected]
├─ [email protected]
│  ├─ @prisma/[email protected]
│  └─ @prisma/[email protected]
└─ [email protected]
   └─ @prisma/[email protected]

JSON Type Generator setup

// /<PROJECT_ROOT_PATH>/prisma/schema.prisma

generator client {
  provider      = "prisma-client-js"
  binaryTargets = ["native", "linux-musl"]
}

generator json_gen {
  provider = "prisma-json-types-generator"
  namespace = "IO"
}
// /<PROJECT_ROOT_PATH>/index.ts
declare global {
  export namespace IO {
    ... type delcarations ...
  }
}

Local development: running `pnpm test` results in "prisma-json-types-generator: command not found"

While working on #34, I was trying to set up local development for the package and noticed that there was a test command. However, running pnpm build then pnpm test gives the following error for me:

$ pnpm test

> [email protected] test /Users/noahgilmore/code/prisma-json-types-generator
> prisma generate && tsc --noEmit -p tsconfig.test.json

Prisma schema loaded from prisma/schema.prisma
Error: Generator at prisma-json-types-generator could not start:

/bin/sh: prisma-json-types-generator: command not found

 ELIFECYCLE  Test failed. See above for more details.

I'm assuming that this is because we specified the generator as prisma-json-types-generator in schema.prisma, but prisma doesn't know how to find an executable called that name. I've never worked with a custom prisma generator before, but assuming I'm missing a step somewhere? If so, would be happy to document it! Tagging @arthurfiorette since I'm assuming you had a different workflow for when you added these tests.

feat: add `output` param in the `generator`

I'm using pnpm with turborepo in my project and I have a prisma dedicated package.
Unfortunately when I try to generate the schema, the client is generated like this: ✔ Generated Prisma Client (4.8.0 | library) to .\..\..\node_modules\.pnpm\@[email protected][email protected]\node_modules\@prisma\client in 278ms

Instead, looking at the code of this lib, it always search for .prisma/client in the current node_modules directory.

Could you please add the output param in the generator so that we can change the path of the generated client?

Oh and btw, amazing lib! Great work!

pnpm monorepo path issue

require.resolve(path.resolve(clientOutput, '../../.prisma/client'))

When running the generate command, i get this error

Prisma schema loaded from ../../packages/pl-database/prisma/schema.prisma
Error: 
Cannot find module '/Users/jakeleventhal/Code/Ecominate/packages/.prisma/client'

The path that it should be looking in is wrong.
My schema file has this

generator client {
  provider        = "prisma-client-js"
  output          = "./"
  previewFeatures = ["clientExtensions", "fullTextSearch", "fullTextIndex"]
}

If i remove this line

output          = "./"

it works just fine

Getting error in Digital Ocean

I was upgrading some dependencies in my repo and after deploying to digital ocean I got the following error. Any Idea why that would be happening:

› using Ubuntu 18.04 stack
[2023-06-02 00:35:16] │ Detected the following buildpacks suitable to build your app:
[2023-06-02 00:35:16] │ 
[2023-06-02 00:35:16] │    heroku/nodejs-engine   v0.5.2  
[2023-06-02 00:35:16] │    digitalocean/node      v0.3.6  (Node.js)
[2023-06-02 00:35:16] │    digitalocean/procfile  v0.0.3  (Procfile)
[2023-06-02 00:35:16] │    digitalocean/custom    v0.1.1  (Custom Build Command)
[2023-06-02 00:35:16] │ 
[2023-06-02 00:35:16] │ For documentation on the buildpacks used to build your app, please see:
[2023-06-02 00:35:16] │ 
[2023-06-02 00:35:16] │    Node.js  v0.3.6  https://do.co/apps-buildpack-node
[2023-06-02 00:35:16] ╰─────────────────────────────────────────────╼
[2023-06-02 00:35:16] 
[2023-06-02 00:35:16] ╭──────────── build caching ───────────╼
[2023-06-02 00:35:17] │  › checking for cache from a previous build
[2023-06-02 00:35:18] │ Layer cache not found
[2023-06-02 00:35:19] │ Restoring metadata for "heroku/nodejs-engine:nodejs" from app image
[2023-06-02 00:35:19] │ Restoring metadata for "heroku/nodejs-engine:yarn" from app image
[2023-06-02 00:35:19] │ Layer cache not found
[2023-06-02 00:35:20] │ Removing "heroku/nodejs-engine:nodejs", not in cache
[2023-06-02 00:35:20] │ Removing "heroku/nodejs-engine:yarn", not in cache
[2023-06-02 00:35:20] ╰───────────────────────────────────────╼
[2023-06-02 00:35:20] 
[2023-06-02 00:35:20] ╭──────────── app build ───────────╼
[2023-06-02 00:35:20] │ ---> Node.js Buildpack
[2023-06-02 00:35:20] │ ---> Installing toolbox
[2023-06-02 00:35:20] │ ---> - jq
[2023-06-02 00:35:20] │ ---> - yj
[2023-06-02 00:35:20] │ ---> Getting Node version
[2023-06-02 00:35:20] │ ---> Resolving Node version
[2023-06-02 00:35:21] │ ---> Downloading and extracting Node v16.20.0
[2023-06-02 00:35:24] │ ---> Parsing package.json
[2023-06-02 00:35:25] │ ---> Installing [email protected]
[2023-06-02 00:35:26] │ ---> No file to start server
[2023-06-02 00:35:26] │ ---> either use 'docker run' to start container or add index.js or server.js
[2023-06-02 00:35:26] │ Project contains yarn.lock, using yarn
[2023-06-02 00:35:26] │ Warning: a .npmrc file was found. yarn does not read .npmrc files, use .yarnrc instead if needed.
[2023-06-02 00:35:26] │ Installing node_modules using yarn (from yarn.lock)
[2023-06-02 00:35:28] │ Running yarn install
[2023-06-02 00:35:28] │ 
[2023-06-02 00:35:28] │ yarn install v1.22.19
[2023-06-02 00:35:28] │ [1/4] Resolving packages...
[2023-06-02 00:35:29] │ [2/4] Fetching packages...
[2023-06-02 00:36:34] │ warning [email protected]: The engine "pnpm" appears to be invalid.
[2023-06-02 00:36:34] │ [3/4] Linking dependencies...
[2023-06-02 00:36:34] │ warning " > @nhogs/[email protected]" has unmet peer dependency "firebase-admin@^10.0.0 || ^11.0.0".
[2023-06-02 00:36:34] │ warning " > @nx/[email protected]" has unmet peer dependency "@angular-devkit/core@>= 14.0.0 < 17.0.0".
[2023-06-02 00:36:34] │ warning " > @nx/[email protected]" has unmet peer dependency "@angular-devkit/schematics@>= 14.0.0 < 17.0.0".
[2023-06-02 00:36:34] │ warning " > @nx/[email protected]" has unmet peer dependency "@schematics/angular@>= 14.0.0 < 17.0.0".
[2023-06-02 00:36:47] │ [4/4] Building fresh packages...
[2023-06-02 00:36:53] │ $ prisma generate
[2023-06-02 00:36:53] │ Prisma schema loaded from prisma/schema.prisma
[2023-06-02 00:36:54] │ Error: Generator "prisma-json-types-generator" failed:
[2023-06-02 00:36:54] │ 
[2023-06-02 00:36:54] │ /bin/sh: 1: prisma-json-types-generator: not found
[2023-06-02 00:36:54] │ 
[2023-06-02 00:36:54] │ error Command failed with exit code 1.
[2023-06-02 00:36:54] │ info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
[2023-06-02 00:36:54] │ 
[2023-06-02 00:36:54] │ unable to invoke layer creator
[2023-06-02 00:36:54] │ installing node_modules: exit status 1
[2023-06-02 00:36:54] │ ERROR: failed to build: exit status 1
[2023-06-02 00:36:54] │ 
[2023-06-02 00:36:54] │ 
[2023-06-02 00:36:54] │ For documentation on the buildpacks used to build your app, please see:
[2023-06-02 00:36:54] │ 
[2023-06-02 00:36:54] │    Node.js  v0.3.6  https://do.co/apps-buildpack-node
[2023-06-02 00:36:54] │ 
[2023-06-02 00:36:54] │  ✘ build failed

Generated PrismaJson is empty

Running out of ideas how to get this to work. The generated namespace is empty:

/node_modules/.prisma/client/index.d.ts

// This file was overwritten by prisma-json-types-generator
// Report issues to

declare global {
  namespace PrismaJson {}
}

prisma/schema.prisma

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

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

model Run {
  id           String    @id @default(cuid())
  status       RunStatus @default(CREATED)
  public_id    String
  project_name String?
  name         String?
  text         String?   @db.Text
  /// [RunAttributes]
  attributes   Json?
  project_id   String
  project      Project   @relation(references: [id], fields: [project_id])

  @@index([project_id])
}

src/app.d.ts

declare global {
  namespace PrismaJson {
    type RunAttributes = {
      address: string;
      location_type: string | null;
      location_type: "complex_estate" | "free_standing" | "plot_farm" | null;
      complex_name: string | null;
      unit_number: string | null;
      block_name: string | null;
      plot_farm_name: string | null;
      plot_farm_number: string | null;
      additional_notes: string | null;
    };
  }
}
"@prisma/client": "^5.1.1",
"prisma-json-types-generator": "^3.0.0-beta.4",

What am I missing? Thank you!

Library isn't working for me

My file structure:
prisma

  • schema.prisma
    src
  • jsonTypes.ts(the types that I'm using)

My schema.prisma file

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["clientExtensions", "fullTextSearch"]
}

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

generator json {
  provider  = "prisma-json-types-generator"
  namespace = "PrismaJsonTypes"
}

model AppData {
  /// [One of my types]
  aField Json?
}

// My other db schema

My jsonTypes.ts

declare global {
  namespace PrismaJsonTypes {
    // My types
  }
}

When I use prisma to fetch the data, the aField type is any(not Prisma.JsonValue). After inspecting I realised that prisma isn't finding my namespace.

fix: types are not replace using ´pnpm´

When using ´pnpm´, the types are not replaced with the correct namespace in the ´.prisma/client/index.d.ts´ file.
They remains as ´Prisma.JsonValue´.

Using ´yarn´ it works fine.

Add option to use type instead of namespace

It would be very useful if there was a generator option to emit PrismaJson["MyType"] instead of PrismaJson.MyType, unless I'm missing something. This would allow me to do something like

  export type PrismaJson ={ [K in keyof Types]: ValueTree<Types[K]> };

Does triple slash have significance?

I'm not sure, but I think if I'm not using triple slash, my prisma types are not correct when running npx prisma generate. I added triple slash and it worked.

Does the:

declare global {
  namespace PrismaJson {

have to go into a .d.ts file so it gets loaded in order to work? My tsconfig is this:

"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],

So I thought it would read all the types even if I place it in a rnadom .ts file that no one imports.

``Cannot find module '.prisma/client'`` in pnpm workspace

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["orderByNulls", "interactiveTransactions"]
}

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

generator records {
  provider = "prisma-json-types-generator"
  namespace = "PrismaJson"
  clientOutput = ".prisma/client"
}
│ database:build: Require stack:
│ database:build: - ROOT\node_modules\.pnpm\[email protected]\node_modules\prisma-json-types-generator\dist\file\reader.js
│ database:build: - ROOT\node_modules\.pnpm\[email protected]\node_modules\prisma-json-types-generator\dist\on-generate.js
│ database:build: - ROOT\node_modules\.pnpm\[email protected]\node_modules\prisma-json-types-generator\dist\generator.js
│ database:build: - ROOT\node_modules\.pnpm\[email protected]\node_modules\prisma-json-types-generator\dist\bin.js

Include typescript in peerDependencies

When I run it locally it works

but when I run it in a docker environment it throws an error

#17 3.230 Prisma schema loaded from schema.prisma
#17 6.129 Error: Generator "prisma-json-types-generator" failed:
#17 6.129 
#17 6.129 node:internal/modules/cjs/loader:1080
#17 6.129   throw err;
#17 6.129   ^
#17 6.129 Error: Cannot find module 'typescript'
#17 6.129 Require stack:
#17 6.129 - /test/node_modules/.pnpm/[email protected][email protected]/node_modules/prisma-json-types-generator/dist/on-generate.js
#17 6.129 - /test/node_modules/.pnpm/[email protected][email protected]/node_modules/prisma-json-types-generator/dist/generator.js
#17 6.129 - /test/node_modules/.pnpm/[email protected][email protected]/node_modules/prisma-json-types-generator/dist/bin.js
#17 6.129     at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
#17 6.129     at Module._load (node:internal/modules/cjs/loader:922:27)
#17 6.129     at Module.require (node:internal/modules/cjs/loader:1143:19)
#17 6.129     at require (node:internal/modules/cjs/helpers:110:18)
#17 6.129     at Object.<anonymous> (/test/node_modules/.pnpm/[email protected][email protected]/node_modules/prisma-json-types-generator/dist/on-generate.js:5:46)
#17 6.129     at Module._compile (node:internal/modules/cjs/loader:1256:14)
#17 6.129     at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
#17 6.129     at Module.load (node:internal/modules/cjs/loader:1119:32)
#17 6.129     at Module._load (node:internal/modules/cjs/loader:960:12)
#17 6.129     at Module.require (node:internal/modules/cjs/loader:1143:19) {
#17 6.129   code: 'MODULE_NOT_FOUND',
#17 6.129   requireStack: [
#17 6.129     '/test/node_modules/.pnpm/[email protected][email protected]/node_modules/prisma-json-types-generator/dist/on-generate.js',
#17 6.129     '/test/node_modules/.pnpm/[email protected][email protected]/node_modules/prisma-json-types-generator/dist/generator.js',
#17 6.129     '/test/node_modules/.pnpm/[email protected][email protected]/node_modules/prisma-json-types-generator/dist/bin.js'
#17 6.129   ]
#17 6.129 }
#17 6.129 Node.js v18.16.1

My package.json for my db package , I am in a mono repo.

  "dependencies": {
    "@prisma/client": "4.16.2",
    "dotenv-cli": "7.2.1",
    "prisma": "4.16.2",
    "prisma-json-types-generator": "2.5.0",
    "ts-node": "10.9.1",
    "typescript": "5.1.6"
  },

when I look at my local on-generate.js

CleanShot 2023-07-06 at 13 52 50

there's a require to typescript which is not included in dependencies 🤔

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.