GithubHelp home page GithubHelp logo

graphql-nexus / nexus-plugin-prisma Goto Github PK

View Code? Open in Web Editor NEW
830.0 830.0 118.0 5.07 MB

Deprecated

License: MIT License

TypeScript 98.01% JavaScript 1.99%
crud graphql nexus prisma type-safety

nexus-plugin-prisma's People

Contributors

0xflotus avatar 2color avatar ahmedelywa avatar arvindell avatar beeplin avatar bkrausz avatar brannon-darby avatar coopbri avatar craigspaeth avatar dependabot[bot] avatar devanb avatar divideby0 avatar gustawdaniel avatar hajnalben avatar haleksandre avatar jangerhofer avatar janpio avatar jasonkuhrt avatar kyh avatar lvauvillier avatar matart15 avatar nikolasburk avatar pantharshit00 avatar renovate-bot avatar renovate[bot] avatar schickling avatar ssalbdivad avatar t0wer001 avatar tgriesser avatar weakky 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

nexus-plugin-prisma's Issues

mongo dependencies

Is nexus-prisma compatible with mongo version of prisma?
It would be helpful if there is an example repo that has mongo + nexus working

Support for `authorize` on t.prismaFields

@tgriesser is implementing a field-level authorize method in the main nexus repo. Is there a way we could include something similar in t.prismaFields @Weakky?

Something like this:

export const User = prismaObjectType({
  name: 'User',
  definition(t) {
    t.prismaFields([{ 
      name: 'posts', 
      authorize: ()=>{ return true } // auth logic here
    }])
  },
})

Parent Arg in Resolvers don't expose nested fields

I was planning to implement a dataloader for recurring queries such as

{
  user(input: {id: "cjsktbe8r5xpz0b86a0le6efk" }){
    name
    email
    posts {
      author{
        posts {
          author{
            posts{
              author{
                posts{
                  title
                }
              }
            }
          }
          }
        }
      }
    }
  }

So I went to adjust my Post type author field only to find that the parent doesn't expose any of the nested fields on my datamodel, I'm looking to gain access to the author property to send to dataloader as a key:

I only get following properties of the parent exposed

