graphql-nexus / nexus-prisma Goto Github PK
View Code? Open in Web Editor NEWPrisma plugin for Nexus
Home Page: https://graphql-nexus.github.io/nexus-prisma
License: MIT License
Prisma plugin for Nexus
Home Page: https://graphql-nexus.github.io/nexus-prisma
License: MIT License
Need to reboot the nexus-prisma
package
Last version before deprecation last year was 0.16. Let's start at 0.20.0.
Apologies if i'm missing something
Was seeing this error being thrown for a nested resolver
'Prisma client not found in context. Set a Prisma client instance to 'prisma' field of Nexus context'
Looking into it & after seeing the docs were updated to say you could customise the prismaClientContextField
using $settings, but I'm seeing this error when trying
Had a look into it & also noticed this, should that also be if (!ctx[settings.runtime.data.prismaClientContextField])
(once its configurable that is)?
Mention which Node version is needed to support this
watch out for this:
In order to support BigInt in JSON.parse and JSON.stringify, it is recommended to install this npm package together with this scalar. Otherwise, JavaScript will serialize the value as string. json-bigint-patch
The generator does not support the output property of other prisma generators
Read and respect the output property in the schema definition like
generator nexusPrisma {
provider = "nexus-prisma"
output = "../lib/nexus"
}
We want to use nexus-prisma
for our GraphQL server, but we need to adjust how it generates models. We have 170+ data models and it would require a lot of handwork to manually remap each data model. Currently, we have the name of tables as notes
and we want to expose models as Note
. Right now we can do something like this
export const Note = objectType({
name: 'notes',
definition: (t) => {
t.field(notes.id);
t.field(notes.name);
t.field(notes.snippets);
},
});
We would like to do something like this:
export const Note = objectType({
name: 'Note',
definition: (t) => {
t.field(Note.id);
t.field(Note.name);
t.field(Note.snippets);
},
});
I would like to enhance nexus-generator
with model mapping and this would enable rename generated names of models.
generator nexusPrisma {
provider = "nexus-prisma"
modelMapping = [{from: "notes", to: "Note"}]
}
model notes {
id Int @id @default(autoincrement())
name String
}
I don't know what could be ideal mapping object and where should configuration live.
nexus-prisma
returns a "MODULE_NOT_FOUND" error when calling the function that fetches the DMMF.
It looks like the dynamic require here is throwing the error:
When I modify the variable importId
for its default value '@prisma/client' directly in the require like so require('@prisma/client')
it works correctly. So with that in mind I've tried a few "hack" such as trying to wrap the variable in a template literals require(`${importId}`)
as well as appending an empty string require('' + importId)
but both still returned the error.
Integrate the require code within the generated file / generate the prisma helper file with the require
pointing directly to the package name's string instead of using a variable at runtime?
Use dynamic import
instead of require
?
https://github.com/haleksandre/nexus-prisma-test
git clone https://github.com/haleksandre/nexus-prisma-test.git
cd nexus-prisma-test
npm install
npm run build
node dist/server.js
Peer dependency warnings provided by package managers are weak. Users often ignore. Or don't see at all.
Do runtime checks.
Fatal if the package is not even installed (defined as importable).
Warn if the version doesn't satisfy the accepted range.
Allow opting out with an environment variable.
The t.dateTime scalar shorthand does not function as expected
NexusPrismaScalar
types in the types array for makeSchema
t.dateTime(User.createdAt.name, User.createdAt)
TSError: ⨯ Unable to compile TypeScript:
src/modules/User.ts:12:7 - error TS2339: Property 'dateTime' does not exist on type 'ObjectDefinitionBlock<"User">'.
However, there is a fix suggested on the Slack to use the long-form:
t.field(User.createdAt.name, { type: 'DateTime', ...User.createdAt })
and this works.
Ideally, the scalar shorthand should work to avoid having to declare the type for each DateTime field.
Additionally, the documentation in the README is slightly off, the helper is dateTime
instead of datetime
.
This plugin provides you with automatically generated resolvers for relation fields. But it would be nice if it provided you with some filtering options automatically generated for you, ideally exposing the whole querying api of Prisma (or at least some basic stuff).
E.g. check how TypeGraphQL does it:
https://typegraphql.com/docs/prisma.html
SO: Windows 10 Pro
Prisma version: 2.22.1
nexus-prisma version: 0.25.0
I am trying to generate models with nexus-prisma
generator using the prisma generate
command but when i run it, the process get stuck:
You can find the reproduction repo here
I noticed that if i change the generators order inside schema.prisma
file from:
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
generator nexusPrisma {
provider = "nexus-prisma"
}
model User {
id String @id
}
to
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
generator nexusPrisma {
provider = "nexus-prisma"
}
generator client {
provider = "prisma-client-js"
}
model User {
id String @id
}
I got a different error in the prisma generate
process:
I am not sure if i am doing something wrong, is it a issue or a mistake?
Should we set lodash and tslib as dependencies?
prisma:GeneratorProcess Error: nexus-prisma tried to access lodash, but it isn't declared in its dependencies; this makes the require call ambiguous and unsound. +1ms
prisma:GeneratorProcess Required package: lodash +1ms
prisma:GeneratorProcess Required by: nexus-prisma@virtual:d149297c0cf4f50b3fb6ec82369fe41f2fef13a948e55b70deb5b8268bbbce6457e19622118c4920b6b1e740a4520406051c2bf1d4d87be0036c93a3362c0b2a#npm:0.30.0 (via F:\workspace\business\exammgr\service\.yarn\__virtual__\nexus-prisma-virtual-844556d5f5\0\cache\nexus-prisma-npm-0.30.0-36e80aa3ee-15249bf0a1.zip\node_modules\nexus-prisma\dist\generator\models\) +0ms
prisma:GeneratorProcess Error: @nexus/logger tried to access tslib, but it isn't declared in its dependencies; this makes the require call ambiguous and unsound. +0ms
prisma:GeneratorProcess Required package: tslib +1ms
prisma:GeneratorProcess Required by: @nexus/logger@npm:0.2.0 (via F:\workspace\business\exammgr\service\.yarn\cache\@nexus-logger-npm-0.2.0-eb660358ad-d2e7b51f89.zip\node_modules\@nexus\logger\dist\) +0ms
By default we generate this JSDoc:
* ### ️⚠️ You have not writen documentation for ${thisItem}
*
* Replace this default advisory JSDoc with your own documentation about ${thisItem}
* by documenting it in your Prisma schema. For example:
*
Once users learn/know this, they may prefer to disable the default JSDoc.
@prisma/client
import not workingThe scope here:
name
, description
, type
)Resolvers are free for scalar fields already in Nexus.
It would be nice to have the option to generate CRUD resolvers based on our Prisma schema like TypeGraphQL provides!
Not clear what is runtime vs build time.
Talk about when/how the prisma generator runs.
Talk about the static runtime and how it boots over the given dmmf structure.
It is currently not possible to project enums from Prisma schema into the the GraphQL API.
Example:
enum ProjectRole {
admin
developer
collaborator
viewer
}
enumType({
name: 'ProjectRole',
members: ['admin', 'developer', 'collaborator', 'viewer'],
})
Generate representations of Prisma Schema enums.
import { ProjectRole } from 'nexus-prisma'
ProjectRole.name // 'ProjectRole'
ProjectRole.members // ['admin', 'developer', 'collaborator', 'viewer']
enumType(ProjectRole),
It might also be handy to have access to some of the individual pieces of data.
import { ProjectRole } from 'nexus-prisma/data'
ProjectRole.admin // 'admin'
ProjectRole.developer // 'developer'
ProjectRole.collaborator // 'collaborator'
ProjectRole.viewer // 'viewer'
Similarly it might be handy to have access to the types:
import type { ProjectRole } from 'nexus-prisma/types'
type a = ProjectRole.Admin // 'admin'
type b = ProjectRole.Developer // 'developer'
type c = ProjectRole.Collaborator // 'collaborator'
type d = ProjectRole.Viewer // 'viewer'
type z = ProjectRole.$Members // ProjectRole.Admin | ProjectRole.Developer | ProjectRole.Collaborator | ProjectRole.Viewer
It would be great if we could supply a custom location for the prisma client, or automatically pull it from the prisma-client-js
generator output field.
generated nexus prisma to ...
In #49 unexpectedly the Windows tests fail. Turns out the test project is using an output
for the Prisma Client generator
which now would be used (correctly) - and for some reason that path is wrong/invalid.
After some local reproduction I found this in .yalc\nexus-prisma\dist\runtime\index.js
:
const gentimeSettings = {
"projectIdIntToGraphQL": "Int",
"docPropagation": {
"GraphQLDocs": true,
"JSDoc": true
},
"prismaClientLocation": "C:\\Users\\Jan\\AppData\\Local\\Temp\\9dfe0c5ba27ce64390f947e584e3caeb\
ode_modules\\@prisma\\client"
}
Investigation: #49 (comment)
End result: There seems to be unexpected behavior coming from endent
that is used to format that output.
Reproduction:
const endent = require("endent").default;
var string = "c:\\some\\windows\\path\\with\\node_modules\\in\it"
var prettyString = endent`
before
${string}
after
`;
console.log(string + "\n\n" + prettyString);
You will get the following output:
C:\Users\Jan\Documents\throwaway\ententRepro>node repro.js
c:\some\windows\path\with\node_modules\init
before
c:\some\windows\path\with
ode_modules\init
after
vs. expected
C:\Users\Jan\Documents\throwaway\ententRepro>node repro.js
c:\some\windows\path\with\node_modules\init
before
c:\some\windows\path\with\node_modules\init
after
objectType({
name: Profile.$name,
definition(t) {
t.field(Profile.id.name, Profile.id)
t.field(User.profile.name, {
...User.profile,
type: nonNull(User.profile.type),
})
},
})
context.prisma
I'm having trouble running nexus-prisma in PNPM monorepo. I have two packages users
& posts
, when I run the command prisma run generate
, nexus-prisma
get resolved at the root directory instead of the package directory. Which causes entity types cannot be resolved as they got overwritten.
What should be expected is the generated output should be at the package node_modules level instead of the root directory, like @prisma/client
in the screenshot below.
It's a similar issue to this one for Prisma: prisma/prisma#7484
e2e test:
The package fs-jetpack
is causing a MODULE_NOT_FOUND
error.
I believe that this error is thrown because this package is listed in devDependencies
& used in the src/generator/generate.ts
file, which mean it should be use as a dependencies
It seems that there's some sort of interaction between setting rejectOnNotFound: true
for findUnique
globally and how nexus-prisma tries to resolve relations. Because nexus-prisma uses prisma's fluent API, it performs a findUnique
for the parent model, and then tries to fetch the relation via the fluent API, which throws a Not Found
error if the relation is null.
// schema.prisma
model User {
id @id
}
model Post {
id @id
userId String? @map("user_id")
user User? @relation("user_id")
}
import { objectType } from "nexus";
import { Post } from "nexus-prisma";
export const Post = objectType({
name: "Post",
definition(t) {
t.nonNull.id("id");
t.field(Post.user);
}
});
// lib/prisma.ts
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient({
rejectOnNotFound: {
findUnique: true,
},
});
The above causes nexus-prisma to try to run prisma.post.findUnique({ where: { id: <ID> } }).user()
which will throw a not found error if it is null.
Happy to provide any more explanation.
When running npx prisma generate
I'm getting the following error:
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Error:
✔ Generated Prisma Client (2.28.0-dev.5) to ./node_modules/@prisma/client in 130ms
Error: Cannot find module 'ts-node'
Require stack:
-.../node_modules/nexus-prisma/dist/generator/gentime/settingsLoader.js
- .../node_modules/nexus-prisma/dist/cli/nexus-prisma.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
at Function.Module._load (internal/modules/cjs/loader.js:746:27)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.loadUserGentimeSettings (.../node_modules/nexus-prisma/dist/generator/gentime/settingsLoader.js:9:20)
at Object.onGenerate (.../node_modules/nexus-prisma/dist/cli/nexus-prisma.js:41:26)
at LineStream.<anonymous> (.../node_modules/@prisma/generator-helper/dist/generatorHandler.js:13:46)
at LineStream.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
package.json
{
"dependencies": {
"@prisma/client": "^2.27.0",
"graphql": "^15.5.1",
"nexus": "^1.1.0",
"nexus-prisma": "^0.29.1"
},
"devDependencies": {
"prisma": "^2.27.0"
}
}
Adding ts-node fixed the issue but I'm assuming this package should have ts-node listed under dependencies
rather than as a devDependency
.
I set up a minimal project with typescript, apollo-server, prisma, nexus, and nexus-prisma with 2 tables and 1:n relation
on developing everything looks good, But when I build the project nexus-prisma throw error Type 'Post' does not satisfy the constraint 'NexusNonNullableTypes'
Currently, prisma ids (even integers) are mapped to graphql ID scalar which are mapped to typescript strings
This goes in conflict with prisma itself which maps ids into their corresponding type (int or string)
For example, If I am to return the result of a prisma query in a resolver, I will receive a type error because of that confilct which is what I am facing right now.
export const User = objectType({
name: _User.$name,
definition(t) {
t.field(_User.id.name, User.id);
},
});
export const UserQuery = queryField((t) => {
t.nonNull.field("me", {
type: "User",
async resolve(_, __, { prisma, auth }) {
const me = await prisma.user.findUnique({
where: {
id: auth!.userId,
},
});
if (!me) {
throw new AuthenticationError("You id does not exist in the database");
}
return me;
},
});
});
I receive this error
Types of property 'id' are incompatible. Type 'number' is not assignable to type 'MaybePromise<string>'
As a workaround, I manually changed the type
export const User = objectType({
name: _User.$name,
definition(t) {
t.field(_User.id.name, { type: "Int" });
},
});
To go along with prisma typing, int ids should be mapped to graphql int scalar instead of the ID scalar
We currently depend on typescript
package so that we can internally manually write TS source and then just use TS compiler API to emit the JS and declaration files.
This has the benefit of allowing us in the future to use ts-moprh
to construct the source code and also the benefit of generating something that looks very natural to how it would have looked were the source statically shipped.
But neither of these benefits are particularly user facing, meanwhile there is a significant user facing downside which is that they will need to tree-shake their application before going to production, otherwise end up with a 50mb in their node_modules from the typescript
package.
This should be fine for Next.js apps where tree-shaking is built in (sort of, its using webpack 4 with poor support but hopefully will switch to webpack 5.x soon (it is already advertised on their blog since last year to try it, and that they are internally with their projects) and anyways I think the current behaviour with webpack 4 should be good enough to get the job done here.
Two other solutions here that come to mind:
nexus-prisma-cli
package that users can install into their development dependencies.Currently I personally think we should go the tree-shake route. Its forward facing meaning where the industry is going anyways, and is the ideal for all parties assuming user has it setup already e.g. Next.js or can easily whip out e.g. Parcel with success.
One criticism is that bundlers for backend projects are a lot less common than for frontend ones. However with serverless that I think is become less of an issue, where more and more projects are open to the idea out of necessity or optimization.
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.