DEV Community

Discussion on: The magic of the Node interface

Collapse
 
sfratini profile image
Sebastian Fratini

This is very interesting. I had a few questions.

  1. How to you implement the logic to base64 encode the ID? Is it manual per resolver? Or can you "paste" that snippet somewhere so it is automatically translated to the correct GraphQL Node type for example?
  2. How does the node resolver implementation would look like? Again, my goal is to understand the best practices as we are implementing our own first GraphQL. Is it a factory pattern and you analyze each one of the types that would be returned? I am trying to make the code as re usable as possible. Thanks!
Collapse
 
zth profile image
Gabriel Nordeborn

Hi Sebastian, and thank you!

  1. In pseudo code, something like:
const makeGloballyUniqueId = (
  typename: string, 
  identifier: string
)  => base64.encode(`${typename}:${identifier}`);

It's really not more complicated than that for generating the actual ID. You could then abstract that further and do a small function that can generate a resolver for you, that you can re-use throughout your schema.

  1. I'd say, in the simplest possible form, it'd look like this (warning for more pseudo-code):
const [typename, id] = decodeGloballyUniqueId(id);

switch(typename) {
  case "User": 
    return User.get(id);
  case "BlogPost":
    return BlogPost.get(id);
....

So, it's just a matter of decoding the id and extracting the information you're after, and then use that to resolve the relevant object you need.

Does that make sense?

Collapse
 
sfratini profile image
Sebastian Fratini

Thank you! Yes, this is something similar to what I was implementing. Since I am using sequelize, I was trying to avoid code duplication and maybe thought if it was possible to have a hook or something in the graphql schema so I dont have to manually translate each ID on each resolver.

The code has perfect sense and I'll check the best way to implement it.

Thanks again!