(parameter) post: {
    content?: string | null | undefined;
    createdAt: any;
    id: string;
    published: boolean;
    title: string;
    updatedAt: any;
}
const Post = prismaObjectType({
  name: "Post",
  definition: t => {
    t.prismaFields(["*"]);
    t.field("author", {
      type: "User",
      resolve: async (post, args, ctx) => {
        const author = await ctx.loaders.load(post.author.id)
        return author;
      }
    });

I'm fairly new to using dataloaders, however I have implemented similar dataloaders based on mongoose and a mongodb database.

Thanks for any help to resolve this issue.

Implement GraphQL SDL comment generation

Description

nexus makes it sometimes hard to reason about the relations in your GraphQL schema. To fix that problem, we thought it'd be nice to have generated comments on top of your prismaObjectType calls. eg:

prismaObjectType('Query', t => {
  t.string('hello')
})

Would result in the following generated comment:

/**
 * type Query {
 *   hello: String!
 * }
 */
prismaObjectType('Query', t => {
  t.string('hello')
})

Enhance code generator configuration

Description

There are two things that should be configurable when running nexus-prisma-generate:

  • The path to the output file of the codegen
  • The path to the prisma-client index file

Proposal

Expose two CLI options to input these paths

Question: case when we want explicite schema delegation and integration with prisma-binding

Hello,
Question, please:

On a note on prisma-binding read-me: Unless you explicitly want to use schema delegation we recommend to use Prisma client to build a GraphQL server. I see your are taking the whole thing to a new level with nexus and nexus prisma.

What about the case when we want explicite schema delegation? Can we use nexus-prisma and/or nexus wirth prisma-binding?

nexus-prisma-generate mkdir errors

When running:

npx nexus-prisma-generate --client generated/prisma-client --output generated/nexus-prisma

If generated/nexus-prisma already exists an error is thrown. I expected this to be overwritten.

`t.prismaType.type.resolve` have wrong typing

Description

The code-generated resolve properties currently have the typings that gqliteral expects.
We should instead generated the return type of the resolve properties based on the prisma graphql schema

Check the renderTypeFieldDetails() function in plugin/codegen.ts to find more details

  • Query types
  • Mutation types
  • Subscription types

Question - custom resolvers return null for nested fields

I'm trying to write a custom resolver for one of my queries. This resolver pulls directly from a mysql database (where other resolvers will obviously pull data from the prisma service). The datamodel I have is a User with an Address as a nested field.

The resolver/data model is defined as the following:

t.field("users", "User", {
    ...t.prismaType.users,
    resolve: async (parent, args, ctx) => {
      const result: Array<any> = await users();
      return result;
    }
  });

The users() function is a call to the mysql database that returns a list of users with their respective addresses. This works fine however when i perform the following query:

{
  users{
    id
    first_name
    last_name
    email
    address{
      address_1
      state
    }
  }
}

All the user information returns fine, however the address field is always returning null. I double checked and the data I return for the users() function all has data for the address field. What do I need to do to ensure that the address field returns the full address and NOT null?

Mock prisma for jest unit tests?

makePrismaSchema seems to inject prisma in the context while generating the schema. So when unit testing resolvers like that:

const context = {
  db: {
    user: jest.fn(),
    $exists: { user: jest.fn() },
    createUser: jest.fn(),
  }
}

const SIGNUP_MUTATION = /* GraphQL */ `
  mutation signUp($data: SignUpInput!) {
    signUp(data: $data) {
      email
    }
  }
`;

const user = {
  email: 'test.email.com',
};

context.db.createUser.mockResolvedValue({ ...user });

const res = graphql(schema, SIGNUP_MUTATION, null, context, { data: { idToken: 'TEST_TOKEN' } })

expect(res.data).toEqual({
  signUp: {
    ...user,
  },
});

The real Prisma seems to be called instead of the mocked one:

"message": "request to http://localhost:4466/default/local failed, reason: connect ECONNREFUSED 127.0.0.1:4466"

Naming collision with `nexus` on global interfaces on `inputTypes`

This can be reprocuded using the graphql example from the prisma-examples by removing the skipLibCheck option from tsconfig.json.

$ yarn tsc
yarn run v1.13.0
warning package.json: No license field
$ /Users/nikolasburk/Desktop/prisma-examples/typescript/graphql/node_modules/.bin/tsc
node_modules/nexus-prisma/dist/definitions/inputObjectType.d.ts:13:93 - error TS2344: Type 'string' does not satisfy the constraint '"UserWhereUniqueInput" | "PostWhereInput" | "UserWhereInput" | "PostWhereUniqueInput" | "UserCreateInput" | "PostCreateManyWithoutAuthorInput" | "PostCreateWithoutAuthorInput" | ... 18 more ... | "PostSubscriptionWhereInput"'.

13 export declare function prismaInputObjectType<TypeName extends PrismaInputObjectTypeNames = string>(typeConfig: PrismaInputObjectTypeConfig<TypeName>): core.NexusWrappedType<core.NexusInputObjectTypeDef<TypeName>>;
                                                                                               ~~~~~~

node_modules/nexus-prisma/dist/definitions/objectType.d.ts:15:83 - error TS2344: Type 'string' does not satisfy the constraint '"Query" | "Mutation" | "Subscription" | "Post" | "User" | "UserConnection" | "PageInfo" | "UserEdge" | "AggregateUser" | "PostConnection" | "PostEdge" | "AggregatePost" | "BatchPayload" | "UserSubscriptionPayload" | "UserPreviousValues" | "PostSubscriptionPayload" | "PostPreviousValues"'.

15 export declare function prismaObjectType<TypeName extends PrismaObjectTypeNames = string>(typeConfig: PrismaObjectTypeConfig<TypeName>): core.NexusWrappedType<core.NexusObjectTypeDef<TypeName>>;
                                                                                     ~~~~~~

node_modules/nexus/dist/typegenTypeHelpers.d.ts:3:13 - error TS2320: Interface 'NexusGen' cannot simultaneously extend types 'NexusPrismaTypes' and 'NexusGenTypes'.
  Named property 'inputTypes' of types 'NexusPrismaTypes' and 'NexusGenTypes' are not identical.

3   interface NexusGen {}
              ~~~~~~~~


Found 3 errors.

error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Many mistakes in example code

This code is pulled straight from the docs. Unfortunately there's at least 3 mistakes (specified in comments below).

import { prismaObjectType } from 'nexus-prisma'
import { idArg } from 'nexus-prisma' // ERROR: this should be importing from 'nexus'

const Query = prismaObjectType({ 
  
  name: 'Query',

  // SyntaxError: you've got to decide if this is an arrow function or not
  definition(t) => t.prismaFields(['*']) 

  // TypeError: also the abolve asterisk notation causes a type error 
  //     Argument of type '"*"[]' is not assignable to parameter of type 'AddFieldInput<"objectTypes", "Query">'.

})

Document nexus-prisma-generate

Is there a way to generate javascript files instead of typescript?

Maybe adding something to the generate command.

npx nexus-prisma-generate --client ./src/generated/prisma-client --output ./src/generated/nexus-prisma

I get the below error when trying to use with a javascript project. I think the problem is that the generated/nexus.ts and generated/schema.graphql files are not getting generated.

Expected path for outputs.typegen to be a string, saw src/generated/nexus.ts

Add tests

Add tests for the following functions:

  • prismaInputObjectType
  • prismaEnumType
  • prismaExtendType
  • shouldRelyOnDefaultResolver

nexus-prisma-generate error

Versions:
"nexus": "0.9.11"
"nexus-prisma": "0.2.0"
"prisma-client-lib": "1.26.4"

When I run prisma deploy I experience two different errors depending on how I have defined my hooks -> post-deploy in primsa.yml.

Scenario 1:

Here I have not wrapped the client and output path in double-quotes:

hooks:
  post-deploy:
    - prisma generate
    - npx nexus-prisma-generate --client=./src/generated/prisma-client --output=./src/generated/nexus-prisma

Terminal output:

Deploying service `default` to stage `default` to server `local` 53ms
Service is already up to date.

post-deploy:

Generating schema... 23ms

Running prisma generate...
Saving Prisma Client (TypeScript) at /Users/user/project/src/generated/prisma-client/
Running prisma generate โœ”
npx: installed 85 in 4.658s
prisma_datamodel_1.Parser.create is not a function

Running npx nexus-prisma-generate --client=./src/generated/prisma-client --output=./src/generated/nexus-prisma โœ–

Error: prisma_datamodel_1.Parser.create is not a function

The src/generated/prisma-client/ -path is generated correctly with index.ts and prisma-schema.ts however the src/generated/nexus-prisma/ -path is empty.

Scenario 2:

Here I have wrapped the client and output path in double-quotes:

hooks:
  post-deploy:
    - prisma generate
    - npx nexus-prisma-generate --client="./src/generated/prisma-client" --output="./src/generated/nexus-prisma"

Terminal output:

Deploying service `default` to stage `default` to server `local` 54ms
Service is already up to date.

post-deploy:

Generating schema... 20ms

Running prisma generate...
Saving Prisma Client (TypeScript) at /Users/user/project/src/generated/prisma-client/
Running prisma generate โœ”
npx: installed 85 in 4.691s

Running npx nexus-prisma-generate --client="./src/generated/prisma-client" --output="./src/generated/nexus-prisma"...
ERROR: Cannot find --client path at /Users/user/project/"./src/generated/prisma-client"
Running npx nexus-prisma-generate --client="./src/generated/prisma-client" --output="./src/generated/nexus-prisma" โœ–

Error: ERROR: Cannot find --client path at /Users/user/project/"./src/generated/prisma-client"

In this case only the src/generated/prisma-client/ is present and no src/generated/nexus-prisma/

[nexus-prisma-generate] Allow to put prisma.yml in a custom folder

I'm testing Nexus and trying to migrate an existing application. My prisma.yml file is in a database folder with other files related to Prisma:

  • datamodel.graphql
  • docker-compose.yml
  • prisma.yml
  • seed.graphql

When i try to generate types with:

nexus-prisma-generate --client ./src/generated/prisma-client --output ./src/generated/nexus-prisma

i have the following error:

Could not find `prisma.yml` file

While searching through the code, I found that Nexus-Prisma-generate only allows you to put prisma.yml in the root directory or in a prisma directory:

function findPrismaConfigFile(): string | null {
  let definitionPath: string | null = path.join(process.cwd(), 'prisma.yml')

  if (fs.existsSync(definitionPath)) {
    return definitionPath
  }

  definitionPath = path.join(process.cwd(), 'prisma', 'prisma.yml')

  if (fs.existsSync(definitionPath)) {
    return definitionPath
  }

  return null
}

It would be better allow the user to define the prisma.yml path with a parameter to nexus-prisma-generate, perhaps like this:

nexus-prisma-generate --prisma ./database/prisma.yml --client ./src/generated/prisma-client --output ./src/generated/nexus-prisma

Find a better workflow for code generation

Description

Current code generation lives under the codegen.ts file, and the path to the prisma graphql schema is hard-coded.

For now, the codegen is ran when deploying to prisma (checkout the prisma.yml in the post-hooks) by using the command yarn codegen (defined in the package.json file)

Steps

  • Find a way to pass in the path to the codegen function
  • Decide whether we make it a prisma generator, or we make it a CLI

Add custom query/mutation custom work

Is it possible to add a custom query/mutation without any relationship with datamodelInfo? I mean, I would like to add a query to can be executed through playground but only to do some internal work, generate, re-deploy, executing npm scripts basically..

Like this, where "GenerateInvoices" doesn't exists as an object in its schema, but i would like to publish it and in its resolver, do internal work.

image

Any idea?

Thanks!

An unique `id` field is always assumed when resolving children

Description

When resolving children of a type, eg:

{
  user(where: { id: "" } {
    id
    posts {
	  id
    }
  }
}

The posts field will be resolved as so: ctx.prisma.user({ id: root.id }).posts()
Meaning, we always assume there is a unique field called id on the parent.

We need to find a way to detect what unique field can be used to find the parent

Update peerDependencie nexus from 0.9.14 to 0.9.17

Hello Nexus-Prism Team!

I would like to request the nexus-prisma compatibility with the latest version of the Nexus main framework.

Also, I'd like to know at what level you plan to keep this tool compatible with Nexus. Nexus is in an early stage, it would be very important that my implementations receive the latest bugfixs and features

Graciously

Get rid of the internal caching maps

Description

Because we are automatically exposing input types of object types fields, we need to keep an internal in-memory cache of all the input types that we already exposed to make sure that we do not expose the same input type twice.

The two maps are called __typesMapCache, and __exportedTypesMap

Ideally, we'd get rid of that cache which could cause issues in the future.

This cache is already invalidated every time prismaMakeSchema() is called, through the invalidateCache() function

Question - custom resolvers return null nested fields

I'm trying to write a custom resolver for one of my queries. This resolver pulls directly from a mysql database (where other resolvers will obviously pull data from the prisma service). The datamodel I have is a User with an Address as a nested field.

The resolver/data model is defined as the following:

t.field("users", "User", {
    ...t.prismaType.users,
    resolve: async (parent, args, ctx) => {
      const result: Array<any> = await users();
      return result;
    }
  });

The users() function is a call to the mysql database that returns a list of users with their respective addresses. This works fine however when i perform the following query:

{
  users{
    id
    first_name
    last_name
    email
    address{
      address_1
      state
    }
  }
}

All the user information returns fine, however the address field is always returning null. I double checked and the data I return for the users() function all has data for the address field. What do I need to do to ensure that the address field returns the full address and NOT null?

excluding fields syntax

At the moments looks like in order to exclude a field we have to explicitly declare all fields but the one we want to exclude

example:

type User {
  id: ID! @unique
  email: String! @unique
  password: String!
}

in order to hide password we should do this:

const Post = prismaObjectType({
  name: 'User',
  definition(t) {
    t.prismaFields(['id', 'email'])
  },
})

...

export default makePrismaSchema({
  types: [Query, Mutation, Post],
   ...
}

some solution that comes to mind are:

allow prismaObjectType to get an object argument with include, and exclude key

const Post = prismaObjectType({
  name: 'User',
  definition(t) {
    t.prismaFields({'include': ['*'], exclude, ['password']})
  },
})

use negation ! (i'm not sure this is actually doable in ts) and for every field add a negated version in the union typing

const Post = prismaObjectType({
  name: 'User',
  definition(t) {
    t.prismaFields(['*', '!password'])
  },
})

thoughts?

Errors during transpilation

When you try to transpile it throws these errors:

node_modules/nexus-prisma/dist/definitions/extendType.d.ts:10:151 - error TS2344: Type 'NexusExtendTypeDef<TypeName>' does not satisfy the constraint 'AllNexusNamedTypeDefs'.
  Type 'NexusExtendTypeDef<TypeName>' is not assignable to type 'NexusInputObjectTypeDef<string>'.
    Property 'config' is protected but type 'NexusExtendTypeDef<TypeName>' is not a class derived from 'NexusInputObjectTypeDef<TypeName>'.

10 export declare function prismaExtendType<TypeName extends PrismaObjectTypeNames>(typeConfig: PrismaExtendTypeConfig<TypeName>): core.NexusWrappedType<core.NexusExtendTypeDef<TypeName>>;
                                                                                                                                                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/nexus/dist/builder.d.ts:191:6 - error TS2315: Type 'GraphQLObjectType' is not generic.

191   ): GraphQLObjectType<any, any>;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/nexus/dist/builder.d.ts:209:6 - error TS2315: Type 'GraphQLObjectType' is not generic.

209   ): GraphQLObjectType<any, any>[];
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/nexus/dist/utils.d.ts:15:9 - error TS2315: Type 'GraphQLObjectType' is not generic.

15   type: GraphQLObjectType<any, any>,

Expose input Fields

My datamodel.prisma looks like this:

type Element {
  id: ID! @id
  name: String
  description: String
}

But I only want the field name to be exposed

const User = prismaObjectType({
  name: 'User',
  definition(t) {
    t.prismaFields(['name'])
  },
})

Problem

What I end up having in the exposed shchema is:

type Element {
  name: String!
}

type ElementCreateInput {
  name: String!
  description: String
}

Is there a way to say that I don't want the field to show up in the 'Input' types?
Because it's not only the Create type, but also Update, Upsert, Where and other types,

Thanks

Multiple embedded types bug

NOTE: This problem may be with nexus-prisma and not prisma-client-lib. I'm sorry if that's the case.

Describe the bug
There's a bug with prisma-client-lib where if you have chained embedded types, it's not possible to query the embedded fields on 2nd or 3rd level.

To Reproduce
I have these embedded types

type StateMachine {
    id: ID! @id
    states: [StateMachineState] 
    ...
}
type StateMachineState @embedded {
    transitions: [StateMachineStateTransition]
    ...
}
type StateMachineStateTransition @embedded{
    action: String!
    pre: [StateMachineStatesTransitionHook] @relation(name: "PreHook")
    post: [StateMachineStatesTransitionHook] @relation(name: "PostHook")
    ...
}
type StateMachineStatesTransitionHook @embedded{
    hook: String
    ...
}

In the database the result should look something like this:

{
    "_id" : ObjectId("5c6fff231ed7970008c949f4"),
    "states" : [
        {
            "transitions" : [
                {
                    "action": "some action"
                    "pre" : [
                        {
                            "hook": "do something"
                        }
                    ],
                    "post" : [],
                }
            ]
        }
    ],
}

When I make a create mutation, the document is created correctly in the database. But I can't query for transitions or pre, because I get an error.

If I do:

createStateMachine(
data: {
  states: {
    create: {
      transitions: { create: { action: "someaction" } }
    }
  }
}
) {
    id
    states {transitions { pre(where: {}) {action}}}
  }

The result is:

{
  "data": {
    "createStateMachine": {
      "id": "5c6fff231ed7970008c949f4",
      "states": [
        {
          "transitions": null
        }
      ]
    }
  },
  "errors": [
    {
      "message": "Unknown prisma-client function for field StateMachineState.transitions",
      "locations": [
        {
          "line": 5,
          "column": 7
        }
      ],
      "path": [
        "createStateMachine",
        "states",
        0,
        "transitions"
      ]
    }
  ]
}

Expected behavior
I expect to be able to query embedded fields on many levels, and no only the first one

Versions (please complete the following information):

  • Connector: MongoDB
  • Prisma Server: 1.26.6
  • prisma CLI: prisma/1.26.6 (linux-x64) node-v10.15.1
  • OS: Linux Mint 19 Cinnamon
  • other dependencies: prisma-client, nexus-prisma,

Additional context
I'm using nexus-prisma and the problem may be with their implementation on the client, but I don't know if that's the case. For now what I can gather is that the function to get the second level of embedded (transitions) is expected to be on root level of that prisma-client as you can see on this line: https://github.com/prisma/nexus-prisma/blob/master/packages/nexus-prisma/src/resolver.ts#L98

If the bug is indeed on the nexus-prisma implementation, I'm sorry and I can post this issue there.

Thanks!

Generalise nexus-prisma plugin

Hi all!

I was thinking it would be great if this plugin was based on another more generic nexus plugin.

I am personally in a scenario where I would like to:

  • Starting from an existing private graphql server.
  • Generate the graphql-bindings for that server.
  • Using a nexus-prisma approach to extend, hide, expose types from that private graphql server.
  • Having my public graphql server up an running.

prismaObjectType does not create new objectType if type does not exist.

prismaObjectType works fine if the underlying objectType already exists. If it does not, an error is thrown.
"Must select a GraphQLObjectType, saw which is undefined"
It works fine when switching to objectType instead for new objects.

Is this intended behavior? if so maybe update message:

"Must select a GraphQLObjectType, saw which is undefined. Are you trying to create a new type? If so use objectType instead of prismaObjectType"

npx nexus-prisma-generate fails "no valid 'prisma-client-dir' was found"

I updated all my dependencies and copied the typescript-auth (of the Prisma examples) while using a local docker container as the prisma endpoint.

Using "prisma deploy" runs "prisma generate" sucessfully but "npx nexus-prisma-generate" fails and logs the error "No valid 'prisma-client-dir' was found". The prisma-client folder is created sucessfully as well (../src/generated/prisma-client/).

I went through all the recent changes of the prisma exaples and can't find a solution to my problem. I assume there's something wrong with either the example or nexus prisma.

Wrap `makeSchema` function to allow more parameters

Description

makeSchema should take at least two more params:

  • prismaSchemaPath: The path to the prisma graphql schema
  • And another one to allow configuring the name of prisma-client in the context, so that we can safely access the client when generating the resolver (checkout generateDefaultResolver() function in prisma.ts)

Could not find argument id for type

image
When I use this query

mutation {
  updateStory(where: {
    id: "cjrodoikb001z0860g7wzuk21"
  }, data: {
    content: "asd"
  }) {
    id
  }
}

I got this error message

{
  "data": {
    "updateStory": null
  },
  "errors": [
    {
      "message": "Could not find argument id for type Story",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "updateStory"
      ]
    }
  ]
}

Ability to selectively disable nested create/connects?

I LOVE being able to easily create "derived types" in my GraphQL schema from my Prisma models. The hide/filter options and the ability to add additional custom fields is glorious. To do this before, I had to duplicate and modify my Prisma schema's AST.

Another major divide between the Prisma Client api and a typical GraphQL server is the ability to do arbitrarily nested writes with create and connect. It would be great if we could enable/disable these two options selectively on each relational field in our schema.

As a proposed API:

export const User = prismaObjectType({
  name: 'User',
  definition(t) {
    t.prismaFields([{ 
      name: 'posts', 
      args: ["published"], 
      nestedCreate: false, 
      nestedConnect: false 
    }])
  },
})

Without this, the ability to just "drop in" createUser and deleteUser from our Prisma API isn't useful, since we'd be giving the client free rein to nestedly create/connect/update/disconnect things in our database (assuming we pass the createUser parameters straight through to Prisma without any validation).

I figure it might be hard to implement this, since mutations aren't implemented in a nested way like queries. Any other ideas for how to validate nested arguments?

Transformation API (transform the generated schema during build step)

Description

Once #86 lands, we will be in a better situation to pass parameters to nexus-prisma-generate. We think it might add a lot of value to be able to transform the generated schema during the build step.

That would not only reduce the runtime overhead, but also provide type-safety over the transformed schema and probably unlock some transformation that wouldn't be possible/be harder to implement at runtime.

Use-cases

  • #90
  • #95
  • Rename args
  • Renamed type names (input, object, enum ...)
  • Disable connection types or any other types (like Subscription if not needed)

Do you have any use-cases in mind? Let's use this thread as a place to discuss these ๐Ÿ™Œ

Using `t.prismaType` doesn't export the needed input types

Description

When exposing a field from the prisma graphql api, we generate the input types needed for that field to prevent users from having to redeclare all the huge where and data input types.

This already works when using t.prismaFields but doesn't when using t.prismaType

We probably need to create getters inside the t.prismaType object to be aware of which input types are used, and therefore expose them.

Customizing an object with an enum reading from a string

Hi, is possible to overwrite a string property from SDL and expose it as enum with nexus?

I have tried this code, hiding the main type string property, and creating a new one based on an enum. But when I try a query, when it's parsing the response, it throws an error, because it's not converting the string to the enum.

"Expected a value of type \"CostType\" but received: \"MAINTENANCE\"",

import { enumType } from 'nexus';
import { EnumMemberInfo } from 'nexus/dist/core';

const costTypeEnum: EnumMemberInfo[] = [
  { name: "SETUP", value: 0, description: "Setup type cost." },
  { name: "MAINTENANCE", value: 1, description: "Maintenance type cost." },
  { name: "COSTPERMILLION", value: 2, description: "Fixed and mandatory, if global condition type is Traffic.",  },
  { name: "EXCESSCOSTPERMILLION", value: 3, description: "Cost per million searches when l2b is reached.",  },
  { name: "TOTALTRANSACTIONVALUE", value: 4, description: "% charged per annual amount without cancellations.",  },
  { name: "COSPERBOOKING", value: 5, description: "Fixed amount depending on total booking of all suppliers. Optional, mandatory if global condition type is booking.",  }
];

export const CostType = enumType({
    name: "CostType",
    members: costTypeEnum
  });
import { CostType } from './../enum-types/cost-type';
import { prismaObjectType } from "nexus-prisma";

export const costTypeObject = prismaObjectType({
    name: 'Cost',
    definition(t) {
    t.prismaFields({ filter: ["type"] });

    t.field("type", {
        type : CostType,
        description: "Cost type.",
        resolve: (o) => o.type
    })
    }
  })

How can I do it in its resolve function to convert this string to its enum

(o) => o.type ?

Type 'NexusExtendTypeDef<TypeName>' is not assignable to type 'NexusInputObjectTypeDef<string>'.

Getting some TS errors when I run tsc --project tsconfig.json

node_modules/nexus-prisma/dist/definitions/extendType.d.ts:10:151 - error TS2344: Type 'NexusExtendTypeDef<TypeName>' does not satisfy the constraint 'AllNexusNamedTypeDefs'.
  Type 'NexusExtendTypeDef<TypeName>' is not assignable to type 'NexusInputObjectTypeDef<string>'.
    Property 'config' is protected but type 'NexusExtendTypeDef<TypeName>' is not a class derived from 'NexusInputObjectTypeDef<TypeName>'.

my tsconfig.json

{
  "compilerOptions": {
    "lib": ["esnext", "dom"],
    "rootDir": "src",
    "outDir": "dist",
    // "strict": true,
    "sourceMap": true
  },
  "include": [
    "src/**/*"
  ]
}

Workaround till this is fixed

Add skipLibCheck: true to your tsconfig.json

Make it a library

Description

Currently, the plugin is located under the /plugin directory. All the graphql implementation living aside it should be removed or moved to a /examples directory.

The package.json file should also be updated accordingly

Variable '$where' expected value of type 'PostWhereUniqueInput!' but value is undefined. Reason: Expected non-null value, found null.

I'm exposing the post query from my Prisma schema like this:

const Query = prismaObjectType('Query', t => {
  t.prismaFields(['post'])
})

Now, in the Playground I'm sending the following query:

{
  post(where: {
    id: "asd"
  }) {
    id
    author {
      id
    }
  }
}

I'm getting this response:

{
  "data": {
    "post": null
  },
  "errors": [
    {
      "message": "Variable '$where' expected value of type 'PostWhereUniqueInput!' but value is undefined. Reason: Expected non-null value, found null. (line 1, column 8):\nquery ($where: PostWhereUniqueInput!) {\n       ^",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "post"
      ]
    }
  ]
}

I'd expect that there are no errors returned since I provided the expected payload.

`t.prismaType` doesn't work if used with a different field name

Description

Given the following Query type:

type Query {
  users(...): [User!]!
}

You could use t.prismaType in the following way:

prismaObjectType('Query', t => {
  t.field('users', 'User', t.prismaType.users)
})

However, it wouldn't work if you renamed the field name users to something else. eg:

prismaObjectType('Query', t => {
  t.field('customers', 'User', t.prismaType.users) // users -> customers
})

The reason why it doesn't work is because users is needed when generating the resolver.
Internally, this would result in a such a call to the prisma client:

return ctx.client['customers']() instead of return ctx.client['users']() (customers would not be a valid function for the client here)

We probably need to add a fieldName inside the t.prismaType.users object to keep track of the "prisma" field name

t.field only accepts 'BaseScalars' as type

Fails to compile with the following error

error TS2345: Argument of type '"UserAuth"' is not assignable to parameter of type 'BaseScalars'.

clippy

export const UserAuth = prismaObjectType('UserAuth')
type UserAuth {
  id: ID! @unique
  user: User @relation(name: "UserOnUserAuth")
  auth0UserId: String! @unique
  emailVerified: Boolean @default(value: false)
}

Implement `omit` option

Description

t.prismaFields has three options: { pick, omit, aliases }.

The omit option isn't implemented yet. It's role is to omit fields from the chosen GraphQL type. It is the opposit of pick

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.