Git Product home page Git Product logo

apex-graphql-client's Introduction

Saleforce Apex GraphQL Client

CI codecov

The package for Salesforce that aimed to provide a convenient way to communicate with a GraphQL server via Apex.

What is supported:

  • ✅ Building queries, mutations and subscriptions
  • ✅ Building graphql nodes (fields). If you want to send requests yourself
  • ✅ Passing arguments to the graphql nodes (fields)
  • ✅ Passing variables to the graphql operations from request
  • ✅ Passing directives to the graphql operations and nodes
  • ✅ Using fragments for graphql requests. Inline fragments are supported as well.
  • ✅ Sync and async graphql HTTP client for sending requests (with callback implementation for async calls)
  • ✅ Handling responses in GraphQL format

What is NOT supported:

  • ❌ Sending subscription requests (WebSocket protocol is not supported by Apex)

If you think there is something that is not implemented yet as for GraphQL client I'd appreciate if you open an issue/discussion in this repository.

🔍 Overview

Generate a GraphQL node

GraphQL node statement:

continents {
  name
  countries {
    name
    capital
    currency
  }
}

Equivalent Apex code:

GraphQLField continents = new GraphQLField('continents')
    .withField('name')
    .withField(new GraphQLField(
        'countries',
        new List<String> { 'name', 'capital', 'currency' }
    ));

// Will print a well-formatted node just like on the example above
System.debug(continents.build(true));

Create a query GraphQL request

GraphQL query statement:

query {
  countries(filter: "Bel", count: 1) {
    name
    capital
    currency
  }
  continents {
    name
  }
}

Equivalent Apex code:

GraphQLField countries = new GraphQLField(
    'countries',
    new List<String> { 'name', 'capital', 'currency' }
)
    .withArgument('filter', 'Bel')
    .withArgument('count', 1);

GraphQLField continents = new GraphQLField(
    'continents',
    new List<String> { 'name' }
);

GraphQLQuery query = new GraphQLQuery(
    new List<GraphQLField> { countries, continents }
);

System.debug(query.build(true));

After you created a query or mutation you can send it to the GraphQL endpoint:

...
GraphQLRequest request = query.asRequest();

// Add custom header if needed
request.withHeader('Authorization', 'Bearer token');

// Provide a GraphQL endpoint to the client
GraphQLHttpClient client = new GraphQLHttpClient('https://gql-endpoint.com/graphql');

GraphQLResponse response = client.send(request);

// Check if there are any errors and data
System.debug(response.hasErrors());
System.debug(response.hasData());

List<GraphQLResponseError> errors = response.getErrors();
Map<String, Object> dataAsMap = response.getData();
// It's also possible to get data as any Apex class type
SomeWrapper dataAsWrapper = (SomeWrapper) response.getDataAs(SomeWrapper.class);

Alternatively, sometimes it's easier to just send a request as a plain string, so you can do:

String query = 'query { countries { name, capital, currency } }';

GraphQLRequest request = new GraphQLRequest(query);

// Provide a GraphQL endpoint to the client
GraphQLHttpClient client = new GraphQLHttpClient('https://gql-endpoint.com/graphql');

GraphQLResponse response = client.send(request);

...

All examples can be found here.

🚀 Installation

From Unmanaged Package

You can just install the package by the link on a sandbox or dev org.

If you prefer using salesforce CLI you can simply run:

sfdx package:install -p 04t7R000000FE1lQAG -w 10 -b 10 -o <username>

From Source

You can also install the package with the automated scripts: pkg-deploy.sh and pkg-from-scratch.sh. First is for deploying changes to the existing org:

./scripts/pkg-deploy.sh <username>

Second is for creating a new configured scratch org:

./scripts/pkg-from-scratch.sh <devhub_username> <scratch_username>

📝 Documentation

For more detailed information about the content of the repository and the package, please visit the documentation page.

There is also a nice article on medium.com by Justin Wills about how to use this library with the Shopify integration. He has also posted a video on YouTube for the same topic.

The changelog is here.

❓ Questions

If you have any questions you can start a discussion. If you think something works not as expected you can create an issue. If you want to request a new feature you can create an issue with the appropriate template selected.

🤝 Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate.

License

MIT

apex-graphql-client's People

Contributors

ilyamatsuev avatar

Stargazers

Pramod avatar jbold avatar Andrew Wisniowski avatar Sathish Balaji avatar Tom Souza avatar Brent Bowers avatar Ross Belmont avatar Alessandro Porfírio avatar Kevin O'Hara avatar  avatar Lahcen Lamkirich avatar Léonard Henriquez avatar  avatar Jan Kaczorowski avatar Marshall Vaughn avatar Jesse R K avatar Vince Kruger avatar  avatar Justin avatar  avatar Rafael Neto avatar Austin Barwick avatar  avatar  avatar Muhammad Saad Siddique - Supporting Palestine avatar  avatar Birger Wollburg avatar  avatar a.septilko avatar Adela Zalewski avatar  avatar Andreu avatar Valentin Dubaleko avatar Anastasiya Septilko avatar

Watchers

Vince Kruger avatar James Cloos avatar  avatar Jason Hurder avatar

apex-graphql-client's Issues

Support for nested arguments a GraphQLNode

What is missing from the application? Please describe.

I'd like to be able to specify nest arguments in a GraphQLNode object. The current structure doesn't seem to serialize the objects appropriately as the values are being treated as strings.

The query I am trying to build contains a nested parameter in the order argument list: customerLink: { ref: $customerRef }. When I attempt to use the withArgument method, the argument value is rendered as a string rather than a json object.

This is the query I am attempting to construct:

