Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

gql-payload

Package Overview
Dependencies
Maintainers
0
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

gql-payload

GraphQL Payload Builder

  • 2.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
16
decreased by-56.76%
Maintainers
0
Weekly downloads
 
Created
Source

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

NameDescriptionTypeRequiredExample
operationName of operation to be executed on serverString | ObjectYes getThoughts, createThought

{ name: 'getUser', alias: 'getAdminUser' }
fieldsSelection of fieldsArrayNo ['id', 'name', 'thought']

['id', 'name', 'thought', { user: ['id', 'email'] }]
variablesVariables sent to the operationObjectNo { key: value } eg: { id: 1 }

{ key: { value: value, required: true, type: GQL type, list: true, name: argument name } eg:
{ email: { value: "user@example.com", required: true }, password: { value: "123456", required: true }, secondaryEmails: { value: [], required: false, type: 'String', list: true, name: secondaryEmail } }

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

NameDescriptionTypeRequiredExample
operationNameName of operation to be sent to the serverStringNo getThoughts, createThought
fragmentNamed fragment config for reusable fields to be sent to the serverArrayNo [{ name: "NamedFragment", on: "User", fields: ["grade"] }]

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: "jon.doe@example.com", 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: 'jon.doe@example.com', 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: "jon.doe@example.com", 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: 'jon.doe@example.com', 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

Keywords

FAQs

Package last updated on 28 Aug 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc