HowToGraphQL - Chapter 6 Authentication - Why is postedBy() invoked?

Viewed 67

I hope I can get clarity when asking this question since GraphQL is a fairly obscure concept and there aren't that many answers online.

In the tutorial (https://www.howtographql.com/graphql-js/6-authentication/) in the #Resolving relations section near the middle of the page there's this code:

function postedBy(parent, args, context) {
  return context.prisma.link.findUnique({ where: { id: parent.id } }).postedBy()
}

Why is postedBy() called at the end?

Super confused.

1 Answers

This part is not strictly related to auth [reasons] ... creating post mutation will work without that. But:

  • post mutation creates an [Link] entry with a relation (to User in prisma schema meaning docs );
  • postedBy is a virtual field - 'Relation fields define connections between models at the Prisma level and do not exist in the database. ';
  • post mutation returns a Post type - then 'asked' return object can contain postedBy field (and its User object/type subfield[-s]);
  • when postedBy field is queried (as part of mutation result tree), it (related User object/type - graphql context) must be resolved using function postedBy(parent, args, context);

In resolver body we're using/working with "Prisma client" - ORM lib, then:

context.prisma.link.findUnique({ where: { id: parent.id } }).postedBy()
  • context.prisma is/gives an access to client from graphql server context;
  • context.prisma.link is/gives an access to links API:

From docs: Models:

  • Represent the entities of your application domain;
  • Map to the tables in your database
  • Form the foundation of the queries available in the generated Prisma Client API
  • context.prisma.link.findUnique({ where: { id: parent.id } }) - queries for DB link entity - returns a Link 'instance' (prisma context);
  • context.prisma.link.findUnique({ where: { id: parent.id } }).postedBy() - still prisma client API context (not graphql - resolver), not 'calling itself' ;

See docs: Prisma client fluent api

  • prisma's .postedBy() gets a connection to User (prisma) 'instance', returned as/resolved to User (graphql) object/type (with id read from DB table);

  • postedBy { id } requested (in query) could be satisfied ... but sendBy User part of post mutation result (Link.postedBy) can be asked to contain links (and subfields) - function links(parent, args, context) { is for resolving that relation/connection;

  • each of returned links can be queried for postedBy user fields ...

... it's a graph/tree, completely resolvable now (nodes, DB entries and relations, virtuals)

Related