GraphQL: Are either of these two patterns better/worse? - graphql

I'm relatively new to GraphQL, and I've noticed that you can select related fields in one of two different ways. Let's say we have a droids table and a humans table, and droids have an owner which is a record in the humans table. There's (at least) two ways you can express this:
query DroidsQuery {
id
name
owner {
id
}
}
or:
query DroidsQuery {
id
name
ownerId # this resolves to owner.id
}
At first glance the former seems more idiomatic, and obviously if you're selecting multiple fields it has advantages (owner { id name } vs. having to make a new ownerName so you can do ownerId ownerName). However, there's a certain explicitness to the ownerId style, as you're expressing "here's this thing I specifically expected you to select".
Also, from an implementation standpoint, it seems like owner { id } would lend itself to the resolver making an unnecessary JOIN, as it would translate owner { id } as the id column of the humans table (vs. an ownerId field which, with its own resolver, knows it doesn't need a JOIN to get the owner_id column of the droids table).
As I said, I'm new to GraphQL, so I'm sure there's plenty of nuances to this question that I'd appreciate if I'd been using it longer. Therefore, I was hoping for insight from someone who has used GraphQL into the upsides/downsides of either approach. And just to be clear (and to avoid having this answer closed) I'm looking for explicit "here's what is objectively bad/good about one approach over the other", not subjective "I prefer one approach" answers.

You should understand GraphQL is just a query language + execution semantics. There are no restrictions on how you present your data and how you resolve your data.
Nothing stops you from doing what you describe, and returning both owner object and ownerId.
type Droid {
id: ID!
name: String!
owner: Human! # use it when you want to expand owner detail
ownerId: ID! # use it when you just want to get id of owner
}
You already pointed out the main problem: the former implementation seems more idiomatic. No you don't make a idiomatic code, you make practical code.
A real world example as you design field pagination in GraphQL:
type Droid {
id: ID!
name: String!
friends(first: Int, after: String): [Human]
}
The first time, you query a droid + friends, and it is fine.
{
query DroidsQuery {
id
name
friends(first: 2) {
name
}
}
}
Then, you click more to load more friends; it hits DroidsQuery one more time to query the previous droid object before resolving the next friends:
{
query DroidsQuery {
id
friends(first: 2, after: "dfasdf") {
name
}
}
}
So it is practical to have another DroidFriendsQuery query to directly resolve friends from droid id.

Related

Is there any way limit the form of the query in graphql

For example, if there are two types User and Item
type User {
items: [Item!]!
}
type Item {
id: ID!
name: String!
price: Int!
}
If one user has PARTNER role.
I want to prevent it from being called only in the form of the query below.
query Query1 {
user {
items {
name
}
}
}
If user call another query, I want to indicate that user doesn't have permission.
query Query2 {
user {
items {
id
name
}
}
}
In short. if (Query1 != Query2) throw new Error;
Your question is a bit hard to follow but a couple things:
A GraphQL server is stateless - you cannot (and really should not) have a query behave differently based on a previous query. (If there's a mutation in between sure but not two queries back to back)
access management is normally implemented in your resolvers. You can have the resolver for the item id check to see if the user making the query has the right to see that or not and return an error if they don't have access.
Note that it can be bad practice to hide the id of objects from queries as these are used as keys for caching on the client.

Schema design to avoid nested pagination

First of all, I am using a simplified version of "Relay" pagination where "List" is a basic equivalent of "connection" and "limit" is the equivalent to "first" and "cursor" is the equivalent to "after".
This is the relevant part of my schema:
extend type Query {
artist(id: ID!): Artist
artists(limit: Int!, cursor: String): ArtistList!
}
type Artist {
id: ID!
account: Account!
photos(limit: Int!, cursor: String): PhotoList!
website: String
instagram: String
facebook: String
created: Date!
updated: Date
about: String
}
type ArtistList {
nodes: [Artist]!
page: Page!
}
I want avoid nested pagination, so want permit get next nodes of photos on the query artist and not permit get next nodes of photos on the query artists (For example, permit the argument cursor of photos on query artist and ban it on query artists). But I can't see how to express that in the GraphQL schema.
There is no way to do what you want to do specifically. You could return different types from artist (e.g. ArtistWithPagination) and from artists (e.g. ArtistWithoutPagination). I am not sure if this would be worth the tradeoff of having two very similar types.
Alternatively, you could throw a runtime error when a user attempts to query the API in this undesired way (with a custom validation rule). If your GraphQL API is internal you could even develop a linter, that warns developers if they do the double pagination in their queries.

When do I use nested fields in GraphQL and when do I flatten them?

With GraphQL schemas, when should I provide a type relation's field as a root-level field for its associated type?
Example
In many examples, I almost always see schemas that require the client to create queries that explicitly traverse the graph to get a nested field.
For a Rock Band Table-like component in the front end (or client), the GraphQL service that provides that component's data may have a schema that looks like this:
type Artist {
name: String!
instrument: String!
}
type RockBand {
leadSinger: Artist,
drummer: Artist,
leadGuitar: Artist,
}
type Query {
rockBand: RockBand
}
If the table component specified a column called, "Lead Singer Name", given the current schema, a possible query to fetch table data would look like this:
{
rockBand {
leadSinger {
name
}
}
}
For the same Rock Band Table, with the same column and needs, why not design a schema like this:
type RockBand {
leadSinger: Artist,
leadSingerName: String,
drummer: Artist,
leadGuitar: Artist,
}
That way a possible query can be like this?
{
rockBand {
leadSingerName
}
}
Does the choice to include the "leader singer's name", and similar relation fields, entirely depend on the client's need? Is modifying the schema to serve data for this use-case too specific a schema? Are there benefits to flattening the fields outside of making it easier for the client? Are there benefits to forcing traversal through the relation to get at a specific field?

How to use same generated ID in two fields prisma-graphql

I'm implementing a graphql prisma datamodel. Here I have a type called BankAccount . I may need to update and delete them as well. I'm implementing this as immutable object. So, when updating I'm adding updating the existing record as IsDeleted and add a new record. And when updating an existing record I need to keep the id of the previous record to know which record is updated. So, I've came up with a type like this
type BankAccount {
id: ID! #unique
parentbankAccount: String!
bankName: String!
bankAccountNo: String!
isDeleted: Boolean! #default(value: "false")
}
Here the parentBankAccount keeps the id of previous BankAccount. I'm thinking when creating a bank account, setting the parentBankAccount as same as the id as it doesn't have a parent. The thing is I'm not sure it's possible. I'm bit new to GraphQL. So, any help would be appreciated.
Thanks
In GraphQL, generally if one object refers to another, you should directly refer to that object; you wouldn't embed its ID. You can also make fields nullable, to support the case where some relationship just doesn't exist. For this specific field, then, this would look like
type BankAccount {
parentBankAccount: BankAccount
...
}
and that field would be null whenever an account doesn't have a parent.
At an API level, the layout you describe seems a little weird. If I call
query MyBankAccount {
me { accounts { id } }
}
I'll get back some unique ID. I'd be a little surprised to later call
query MyBalance($id: ID!) {
node(id: $id) {
... on BankAccount {
name
isDeleted
balance
}
}
}
and find out that my account has been "deleted" and that the balance is from a week ago.
Using immutable objects in the underlying data store makes some sense, particularly for auditability reasons, but that tends to not be something you can expose out through a GraphQL API directly (or most other API layers: this would be equally surprising in a REST framework where the object URL is supposed to be permanent).

how do you update the cache after a mutation that returns a circular type?

All of the answers I have found relate to graphql. I need to know how to update the cache on the client using apollographql.
Given this Friend type and mutation.
type Friend {
id: String
name: String
friends: [Friend]
}
type Mutation {
createFriend (
friends: [FriendInput]
): [Friend]
}
The friends array is circular. How do you represent this in the response and how do you update the clients cache?
If you're interested in the friends of a specific person, your store probably contains a bunch of Friend objects (I would actually call them Person, and friends is just a field on the Person type). For doing the mutation, it should be enough to provide the id of each friend of that new person, unless you want to create not just one person at a time in these mutations, but multiple.
For the mutation response, just include the data that you need for each friend. If you need the name and id of each of the persons friends, then include that as well. Most likely you won't need to go two levels deep, but if you want to, you can do that as well.
In Apollo Client, you don't actually need to do anything special to have this data be properly written into your store, because Apollo Client automatically normalizes by the id field and stores each friend only once. So if you're sure that you already have all the persons on the client, it will be enough to ask only for the id of each friend, so for example:
{
createFriend( friends: [{ name: 'Joe', friends: [{ id: 1}, {id: 4}] }]) {
id
name
friends {
id
name
}
}
}

Resources