npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

apollo-dynamic

v1.0.4

Published

Apollo utility to create dynamic selection sets on queries, mutations and subscriptions, based on decorated schema.

Downloads

3

Readme

Apollo Dynamic npm version

Apollo Dynamic allows to create dynamic selection sets on queries, mutations and subscriptions when using @apollo/client for consult GraphQL resolvers. It works by decorating entity classes with @SelectionType and @SelectionField which allows to fabric dynamics selections set with a similar syntax as TypeORM repositories (relations).

This library can be used with any wrapper of Apollo Client, it offer simple functions and decorators that can be imported directly with TypeScript.

Installation

$ npm install apollo-dynamic

Usage

With Apollo Client you can make GraphQL queries like this:

import { gql, useQuery } from '@apollo/client';

const GET_PERSONS = gql`
  query GetPersons {
    persons {
      id
      firstname
      lastname
      secret
      profile {
        avatar
        nickname
      }
    }
  }
`;

And make the http call using this:

const { loading, error, data } = useQuery(GET_PERSONS);

It works fine at first, but what happened if we want to not get the profile in some queries, or if we want to hide some parameters by a condition. Well, you probably may answer this:

const GET_PERSONS = gql`
  query GetPersons($isSuperAgent: Boolean!, $includeProfile: Boolean!) {
    persons {
      id
      firstname
      lastname
      secret @include(if: $isSuperAgent)
      profile @include(if: $includeProfile) {
        avatar
        nickname
      }
    }
  }
`;

And you are right, but what happens if we have relationships that can be nested indefinitely, or if the relationship is in both ways?. In this cases (most cases) you must repeat all the logic for the opposite side of the relationship, in the other entity queries. Some say that this can be afforded with code generation. But i bring here a superior solution: Dynamic Selection Sets!

Decorators


In the typical CRUD systems, we always have entities that we use as interfaces to move data from here to there. So we can assume that if you are using the GetPersons resolver, you probably have a Person entity class or type, like this:

export class Person {
    id?: string;
    firstname?: string;
    lastname?: string;
    secret?: string;
    profile: Profile;
    articles: Article[];
}

export class Profile {
    avatar: string;
    nickname: string;
}

export class Article {
    id: string,
    name: string;
    person: Person;
    type: ArticleType;
}

export class ArticleType {
    category: string;
    section: string;
}

We add some more entities for the example.

The proposed library want to make use of this precious interfaces that we don't want to repeat on all the code, because if something change in the entity model we have to change it everywhere. So here we introduce the @SelectionType and @SelectionField decorators:

import { SelectionType, SelectionField } from 'apollo-dynamic'

@SelectionType('Person')
export class Person {
    @SelectionField()
    id?: string;

    @SelectionField()
    firstname?: string;

    @SelectionField()
    lastname?: string;

    @SelectionField({ include: 'isSuperAgent' })
    secret?: string;

    @SelectionField(() => Profile)
    profile: Profile;

    @SelectionField(() => Article)
    articles: Article[];
}

@SelectionType('Profile')
export class Profile {
    @SelectionField()
    avatar: string;

    @SelectionField()
    nickname: string;
}

@SelectionType('Article',{
    default: { relations: { artType: true } }
})
export class Article {
    @SelectionField({ skip: (cond) => cond.noIDsPlease })
    id: string,

    @SelectionField()
    name: string;

    @SelectionField(() => Person)
    person: Person;

    @SelectionField(() => ArticleType)
    artType: ArticleType;
}

@SelectionType('ArticleType')
export class ArticleType {
    @SelectionField()
    category: string;

    @SelectionField()
    section: string;
}

Now with this decorators we can use the Selection Types on our queries and the selection set will be generated automatically based on the input parameters we send.

Queries, Mutations and Subscriptions


Going back to our query example, we can rewrite our GraphQL query using the new Selection Types like this (we use the names from @SelectionType decorator):

const GET_PERSONS = gql`
  query GetPersons {
    persons {
      Person
    }
  }
`;

And use it like this:

const { loading, error, data } = useQuery(
  select(GET_PERSONS, {
    relations: { profile: false, article: { artType: true } },
    conditions: { isSuperAgent: false }
  })
);

This will get us something like this:

const GET_PERSONS = gql`
  query GetPersons {
    persons {
      id
      firstname
      lastname
      article {
        id
        name
        artType {
          category
          section
        }
      }
    }
  }
`;

We can also create the query from the Article side or from whatever entity we want. The magic is we can define the GraphQL interfaces once and then use em wherever we want without losing the capability of customize the result set. So we don't have to repeat the queries strings for every different selection set we want to ask for. Or moreover, we don't need to mediate with include or skip parameters that can or cannot be relevant (it can't be nullified on common queries).

Going forward, we can do the same with mutations:

const CREATE_PERSON = gql`
  query CreatePerson($personCreateInput: PersonCreateInput!) {
    createPerson(personCreateInput: $personCreateInput) {
      Person
    }
  }
`;

const [mutateFunction, { data, loading, error }] = useMutation(
  select(CREATE_PERSON, { relations: { profile: true } }),
  { variables: { firstname: 'Jonh', lastname: 'Doe' } }
);

And with subscriptions:

const ARTICLES_SUBSCRIPTION = gql`
  subscription OnArticleAdded($id: ID!) {
    articleAdded(id: $id) {
      Article
    }
  }
`;

const { data, loading } = useSubscription(select(ARTICLES_SUBSCRIPTION, { relations: { artType: true } }), {
  variables: { id: 'someid' }
});

Stay in touch

License

This package is MIT licensed.