query OrderQuery ($count: Int = 10, $cursor: String = null, $ref: [String] = null, $status: [String], $customerRef: String!) {    
  orders (first: $count, after: $cursor,  ref: $ref, status: $status,  customerLink: { ref: $customerRef })  { 
    pageInfo { 
      hasPreviousPage 
      hasNextPage 
    } 
    edges {   
        cursor 
      node { 
        id            
        status
      }       
    }     
  }   
} 

Here is my code to build this query out:

public override GraphQLQueryNode GetQuery()
{   
    
    GraphQLNode orderNode 
        = new GraphQLNode('node')
            .withFragment('OrderHeaderFields');
    if (m_params.IncludeLines)
    {
        GraphQLNode orderItemsNode 
            = new GraphQLNode('items')
                .withNode(new GraphQLNode('edges')
                    .withNode(new GraphQLNode('node')
                        .withFragment('OrderLineFields')));
        orderNode.withNode(orderItemsNode);
    }   
    
    GraphQLNode parentNode = new GraphQLNode('orders')  
        .withArgument('first', '$count')
        .withArgument('after', '$cursor')
        .withArgument('ref', '$ref')
        .withArgument('status', '$status')
        .withNode(new GraphQLNode('pageInfo', new List<string> {'hasPreviousPage', 'hasNextPage'}))
        .withNode(new GraphQLNode('edges', new List<string> {'cursor'})
            .withNode(orderNode));      
    if (m_params.CustomerId != null)
    {            
        parentNode.withArgument('customerLink', new Map<string, object> { 'ref' => '$customerRef'});
    }
    GraphQLQueryNode query = new GraphQLQueryNode('OrderQuery', parentNode);
    query.fragments.add(OrderHeaderQueryFragment.getFragment());
    
    if (m_params.IncludeLines)
        query.fragments.add(OrderHeaderQueryFragment.getLineFragment());
    
    query.withVariable('count', 'Int = 10');
    query.withVariable('cursor', 'String = null');        
    query.withVariable('ref', '[String] = null');  
    query.withVariable('status', '[String] = null');
    
    if (m_params.CustomerId != null)
       query.withVariable('customerRef', 'String!');  
    
    return query;    
}

The code I've used to generate this renders the query like this (notice '$customerRef' is in double quotes):

query OrderQuery($count: Int = 10, $cursor: String = null, $ref: [String] = null, $status: [String] = null, $customerRef: String!)  {
  orders(first: $count, after: $cursor, ref: $ref, status: $status, customerLink: {ref:"$customerRef"}) {
    pageInfo {
      hasPreviousPage
      hasNextPage
    }
    edges {
      cursor
      node {
        id
        status
      }
    }
  }
}

Describe the solution you'd like

I'd like to be able to nest arguments in the query as my example shows at the top/

Describe alternatives you've considered

I've modifed the GraphQLArgument code locally to allow passing a nested GraphQLArgument to the withVariable() method. I added code to handle the GraphQLArgument type in the toString() method where it renders the key/value pair as desired.

Allow enums in complex arguments

Discussed in #33

Originally posted by GuiuGaldino March 11, 2024
Hello, I am trying to use enum in a nested argument in a mutation request but it seens it is not working properly. See the example below and the mutation when i run revokeDrivePrevileges .build():

GraphQLField revokeDrivePrevileges = new GraphQLField('revokeCoReader')
            .withArgument('brandId', 'BMW')
            .withArgument('carType', 'SUV')
            .withArgument('accountId', '12345768')
            .withArgument(
                'metadata',
                new Map<String, Object>{
                    'channel' => new GraphQLEnum(Constants.CHANNEL),
                    'authorType' => new GraphQLEnum(Constants.AUTHOR_TYPE),
                    'agentId' => '123456'
                }
            );

revokeCoReader(brandId:"BMW",carType:"SUV",accountId:"12345768",metadata:{agentId:"123456",authorType:{value:"AGENT"},channel:{value:"SALESFORCE"}})


When a complex argument is serialized, Apex doesn't know how to serialize the GraphQLEnum instances, which leads to them being serialized in a format like this: { "value": "ENUM_VALUE" }

Expected behavior: any GraphQLEnum variable/instance should be serialized as a value only, without double quotes, as part of any argument (custom map or an Apex class)

Getting a Syntax Error: Expected $, found @

Summary

I am trying to implement a mutation that creates a token using an email and password combination in the variables. I am receiving this error: First error: Syntax Error GraphQL (1:37) Expected $, found @ in reference to the @ in the email being passed.

Steps To Reproduce:

  1. Created the code using this structure:

` GraphQLField tokenCreateNode = new GraphQLField('tokenCreate')
// Point the argument to the variables
.withArgument('email', '$email')
.withArgument('password', '$password')
.withField('token')
.withField('refreshToken');

GraphQLMutation mutation = new GraphQLMutation('CreateToken', tokenCreateNode)
// Define variable for the mutation
.defineVariable('email', email)
.defineVariable('password', password);`

Expected result

Successful callout

Actual result

Getting syntax error

Additional information

Feel free to attach a screenshot or code snippets.

I can't seem to be able to install the package in my sandbox

Summary

Short summary of what is going on or to provide context.

Steps To Reproduce:

  1. This is step 1. Clicked the install in sandbox link form your readme
  2. This is step 2. Clicked install for admins only, but al lit does is running and saying looking for admins and them error when it times out because the run time is took too long

Expected result

Expected it not to take so long to install and time out ..

Actual result

got an email that let me know the installation of the package failed

Additional information

Feel free to attach a screenshot or code snippets.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.