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

gql-payload

v2.1.0

Published

GraphQL Payload Builder

Downloads

219

Readme

GraphQL Payload Builder

This is an optimized fork of gql-query-builder with extra features for generating GraphQL payloads using plain JavaScript Objects (JSON).

npm

Install

npm install gql-payload --save or yarn add gql-payload

Usage

import { gqlQuery, gqlMutation, gqlSubscription } from 'gql-payload'

const query = gqlQuery(options: object)
const mutation = gqlMutation(options: object)
const subscription = gqlSubscription(options: object)

Options

options is { operation, fields, variables } or an array of options

Adapter

An optional third argument adapter is a typescript/javascript class that implements IQueryAdapter, IMutationAdapter or ISubscriptionAdapter.

If adapter is undefined then src/adapters/DefaultQueryAdapter or src/adapters/DefaultMutationAdapter is used.

import { gqlQuery } as gql from 'gql-payload'

const query = gqlQuery(options: object, adapter?: MyCustomQueryAdapter,config?: object)

Config

Examples

  1. Query
  2. Query (with variables)
  3. Query (with nested fields selection)
  4. Query (with required variables)
  5. Query (with custom argument name)
  6. Query (with operation name)
  7. Query (with empty fields)
  8. Query (with alias)
  9. Query (with adapter defined)
  10. Query (with inline fragment)
  11. Query (with named fragment)
  12. Mutation
  13. Mutation (with required variables)
  14. Mutation (with custom types)
  15. Mutation (with adapter defined)
  16. Mutation (with operation name)
  17. Subscription
  18. Subscription (with adapter defined)
  19. Example with Fetch
  20. Example with Ofetch
  21. Example with Axios

Query:

import { gqlQuery } from "gql-payload";

const query = gqlQuery({
  operation: "thoughts",
  fields: ["id", "name", "thought"]
});

console.log(query);

Output:

{
  query: 'query {thoughts { id name thought } }',
  variables: {}
}

↑ all examples


Query (with variables):

import { gqlQuery } from "gql-payload";

const query = gqlQuery({
  operation: "thought",
  variables: { id: 1 },
  fields: ["id", "name", "thought"]
});

console.log(query)

Output:

{
  query: 'query ($id: Int) { thought (id: $id) { id name thought } }',
  variables: { id: 1 }
}

↑ all examples


Query (with nested fields selection):

import { gqlQuery } from "gql-payload";

const query = gqlQuery({
  operation: "orders",
  fields: [
    "id",
    "amount",
    {
      user: [
        "id",
        "name",
        "email",
        {
          address: [
            "city",
            "country"
          ]
        }
      ]
    }
  ]
});

console.log(query);

Output:

{
  query: 'query { orders { id amount user { id name email address { city country } } } }',
  variables: {}
}

↑ all examples


Query (with required variables):

import { gqlQuery } from "gql-payload";

const query = gqlQuery({
  operation: "userLogin",
  variables: {
    email: { value: "[email protected]", required: true },
    password: { value: "123456", required: true }
  },
  fields: ["userId", "token"]
});

console.log(query);

Output:

{
  query: 'query ($email: String!, $password: String!) { userLogin (email: $email, password: $password) { userId token } }',
  variables: { email: '[email protected]', password: '123456' }
}

↑ all examples


Query (with custom argument name):

import { gqlQuery } from "gql-payload";

const query = gqlQuery([{
  operation: "someoperation",
  fields: [{
    operation: "nestedoperation",
    fields: ["field1"],
    variables: {
      id2: {
        name: "id",
        type: "ID",
        value: 123
      }
    }
  }],
  variables: {
    id1: {
      name: "id",
      type: "ID",
      value: 456
    }
  }
}]);

console.log(query);

Output:

{
  query: 'query ($id2: ID, $id1: ID) { someoperation (id: $id1) { nestedoperation (id: $id2) { field1 } } }',
  variables: { id1: 456, id2: 123 }
}

↑ all examples


