GraphQL Prisma - use orderBy on nested relationships - graphql

I am fairly new to GraphQL Prisma combo, I cannot seem to order nested relationships without error because the only available orderBy fields are regarding the ID.
My intended goal in the playground would be to create a query that looks similar to the following:
getPosts{
connections(orderBy: "text_asc"){
id
text
}
}
Resolver
getPosts(parent, args, ctx, info){
return ctx.db.query.posts({}, info)
}
Data Model
type Post {
id: ID! #id
isPublished: Boolean! #default(value: false)
title: String!
text: String!
connections: [Connection!]! #relation(name: "ClientConnect")
}
type Link {
id: ID! #id
text: String!
url: String!
}
type Connection {
id: ID! #unique #id
client: Link #relation(name: "LinkConnect")
}

Related

How to resolve Inconsistent __typename error in Relay?

I just tried to implement the Relay in Frontend for this graphql tutorial, In that tutorial, they created graphql server to store URL(Link) bookmarks with the User who posted those URLs.
The relationship between the link and the users is:
Link belongs_to :user,
User has_many :links.
And I listed out all the Links with Users in Frontend, at the time I got the below error.
Warning: RelayResponseNormalizer: Invalid record 1. Expected __typename to be consistent, but the record was assigned conflicting types Link and User. The GraphQL server likely violated the globally unique id requirement by returning the same id for different objects
I'm not aware of how much it will impact the application. because I got the expected result from Frontend.
Frontend View of Query.
I read this relay official blog for this kind of error, but there is no example to know how exactly to resolve this. so can someone help to resolve this?
Relay Query
graphql`
query LinkListQuery {
allLinks {
id,
description,
url,
postedBy {
id,
name
}
}
}`
Schema:
input AUTH_PROVIDER_CREDENTIALS {
email: String!
password: String!
}
input AuthProviderSignupData {
credentials: AUTH_PROVIDER_CREDENTIALS
}
type Link implements Node {
description: String!
id: ID!
postedBy: User
url: String!
votes: [Vote!]!
}
input LinkFilter {
OR: [LinkFilter!]
descriptionContains: String
urlContains: String
}
type Mutation {
createLink(description: String!, url: String!): Link!
createUser(name: String!, authProvider: AuthProviderSignupData): User!
createVote(linkId: ID): Vote!
signinUser(credentials: AUTH_PROVIDER_CREDENTIALS): SignInUserPayload
}
"""An object with an ID."""
interface Node {
"""ID of the object."""
id: ID!
}
type Query {
allLinks(filter: LinkFilter, first: Int, skip: Int): [Link]!
"""Fetches an object given its ID."""
node(
"""ID of the object."""
id: ID!
): Node
}
"""Autogenerated return type of SignInUser"""
type SignInUserPayload {
token: String
user: User
}
type User implements Node {
email: String!
id: ID!
links: [Link!]!
name: String!
votes: [Vote!]!
}
type Vote {
id: ID!
link: Link!
user: User!
}

How do you expose different subsets of a GraphQL type to different users?

I have a User type with many fields on it. I want to expose different fields on it depending on who is querying information about the User. What is a good way to organize this without having many many different types each representing a slightly different view of a user? Here is an example with 4 different types representing different views of the same user. Is there a better way to organize this?
Of course I can make all the fields nullable but that doesn't seem helpful to the developer querying the data.
type UserForSelf {
id: ID!
username: String!
avatarUrl: String!
email: String!
mailingAddress: Address!
team: Team!
lastLogin: DateTime!
}
type UserForPublic {
id: ID!
username: String!
avatarUrl: String!
}
type UserForAdmin {
id: ID!
username: String!
avatarUrl: String!
email: String!
team: Team!
lastLogin: DateTime!
}
type UserForTeamMember {
id: ID!
username: String!
avatarUrl: String!
email: String!
team: Team!
}
You should consider using Schema Directives for this use case.
That basically allows you to only resolve some specific field if the user has permission for it. Otherwise you can return null or throw an error.
So in the end you would have a single type User like this:
directive #hasRole(role: String) on FIELD_DEFINITION
type User {
id: ID!
username: String!
avatarUrl: String!
email: String! #hasRole(role: "USER")
mailingAddress: Address! #hasRole(role: "USER")
team: Team! #hasRole(role: "USER")
lastLogin: DateTime! #hasRole(role: "USER")
}
Then you can have a directive resolver kinda like this:
const directiveResolvers = {
...,
hasRole: (next, source, {role}, ctx) => {
const user = getUser()
if (role === user.role) return next();
throw new Error(`Must have role: ${role}, you have role: ${user.role}`)
},
...
}
If you have a field that only ADMIN can query, you would just use the #hasRole(role: "USER") directive.
Then your service layer (or your resolver if you don't have a service layer) would be responsible to define which User to fetch (if your own user or some user based on ID as long as you have permission).
You can use directives for a lot of different use cases. Here are a few good references:
https://www.prisma.io/blog/graphql-directive-permissions-authorization-made-easy-54c076b5368e
https://www.apollographql.com/docs/apollo-server/schema/directives/

Is it possible to create two or more relations to a model in prisma?

I'm trying to create two relations to a model in datamodel.prisma
datamodel.prisma
type User {
id: ID! #id
user_id: String! #unique
username: String!
email: String! #unique
}
type Operation {
id: ID! #id
teams: [User] #relation(link: INLINE)
created_by: User #relation(link: INLINE)
}
When I try to deploy this is the error I'm getting
Error
Errors:
Operation
✖ The relation field `teams` must specify a `#relation` directive: `#relation(name: "MyRelation")`
✖ The relation field `created_by` must specify a `#relation` directive: `#relation(name: "MyRelation")`
What I want to achieve is an operation can have multiple members(one to many) and can only be created by one member(one to one). How can I achieve this in Prisma?
Could you try creating it like this:
type User {
id: ID! #id
user_id: String! #unique
username: String!
email: String! #unique
}
type Operation {
id: ID! #id
teams: [User] #relation(name: "Teams", link: TABLE)
created_by: User #relation(name: "Createdby", link: TABLE)
}
The name field is required while creating multiple relations to the same model.
Also I'm assuming you are using Postgres.

Filter by Email in prisma GraphQL

I'm trying to filter a user by email, I am using prisma and doing tests with the "playground", is there any way to filter the user's data by email?
My schema:
interface Model {
id: ID! #id
createdAt: DateTime! #createdAt
updatedAt: DateTime! #updatedAt
}
type User implements Model {
id: ID! #id
createdAt: DateTime! #createdAt
updatedAt: DateTime! #updatedAt
username: String
name: String!
surname: String!
email: String!
token_usuario: String! #unique
}
My attempts:
Using prisma 2.0, the db client exposes something like this:
ctx.prisma.user.findMany({
where: {
email: { contains: "something" }
}
});
And I expect the query would follow suit. So try passing in the where field for filtering. Would need to see the full schema to say for sure.

How to resolve subselections / relations in prisma (nested lists)

Let's take an example from the github repo of prisma:
We have a user, the user could have multiple posts, and one post could have multiple links.
My goal is, to retrieve all posts and all links.
This means, my response is a list (links) in a list (posts).
I want to map the values I get back as two nested lists.
datamodel.prisma
type User {
id: ID! #id
email: String! #unique
name: String
posts: [Post]!
}
type Post {
id: ID! #id
createdAt: DateTime! #createdAt
updatedAt: DateTime! #updatedAt
published: Boolean! #default(value: false)
title: String!
content: String
author: User!
links: [Link]!
}
type Link {
id: ID! #id
url: String
title: String
post: Post!
}
schema.graphql
type Query {
...
}
type Mutation {
...
}
type Link {
id: ID!
url: String
title: String
post: Post!
}
type Post {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
published: Boolean!
title: String!
content: String
author: User!
}
type User {
id: ID!
email: String!
name: String
posts: [Post]!
}
I want to query all posts of a user, and all of the links for every post in the response.
How would I query this request?
user {
id
posts {
id
links {
id
}
}
}
The above code snipper would not work.
EDIT
I want to use the following:
User: {
listPosts: (parent, args, context, info) {
return context.prisma.posts().links()
}
}
So in my response (data in front-end via react-apollo Query Component), I want to map over posts AND the links in each post.
BUT the links attribute in posts is null.
Is there another way to achieve this?!
According to the docs:
Prisma client has a fluent API to query relations in your database. Meaning you can simply chain your method calls to navigate the relation properties of the returned records. This is only possible when retrieving single records, not for lists. Meaning you can not query relation fields of records that are returned in a list.
In order to get around that limitation, you can use the $fragment method:
const fragment = `
fragment UserWithPostsAndLinks on User {
id
email
name
posts {
id
title
content
links {
id
url
title
}
}
}
`
const userWithPostsAndLinks = await prisma.user({ id: args.id }).$fragment(fragment)

Resources