Coder Social home page Coder Social logo

graphql-nexus / nexus-prisma Goto Github PK

View Code? Open in Web Editor NEW
555.0 22.0 45.0 4.55 MB

Prisma plugin for Nexus

Home Page: https://graphql-nexus.github.io/nexus-prisma

License: MIT License

TypeScript 92.63% JavaScript 6.74% Shell 0.63%
nexus prisma graphql api crud generation nexus-prisma prisma-generator prisma-schema custom-scalars

nexus-prisma's People

Contributors

0x77dev avatar 2-am-zzz avatar ahmedelywa avatar alexis-anzieu-ssense avatar andrewicarlson avatar arvindell avatar boostvolt avatar flada-auxv avatar haleksandre avatar heddendorp avatar iddan avatar jasonkuhrt avatar jolg42 avatar kashifnazar avatar lewebsimple avatar lvauvillier avatar martzoukos avatar mrbrownt avatar nvitaterna avatar qantata avatar renovate[bot] avatar rostislav-simonik avatar ruheni avatar sadmanyasar avatar semantic-release-bot 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nexus-prisma's Issues

Release hello world package

Perceived Problem

Need to reboot the nexus-prisma package

Ideas / Proposed Solution(s)

Last version before deprecation last year was 0.16. Let's start at 0.20.0.

runtime `$settings` not exported from nexus-prisma

Screenshot

image

Description

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

image

Had a look into it & also noticed this, should that also be if (!ctx[settings.runtime.data.prismaClientContextField]) (once its configurable that is)?

Enhance Nexus .type JSDoc with scalar info as found in GraphQL doc

Add support for BigInt scalar

Perceived Problem

Ideas / Proposed Solution(s)

  • Use https://www.graphql-scalars.dev/docs/scalars/big-int

  • 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

Support output attribute for the generator

Perceived Problem

The generator does not support the output property of other prisma generators

Ideas / Proposed Solution(s)

Read and respect the output property in the schema definition like

generator nexusPrisma {
   provider = "nexus-prisma"
   output   = "../lib/nexus"
}

Possibility to change generated model names

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);
  },
});

Ideas / Proposed Solution(s)

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.

Document 1:1 relations

Perceived Problem

  • We have some support for generated resolvers for 1:1 relations now but its not documented so might as well not exist :)

Test gentime settings system

What

  • we currently have no coverage over the gentime settings system
  • check that config file errors, static OR runtime, are gracefully handled
  • check that files of correct name/place are read as expected
  • check that changing the settings actually has the intended effect

Why

  • lot of IO and state and logical branching around this, no obvious bugs here, but not obviously no bugs!

How

  • some kind of e2e test, multiple
  • we can reuse our TestProject class abstraction

DMMF dynamic require causing MODULE_NOT_FOUND

Screenshot

Screenshot from 2021-06-04 14-57-04

Description

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:

https://github.com/prisma/nexus-prisma/blob/acfdc6b08f84a0c752ec0edc8cc251c81302294f/src/helpers/prisma.ts#L14-L23

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.

Possible solutions

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?

Repro Steps

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

Validate peer dependencies

Perceived Problem

Peer dependency warnings provided by package managers are weak. Users often ignore. Or don't see at all.

Ideas / Proposed Solution(s)

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.

t.dateTime scalar helper not working

Description

The t.dateTime scalar shorthand does not function as expected

Repro Steps/Link

  1. Installed the NexusPrismaScalar types in the types array for makeSchema
  2. Attempted to write a definition for a field like:
t.dateTime(User.createdAt.name, User.createdAt)
  1. Received an error:
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.

Filtering on relations

Perceived Problem

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).

Ideas / Proposed Solution(s)

E.g. check how TypeGraphQL does it:
https://typegraphql.com/docs/prisma.html

nexus-prisma generator gets stucked

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:

image

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:

image

I am not sure if i am doing something wrong, is it a issue or a mistake?

Test all officially supported versions of Prisma in CI

What

  • We list multiple versions of Prisma in our peer dependency requirements
  • In CI we only test what is in our dev dependencies
  • This means we are not testing everything we claim to support

Why

  • Increase confidence both us and our users

How

  • gh matrix, prisma version dimension matching what we put into our peer dep package json value
  • install a version of prisma right before testing

Notes

  • This is going to get intense to test each combo of prisma/Node/OS... 😱

Dependencies missing

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

generation setting to disable default advisory JSDoc

Perceived Problem

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.

Ideas / Proposed Solution(s)

  • Gentime setting to disable default advisory JSDoc

Vercel e2e test

What

  • NP fails on vercel deployments

Why

  • something to do with @prisma/client import not working

How

  • write an e2e test

Generate Nexus object type def field configurations from Prisma model scalar fields

Perceived Problem

  • Unable to statically import the models from Prisma Schema into code

Ideas / Proposed Solution(s)

The scope here:

  1. For each scalar field in each PS model
  2. Generate Nexus field config (name, description, type)
  3. Ignore scalar fields in PS that would require custom scalars in Nexus

Resolvers are free for scalar fields already in Nexus.

Officially support Node 16

What

  • We don't have node 16 in our test matrix

Why

  • This means we don't officially support it

How

  • Simply add it to the ci test matrix

Configuration system

Perceived Problem

  • no way to configure runtime
  • no way to configure gentime

Ideas / Proposed Solution(s)

  • gentime configuration file + API
  • runtime configuration API

Write about architecture

Perceived Problem

Not clear what is runtime vs build time.

Ideas / Proposed Solution(s)

Talk about when/how the prisma generator runs.
Talk about the static runtime and how it boots over the given dmmf structure.

Support projecting enums

Perceived Problem

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'],
})

Ideas / Proposed Solution(s)

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

On Windows, the `gentimeSettings` are written broken to the file because of `endent`

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

Lift 1:1 "Nullable on Without-Relation-Scalar Side" limitation

Perceived Problem

Ideas / Proposed Solution(s)

  • Configuration option to generate a guaranteed relation, essentially cheating what the resolver can actually using Prisma Client? Is this a problem in theory but never practice or a real risk of runtime bugs?

Workarounds

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),
    })
  },
})

Entity types cannot be resolved in PNPM monorepo

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.

Screenshot

image

It's a similar issue to this one for Prisma: prisma/prisma#7484

Error: Cannot find module 'fs-jetpack'

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

Always set `rejectOnNotFound` to false

Description

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.

Have generated JSDoc list enum members

Perceived Problem

  • Manual doc already alludes to the members, suggesting innate desire for this feature

image

Ideas / Proposed Solution(s)

  • JSDoc lists the members of the enum

Error: Cannot find module 'ts-node'

Description

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)

Repro Steps/Link

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"
    }
}

Proposed resolution

Adding ts-node fixed the issue but I'm assuming this package should have ts-node listed under dependencies rather than as a devDependency.

nexus-prisma throw error type on build

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'

Screenshot

image

Repro Steps/Link

Link Repository

Mapping prisma int id to graphql int scalar instead of ID scalar

Perceived Problem

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" });
  },
});

Ideas / Proposed Solution(s)

To go along with prisma typing, int ids should be mapped to graphql int scalar instead of the ID scalar

Think about how to handle bundled TypeScript dependency...

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:

  1. Create a nexus-prisma-cli package that users can install into their development dependencies.
  2. Change our internal implementation strategy to be based on raw string construction of JS and TS declaration files.

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.

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.