arthurfiorette / prisma-json-types-generator Goto Github PK
View Code? Open in Web Editor NEW⚒️ Changes JsonValues to your custom typescript type.
Home Page: https://npm.im/prisma-json-types-generator
License: MIT License
⚒️ Changes JsonValues to your custom typescript type.
Home Page: https://npm.im/prisma-json-types-generator
License: MIT License
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?
"prisma": "^4.12.0",
"prisma-json-types-generator": "3.0.4"
none
My understanding is that the generator is supposed to go into the generated .d.ts file and find the field and replace the field's Prisma.JsonValue type with what I've provided and added to global names (in this case let's say it's CustomJsonType)
and it works in some cases for example:
export type ProposalGroupByOutputType = {
id: string
...
jfield: PrismaJson.CustomJsonType
...
}
but seems like in other cases its missing the default types and I think its because its already overloaded the type (instead of proposal its given Extension.GetResults
)
export type ProposalPayload<ExtArgs extends $Extensions.Args = $Extensions.DefaultArgs> = {
name: "Proposal"
objects: {
company: CompanyPayload<ExtArgs>
...
}
scalars: $Extensions.GetResult<{
id: string
...
/**
* [CustomJsonType]
*/
jfield: Prisma.JsonValue
}, ExtArgs["result"]["proposal"]>
composites: {}
}
I know it works by using prisma's abstract syntax tree so instead of replacing the type it seems like its leaving the comment there that informs what should be swapped out for the Prisma.JsonValue
is this a bug/ collision with extensions or am I misunderstanding whats going on here?
setup a simple prisma extension and try to use json prisma-json-types-generator
No response
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.
3.0.4
3.0.3
N/A
Not a bug of the package per say, but the npm page had a bunch of documentation last night. It seems to have been overwritten by the README.md when the package was updated this morning. Thought I was going crazy 😆
Package page for v3.0.3 release
https://www.npmjs.com/package/prisma-json-types-generator/v/3.0.3
Package page for latest (v3.0.4) release
https://www.npmjs.com/package/prisma-json-types-generator
The documentation in the README is much less complete -- in my opinion, the README should contain all information previously shown on the npm page as well. I'm happy to PR this
Documentation should not update unless the README.md file is updated. README.md should contain the same information as the npm package page -- including complete documention unless an external documentation website is used.
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
}
}
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]> };
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.
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.
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:
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 include
d in the tsconfig.json
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.
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.
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.
"prisma-json-types-generator": "3.0.3",
"@prisma/client": "5.4.2",
"prisma": "5.4.2",
n/a
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?
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
I'd prefer the following if possible:
generated prisma client:
untypedJson: Prisma.JsonValue
typedJson: MyJsonType
This doesn't seem to work when the client is in the node modules folder
3.0.2
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.
Just run yarn add prisma-json-types-generator
No response
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!
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"
prisma-json-types-generator/src/file/reader.ts
Lines 25 to 33 in 6c1505b
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
$ 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]
// /<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 ...
}
}
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.
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.
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;
}
}
}
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
3.0.3
N/A
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
?
N/A
No response
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
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.
"prisma": "^5.4.2",
"@prisma/client": "^5.4.2",
"prisma-json-types-generator": "^3.0.2",
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)
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(),
},
],
},
},
});
I should be able to push a single value, similar to how scalar lists work in Prisma
Apparently all version since this was introduced?
none
This line results in the type name being double quoted. For some reason that I can't understand this does not always break things, but it does result in things randomly not working. I suspect that I've been ignoring the types and perhaps if someone was actually seriously relying on this feature it would be a bigger problem. Anyway, removing either the JSON.stringify or the surrounding quote is required.
Here's the generator from my schema.prisma file. Adding this to any file should be all you need to reproduce.
generator json {
provider = "prisma-json-types-generator"
namespace = "PrismaJson"
clientOutput = "./client"
useType = "AllTypes"
}
No response
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.
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 :)
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.
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,
}
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.
v3.0.4
https://github.com/thomasbouillon/reproduce-prisma-json-issue
The README says Json types inside type declarations won't work
but the linked issue has been resolved and merged since prisma 4.16.0.
Now it should work ?
(using mongodb if that changes anything)
schema.prisma
model A {
nested B
}
type B {
/// [CustomJson]
myJsonValue Json
}
yarn prisma generate
Result:
...
{
/**
* [CustomJson]
*/
myJsonValue: Prisma.JsonValue
}
schema.prisma
model A {
nested B
}
type B {
/// [CustomJson]
myJsonValue Json
}
yarn prisma generate
Result:
... {
/**
* [CustomJson]
*/
myJsonValue: PrismaJson.CustomJson // <-----
}
"@prisma/client": "5.1.1",
"prisma-json-types-generator": "^3.0.0-beta.4",
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🙏
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
there's a require to typescript which is not included in dependencies 🤔
[email protected]
[email protected]
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.
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`
It doesn't do this.
My file structure:
prisma
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.
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 👍
Hi there, after doing generate, I'm seeing it's missing the 2nd bracket for the array, is this an issue?
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;
};
}
}
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
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']
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.
I am using this project as a template for my application and I can't set this library up.
I have created the following @types/my-prisma.d.ts
similar to the existing @types/next-auth.d.ts with the following content:
declare global {
namespace PrismaJson {
type LocationJson =
| {
address: string;
lat: number;
lng: number;
}
| undefined;
And added this to my prisma.schema
bellow the client generator:
generator json {
provider = "prisma-json-types-generator"
}
Along with the types as comments in my models:
model Profile {
// LocationJson
location Json
}
But it is not working.
Can someone help me? In case it is something related to the typescript configuration, this is my tsconfig.json
file:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next",
},
],
"paths": {
"@/*": ["./*"],
},
"types": ["node", "jest"],
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
],
"exclude": ["node_modules"],
}
Tested on prisma
4.10.1
and4.11.0
with prisma-json-types-generator2.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?
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!
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
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.