Query (with operation name):

import { gqlQuery } from "gql-payload";

const query = gqlQuery({
  operation: "userLogin",
  fields: ["userId", "token"]
}, {
  operationName: "someoperation"
});

console.log(query);

Output:

{
  query: 'query someoperation { userLogin { userId token } }',
  variables: {}
}

↑ all examples


Query (with empty fields):

import { gqlQuery } from "gql-payload";

const query = gqlQuery([
  {
    operation: "getFilteredUsersCount"
  },
  {
    operation: "getAllUsersCount",
    fields: []
  },
  {
    operation: "getFilteredUsers",
    fields: [{ count: [] }]
  }
]);

console.log(query);

Output:

{
  query: 'query { getFilteredUsersCount getAllUsersCount getFilteredUsers { count } }',
  variables: {}
}

↑ all examples


Query (with alias):

import { gqlQuery } from "gql-payload";

const query = gqlQuery({
  operation: {
    name: "thoughts",
    alias: "myThoughts"
  },
  fields: ["id", "name", "thought"]
});

console.log(query);

Output:

{
  query: 'query { myThoughts: thoughts { id name thought } }',
  variables: {}
}

↑ all examples


Query (with inline fragment):

import { gqlQuery } from "gql-payload";

const query = gqlQuery({
  operation: "thought",
  fields: [
    "id",
    "name",
    "thought",
    {
      operation: "FragmentType",
      fields: ["emotion"],
      inlineFragment: true
    }
  ]
});

console.log(query);

Output:

{
  query: 'query { thought { id name thought ... on FragmentType { emotion } } }',
  variables: {}
}

Query (with named fragment):

import { gqlQuery } from "gql-payload";

const query = gqlQuery({
  operation: "thought",
  fields: [
    "id",
    "name",
    "thought",
    {
      operation: "FragmentName",
      namedFragment: true
    }
  ]
}, {
  fragments: [
    {
      name: "FragmentName",
      on: "FragmentType",
      fields: ["emotion"]
    }
  ]
});

console.log(query);

Output:

{
  query: 'query { thought { id name thought ...FragmentName } } fragment FragmentName on FragmentType { emotion }',
  variables: {}
}

↑ all examples


Query (with adapter defined):

For example, to inject SomethingIDidInMyAdapter in the operationWrapperTemplate method.

import { gqlQuery } from "gql-payload";
import MyQueryAdapter from "where/adapters/live/MyQueryAdapter";

const query = gqlQuery({
  operation: "thoughts",
  fields: ["id", "name", "thought"]
}, null, MyQueryAdapter);

console.log(query);

Output:

{ 
  query: 'query SomethingIDidInMyAdapter { thoughts { id name thought } }',
  variables: {}
}

Take a peek at DefaultQueryAdapter to get an understanding of how to make a new adapter.

↑ all examples


Mutation:

import { gqlMutation } from "gql-payload";

const mutation = gqlMutation({
  operation: "thoughtCreate",
  variables: {
    name: "Tyrion Lannister",
    thought: "I drink and I know things."
  },
  fields: ["id"]
});

console.log(mutation);

Output:

{
  query: 'mutation ($name: String, $thought: String) { thoughtCreate (name: $name, thought: $thought) { id } }',
  variables: { name: 'Tyrion Lannister', thought: 'I drink and I know things.' }
}

↑ all examples


Mutation (with required variables):

import { gqlMutation } from "gql-payload";

const mutation = gqlMutation({
  operation: "userSignup",
  variables: {
    name: { value: "Jon Doe" },
    email: { value: "[email protected]", required: true },
    password: { value: "123456", required: true }
  },
  fields: ["userId"]
});

console.log(mutation);

Output:

{
  query: 'mutation ($name: String, $email: String!, $password: String!) { userSignup (name: $name, email: $email, password: $password) { userId } }',
  variables: { name: 'Jon Doe', email: '[email protected]', password: '123456' }
}

↑ all examples


Mutation (with custom types):

import { gqlMutation } from 'gql-payload'

const mutation = gqlMutation({
  operation: "userPhoneNumber",
  variables: {
    phone: {
      value: { prefix: "+91", number: "9876543210" },
      type: "PhoneNumber",
      required: true
    }
  },
  fields: ["id"]
})

console.log(mutation)

Output:

{
  query: 'mutation ($phone: PhoneNumber!) { userPhoneNumber (phone: $phone) { id } }',
  variables: { phone: { prefix: '+91', number: '9876543210' } }
}

↑ all examples


Mutation (with adapter defined):

For example, to inject SomethingIDidInMyAdapter in the operationWrapperTemplate method.

import { gqlMutation } from "gql-payload";
import MyMutationAdapter from "where/adapters/live/MyMutationAdapter";

const mutation = gqlMutation({
  operation: "thoughts",
  fields: ["id", "name", "thought"]
}, null, MyMutationAdapter);

console.log(mutation);

Output:

{ 
  query: 'mutation SomethingIDidInMyAdapter { thoughts { id name thought } }',
  variables: {}
}

↑ all examples

Take a peek at DefaultMutationAdapter to get an understanding of how to make a new adapter.

Mutation (with operation name):

import { gqlMutation } from "gql-payload";

const mutation = gqlMutation({
  operation: "thoughts",
  fields: ["id", "name", "thought"]
}, {
  operationName: "someoperation"
});

console.log(mutation);

Output:

{
  query: 'mutation someoperation { thoughts { id name thought } }',
  variables: {}
}

↑ all examples


Subscription:

import { gqlSubscription } from "gql-payload";

const subscription = gqlSubscription({
  operation: "thoughtCreate",
  variables: {
    name: "Tyrion Lannister",
    thought: "I drink and I know things."
  },
  fields: ["id"]
});

console.log(subscription);

Output:

{
  query: 'subscription ($name: String, $thought: String) { thoughtCreate (name: $name, thought: $thought) { id } }',
  variables: { name: 'Tyrion Lannister', thought: 'I drink and I know things.' }
}

↑ all examples


Subscription (with adapter defined):

For example, to inject SomethingIDidInMyAdapter in the operationWrapperTemplate method.

import { gqlSubscription } from "gql-payload";
import MySubscriptionAdapter from "where/adapters/live/MySubscriptionAdapter";

const subscription = gqlSubscription({
  operation: "thoughts",
  fields: ["id", "name", "thought"]
}, null, MySubscriptionAdapter);

console.log(subscription);

Output:

{ 
  query: 'subscription SomethingIDidInMyAdapter { thoughts { id name thought } }',
  variables: {}
}

Take a peek at DefaultSubscriptionAdapter to get an understanding of how to make a new adapter.

↑ all examples


Example with Fetch

import { gqlQuery } from "gql-payload";

async function getThoughts () {
  const query = gqlQuery({
    operation: "thoughts",
    fields: ["id", "name", "thought"]
  });

  try {
    const response = await fetch("http://api.example.com/graphql", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(query)
    });
    const data = await response.json();
    console.log(data);
  }
  catch (error) {
    console.log(error);
  }
}

↑ all examples


Example with Ofetch

import { $fetch } from "ofetch";
import { gqlQuery } from "gql-payload";

async function getThoughts () {
  const query = gqlQuery({
    operation: "thoughts",
    fields: ["id", "name", "thought"]
  });

  const data = await $fetch("http://api.example.com/graphql", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: query
  }).catch((error) => console.log(error));

  console.log(data);
}

↑ all examples


Example with Axios

import axios from "axios";
import { gqlQuery } from "gql-payload";

async function getThoughts () {
  try {
    const response = await axios.post(
      "http://api.example.com/graphql",
      gqlQuery({
        operation: "thoughts",
        fields: ["id", "name", "thought"]
      })
    );

    console.log(response);
  }
  catch (error) {
    console.log(error);
  }
}

↑ all examples