Coder Social home page Coder Social logo

graphql-js-client's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphql-js-client's Issues

How do you sort products by the criterias specified in the shopify docs using the client?

I have this query to fetch the products which is working fine:

const fetchProductsWithVariants = (
  client,
  productQty = 10,
  variantQty = 10,
  imagesQty = 10,
  collectionQty = 5
) =>
  client.query(root => {
    root.add("shop", shop => {
      shop.add("name");
      shop.addConnection(
        "products",
        { args: { first: productQty } },
        product => {
          product.add("id");
          product.add("title");
          product.add("description");
          product.addConnection(
            "variants",
            { args: { first: variantQty } },
            variant => {
              variant.add("id");
              variant.add("title");
              variant.add("price");
              variant.add("image", image => {
                image.add("src");
                image.add("id");
                image.add("altText");
              });
            }
          );
          product.addConnection(
            "images",
            { args: { first: imagesQty } },
            image => {
              image.add("src");
            }
          );
          shop.addConnection(
            "collections",
            { args: { first: collectionQty } },
            collection => {
              collection.add("id");
              collection.add("title");
              collection.add("image", image => image.add("src"));
            }
          );
        }
      );
    });
  });

My question is, how do I sort those products by price or any other criteria? I think it's necessary to complete the docs since it barely has information on how to achieve a lot of things that you can do with raw queries

[Feature Request]: Typescript Types for Shopify GraphQL Schema

I'm not sure if this is in the scope of this repo, or another, so I apologize if this is in the wrong spot.

Is it possible to get all of typescript types of the GraphQL Storefront API?

E.g.

interface GetAllProductsResponse {
  shop?: {
    products?: ProductEdge[]
  }
}

interface ProductEdge {
  node: Node
}

interface ProductNode {
  id?: string;
  title?: string;
}

Currently, I'm defining these types as I go along based on the docs I'm reading here.

Is there a standard set of these for typescript that is either:

  1. Published internally at shopify and potentially published as Open Source
  2. Published open source already and I can't seem to find them

Finally, if a package doesn't exist, is this something that would be valuable, or am I proposing a solution to a non-existant problem?

Fetch a given amount of Products from Collection

I need to load only a small amount of Products from a given Collection for using it with InfinityScroll

getProductsInCollection(collectionId) {
        let query = this.shopClient.query((root) => {
            root.add('node', {args: {id: collectionId}, alias: 'collection'}, (node) => {
                node.addInlineFragmentOn('Collection', (collection) => {
                    collection.add('id');
                    collection.addConnection('products', {args: {first: 20}}, (products) => {
                        products.add('id');
                        products.add('title');
                        products.addConnection('variants', {args: {first: 1}}, (variants) => {
                            variants.add('price');
                        });
                        products.addConnection('images', {args: {first: 1}}, (images) => {
                            images.add('src');
                        })
                    })
                })
            })
        });

        return this.shopClient.send(query).then(({model, data}) => {
            // returns all Pages
            //return this.shopClient.fetchAllPages(model.collection.products, {pageSize: 20})
           
           // return first 10
          return model.collection.products;
        });
   }

Do you know if there is a Function to build the Pagination or do i have to implement the Logic?
Or is it even better to build Queries using native GraphQL without using "graphql-js-client"?

Deprecated examples

Examples on the repository documentation use deprecated fields.
All example use shop to fetch everything:
https://github.com/Shopify/graphql-js-client#creating-and-sending-a-query

const query = client.query((root) => {
  root.add('shop', (shop) => {
    shop.add('name');
    shop.addConnection('products', {args: {first: 10}}, (product) => {
      product.add('title');
    });
  });
});

instead of this

const query = client.query((root) => {
  root.add('products', {args: {first: 10}}, (product) => {
    product.add('title');
  });
});

Is it mentioned in the Storefront API documentation that using shop to fetch products, collections, etc is deprecated https://help.shopify.com/en/api/custom-storefronts/storefront-api/reference/object/shop

I think the documentation could me more clearer about this and also add more examples how to fetch mandatory object for an online store, such as collections, producByHandle, search, etc

Enum Problem

I'm trying to run a mutation here that has one of its arguments an object that has an enum. This is the object:

# Webhook Information
type WebhookInfo {
  # Type of this webhook
  type: WebhookTypeEnum

  # URL to call
  url: String

  # List of calls that has already been made for this webhook
  calls: [WebhookCall]

  # JSON string containing extra data that should be sent with the main payload
  extra: String
}
# Webhook Type Enum
enum WebhookTypeEnum {
  # Simple JSON POST
  post
}

and them I'm trying to run:

    webhooks.forEach((wh) => {
      wh.type = this._client.enum(wh.type); // wh.type is originally 'post' string
    });
    const mutation = this._client.mutation((root) => {
      root.add('RequestAccountCreation', {
        args: {
          input: {
            clientId,
            requesterPayload,
            requesterFingerprint,
            requesterSignature,
            extra,
            webhooks: webhooks || [],
          },
        },
      }, (rac) => {
        rac.add('requestId');
        rac.add('error', (error) => {
          error.add('errorCode');
          error.add('message');
          error.add('errorField');
          error.add('errorData');
        });
      });
    });

But when I run, I get a parser error:

In field "webhooks": In element #0: In field "type": Expected type "WebhookTypeEnum", found {key: {name: "WebhookTypeEnum", description: "Webhook Type Enum", _values: [{name: "post", description: "Simple JSON POST", isDeprecated: false, deprecationReason: undefined, value: "POST"}], _enumConfig: {name: "WebhookTypeEnum", description: "Webhook Type Enum", values: {post: {value: "POST", description: "Simple JSON POST"}}}}}

Any ideas? Is that a bug, or I'm doing it wrong?

MVP Features

Tasks

Refetch / Next page

  • Rename graph to Query, which is part of a Document

  • Maybe separate relay assumptions...? (Document & RelayDocument?

  • Pruning to nearest Node.

    • Find nearest node
  • Pruning to this graph is a Node.

    • graph.type.isNode
  • Will require graph.dup()

    Duplicates this graph instance. Not parents or children. Means
    restructuring won't actually have side effects on an existing query
    structure.

  • Will require the ability to add a sub graph through addField

  • Support interfaces in `graphql-js-schema

  • Add to args (at least for connections: cursor, after)

  • Arguments with variables eg. input: $input

  • Will require pairing the query graph to the deserialized graph

  • Some sane way to have as a default on queries.

query {
  ... on Node {
    id
  }
}

Named Fragments and references

  • complete? subtasks?

Named Documents

  • contains queries
  • contains mutations

Mutations

  • complete? subtasks?

Parity in CLI lints and generated lints

  • complete? subtasks?

Inspiration from graphq-ruby-client

Unions

  • figure out what we need to do to support unions

CORB errors

Hello, while requesting client side, I'm hitting the following :

Cross-Origin Read Blocking (CORB) blocked cross-origin...

While using "Content-Type": "application/json", in order to be able to use the defaults query and variablesthat graphql usually provide.

This is basically what the graphiql page use (https://help.shopify.com/en/api/graphiql)

It does work ok while using "Content-Type": "application/graphql". But in that case, it is not possible to use query/variables capabilities

Is the behaviour expected; or is there something to solve ?

Thx for your help

We should not allow for empty fragments fields should be selected

I don't think we should allow users to create empty fragments for instance in this case:

const graph = new Graph('Shop');

assert.deepEqual(splitQuery(graph.toQuery()), splitQuery('fragment on Shop { }'));

We should probably throw an Error when the user calls graph.toQuery(). Basically be pre-emptive on helping the user before they get errors back from the API.

Issue with webURL missing checkout.shopify.com?

Seems like checkout object returned when adding line items is returning a malformed url.

For example:
https:///{shopifyStoreId}/checkouts/{checkoutId}?key={key}

It has been doing that for approximately 3 hours now.

I know this comes with the beta but it seems like the API is stable and I checked the graphql response. It came directly from the API and wasn't modified by the client.

Let me know if you need me to provide more info. I'd be happy to submit a bug report with actual cart IDs, request query, etc.

TypeError: undefined is not an object (evaluating '_graphql.default.send')

I am trying to run a Shopify mutation for customerCreate in react native using react-graphql-client. The following code is what I have written so far. Somehow, it shows the error: Possible Unhandled Promise Rejection (id: 0): TypeError: undefined is not an object (evaluating '_graphql.default.send').

"@react-native-community/async-storage": "^1.11.0",
"@react-native-community/masked-view": "^0.1.10",
"@react-native-community/netinfo": "^5.9.4",
"@shopify/koa-shopify-auth": "^3.1.64",
"axios": "^0.19.2",
"babel-plugin-graphql-js-client-transform": "^1.1.1",
"clone-deep": "^4.0.1",
"convert-css-color-name-to-hex": "^0.1.1",
"dotenv": "^8.2.0",
"graphql-js-client": "^0.12.0",
"isomorphic-fetch": "^2.2.1",
"koa": "^2.13.0",
"koa-session": "^6.0.0",
"lodash": "^4.17.19",
"react": "16.11.0",
"react-dom": "^16.13.1",
"react-native": "0.62.2",
"react-native-elements": "^2.0.2",
"react-native-firebase": "^5.6.0",
"react-native-gesture-handler": "^1.6.1",
"react-native-indicators": "^0.17.0",
"react-native-modal": "^11.5.6",
"react-native-phone-input": "^0.2.4",
"react-native-reanimated": "^1.9.0",
"react-native-safe-area-context": "^3.0.5",
"react-native-screens": "^2.8.0",
"react-native-shopify": "^0.2.7",
"react-native-snap-carousel": "^3.9.1",
"react-native-splash-screen": "^3.2.0",
"react-native-swipe-list-view": "^3.1.2",
"react-native-vector-icons": "^6.6.0",
"react-navigation": "^4.3.9",
"react-navigation-stack": "^2.7.0",
"react-navigation-tabs": "^2.8.13",
"react-redux": "^7.2.0",
"redux": "^4.0.5",
"redux-devtools-extension": "^2.13.8",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"shopify-buy": "^2.10.0",
"util": "^0.12.3"

How do you make arguments dynamic?

Let's say I add a connection:

shop.addConnection('collections, {first: 10, startingAt: '12345'}, collections => {

});

How do we make it so that you can modify those args after the fact when requesting a query?

This also applies for addField

how to access collection by id or collectionByHandle ?

  • Keep getting below error while try to access collection.
    Error: No field of name "collection" found on type "Shop" in schema

  • Overall please let me know how to access particular collection using given sample code in readme.

  • Also give any other method to generate query.
    Here is my code,

const proquery1 = client.query((root) => {
	root.add('shop', (shop) => { 
	   shop.add('name');
	   shop.addConnection('collection', {args: {id: "gid://shopify/Collection/<collection_id>"}}, (collection) => {
		 collection.addConnection('products', {args: {first: 4}}, (product) => {
		 product.add('title');
		 product.addConnection('variants', {args: {first: 1}}, (variant) => {
		   variant.add('title');
		 variant.add('price');
		   });
		 });
	    });
	 });
	});

Any way of sending a raw query with the client??

I was curious to see if I had the possibility to do this. It wasn't on the docs. The query builder is nice but for some use cases it would be useful to be able to send the ray query since the shopify storefront example is broken for raw queries and new react versions using gql package for raw queries....

Is this alive and good for production?

It seems that activity is sparse on this repo.

2 PRs that seem abandoned and are over a year old.

Any advice on the best approach to use Storefront API GraphQL?

why my fetchNextPage is not work

here is my code

// search product by title
export const searchProduct = (query, first = 5) => {
  return graphQLClient.send(gql(graphQLClient)`
    query ($query: String){
      products(query: $query, first: 5) {
        edges {
          cursor
          node {
            id
            title
            images (first: 1) {
              edges {
                node {
                  id
                  src
                }
              }
              pageInfo { hasNextPage, hasPreviousPage }
            }
            description
          }
        }
        pageInfo {
          hasNextPage
          hasPreviousPage
        }
      }
    }
  `, { query })

const query = `title:*${this.keyword}*`
searchProduct(query)
        .then(res => {
          const products = res.model.products
          this.products.push(...products)
          this.hasMore = products[products.length - 1].hasNextPage
          nextPageProduct = products
        })

it is works, but when i use fetchNextPage, it's not work, get error "undefined isn't a defined input type (on $query)"

graphQLClient.fetchNextPage(nextPageProduct)

and here is the fetchNextPage Request

{"query":"query ($query:undefined,$first:Int = 5)  { products (query: $query first: $first after: \"eyJsYXN0X2lkIjo1MzY1OTY3MDk0NDIsImxhc3RfdmFsdWUiOjUzNjU5NjcwOTQ0Mn0=\") { pageInfo { hasNextPage,hasPreviousPage },edges { cursor,node { id,title,images (first: 1) { edges { node { id,src } },pageInfo { hasNextPage,hasPreviousPage } },description } } } }","variables":{"query":"title:*Hydro*"}}

can someone tell me how to fix it ?

// package.json
"dependencies": {
    "babel-plugin-graphql-js-client-transform": "^1.1.1",
    "graphql-js-client": "^0.12.0"
  },

Unable to get Product Filter listing

Unable to get Product Filter listing using Shopify storefront API Version 2022-01

I have changed types as below(added "filters"):

const ProductConnection = {
"name": "ProductConnection",
"kind": "OBJECT",
"fieldBaseTypes": {
"edges": "ProductEdge",
"pageInfo": "PageInfo",
"filters": "Filters"
},
"implementsNode": false
};
Object.freeze(ProductConnection.fieldBaseTypes);
var ProductConnection$1 = Object.freeze(ProductConnection);

I'm trying to set the query as below but not working:

{
collectionByHandle(handle: "filterable-collection") {
handle
products(first: 10) {
filters {
id
label
type
values {
id
label
count
input
}
}
}
}
}

Ref.: https://shopify.dev/custom-storefronts/products/filter-products

Is there any change require n type or query?

Fetching Colletion Image does not work

I'm building an Shopify Ionic 3 App using the Storefront API.
Fetching ID and Title works. But trying to access Image it fails.

Using "GraphiQL" with this Query

{
  shop {
    collections(first: 1) {
      edges {
        node {
          id
          title
          handle
          image {
            originalSrc
          }
        }
      }
      pageInfo {
        hasNextPage
      }
    }
  }
}

will Result with

{
  "data": {
    "shop": {
      "collections": {
        "edges": [
          {
            "node": {
              "id": "Z2lkOi8vc2hvcGlmeS9Db2xsZWN0aW9uLzM2NTUwNjY5OQ==",
              "title": "Snacks",
              "handle": "snacks-co",
              "image": {
                "originalSrc": "https://cdn.shopify.com/s/files/1/2262/0831/collections/Snacks_Collection.jpg?v=1524511173"
              }
            }
          }
        ],
        "pageInfo": {
          "hasNextPage": true
        }
      }
    }
  }
}

Using "graphql-js-client" with Ionic 3, Collection Image is not available.

// Service Provider Function
getCollectionsWithImage() {
  let query = this.client.query((root) => {
    root.add('shop', (shop) => {
      shop.addConnection('collections', {args: {first: 16}}, (collection) => {
        collection.add('id');
        collection.add('title');

        // THIS does not work
        // collection.add('image', {args: {first: 1}}, (image) => {
        //     image.add('originalSrc');
        // })

       // THIS does not work
        // collection.addConnection('image', {args: {first: 1}}, (image) => {
        //     image.add('originalSrc');
        // })                  
       })
    })
  });

  return this.client.send(query).then(({model, data}) => {
    return model.shop.collections;
  });
}

Do you have any Idea?

Not handling 'text/html' Content-Type responses

Hey all ๐Ÿ‘‹

Scenario:

The 403 Forbidden response from the Shopify Graphql API returns a text/html Content-Type. Currently the httpFetcher always runs response.json() regardless of Content-Type. This causes a Syntax Error: Unexpected end of JSON input. on these 403s

Proposed Solution:

Detect content-type by looking at the response headers, and run the appropriate method to parse the response body, a simple implementation of this would look similar to this update to the httpFetcher:

export default function httpFetcher(url, options = {}) {
  return function fetcher(graphQLParams) {
    return fetch(url, {
      body: JSON.stringify(graphQLParams),
      method: 'POST',
      mode: 'cors',
      ...options,
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        ...options.headers
      }
    }).then((response) => {
      const contentType = response.headers.get('content-type');

      if (contentType.includes('application/json')) {
        return _handleJSONResponse(response);
      }

      return _handleTextResponse(response);
    });
  };
}

where _handleJSONResponse and _handleTextResponse would have the response.json() and response.text() calls respectively, as well as wrapping the the body fromtext/html responses in an object, so that the return value of httpFetcher is always an object.

This is just a suggested solution, to get the conversation started on how to handle these non-json responses. I'd love to hear any other possible ways to handle this.

Thanks!

GraphQL Bug?

Hi - is maxVariantPrice being different than price intended?

Screen Shot 2020-05-02 at 3 57 46 PM

Querying existing checkout

Hi, I'm having trouble determining how to implement this kind of syntax:
{ node(id: "your_id_here") {
id
... on Checkout {

}
}

I've successfully queried the checkout node, and have tried a bunch of methods to try to include the checkout object in the results, but it keeps giving me errors. So far the easiest way for me to get around this has been just to send an empty mutation to the 'checkoutLineItemsAdd' instead, but this obviously feels wrong.

Incorrect return type in documentation of Client#fetchNextPage

Hello everyone!

While writing code which utilizes the js-buy-sdk from Shopify, I noticed that the documented return type for Client#fetchNextPage() is Promise<GraphModel[]>, when in fact it returns an object, where the GraphModel[] is under the key model, as seen in the code.

That also means that the types for the js-buy-sdk are also incorrect (in the types it's also not marked as returning a Promise, but that's not a big of a deal, relatively).

So, the question, I suppose, is whether the documentation is incorrect or the code?

Thank you in advance.

How to query node?

I have this query which I want to build

query node{
blogs(first: 250){
edges{
node{
articles(first: 250){
edges{
node{
handle
content
}
}
}
}
}
}
}

how to query for variants with a particular price

I have been trying to understand graphql-js-client. Still I am unable to run the code. using graphql we can fetch variants with its id, title, price. we can pass following arguments during fetching varinats: 'first', 'after' etc. But I want to fetch variants with a particular price or with a particular price range.

Is it possible to fetch variants with particular price or price range ?

I have been exploring shopify admin APIs, storefront APIs to achieve this but in vain. I could not find any solution.

scriptTagCreate access denied in Shopify GraphQL App

I'm trying to create the script tag using the following mutation in the Shopify's GraphQL app.

mutation scriptTagCreate($input: ScriptTagInput!) {
  scriptTagCreate(input: $input) {
    scriptTag {
      id
    }
    userErrors {
      field
      message
    }
  }
}

with the following variables,

{
  "input": {
    "displayScope": "ALL",
    "src": "https://raw.githubusercontent.com/pavinduLakshan/model/master/liveview.js"
  }
}

However I'm getting scriptTagCreate access denied error. Since there is no additional output, I cannot imagine what is the actual issue. here,

{
  "data": {
    "scriptTagCreate": null
  },
  "errors": [
    {
      "message": "ScriptTagCreate access denied",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "scriptTagCreate"
      ]
    }
  ],
  "extensions": {
    "cost": {
      "requestedQueryCost": 10,
      "actualQueryCost": 10,
      "throttleStatus": {
        "maximumAvailable": 1000,
        "currentlyAvailable": 990,
        "restoreRate": 50
      }
    }
  }
}

Can someone have a look at this error and explain me why is this happening? Helpful suggestions are highly appreciated.

query/mutation of giftCards not apparent

Following document for graphql mutation createGiftCard, or query giftCards (https://shopify.dev/api/examples/gift-cards).
It appears this feature is not even available ?

{"errors":[{"message":"GiftCardCreateInput isn't a defined input type (on $input)","locations":[{"line":1,"column":25}],"path":["mutation giftCardCreate"],"extensions":{"code":"variableRequiresValidType","typeName":"GiftCardCreateInput","variableName":"input"}},{"message":"Field 'giftCardCreate' doesn't exist on type 'Mutation'","locations":[{"line":2,"column":3}],"path":["mutation giftCardCreate","giftCardCreate"],"extensions":{"code":"undefinedField","typeName":"Mutation","fieldName":"giftCardCreate"}},{"message":"Variable $input is declared by giftCardCreate but not used","locations":[{"line":1,"column":1}],"path":["mutation giftCardCreate"],"extensions":{"code":"variableNotUsed","variableName":"input"}}]}

{"errors":[{"message":"Field 'giftCards' doesn't exist on type 'QueryRoot'","locations":[{"line":2,"column":3}],"path":["query","giftCards"],"extensions":{"code":"undefinedField","typeName":"QueryRoot","fieldName":"giftCards"}}]}

How will fragments work?

I can see two options.

Manual Fragments

const fragment = new Graph('Shop');
fragment.addField('name');

client.query(root => {
  root.addField('shop', shop -> {
    shop.addFragment(fragment);
  });
});

Auto Fragments
Or the other option is to just handle creating fragments under the hood. Basically if you notice two queries on Shop both querying for name then they'd use the same fragment.

Of course you could do both. But I'm not sure it makes sense to do Manual if you're doing Auto.

Thoughts @minasmart @jamesmacaulay ?

Unable to run in Microsoft Internet Explorer 11

Hey all,

I hope the title didn't scare anyone ๐Ÿ‘น... but is this package meant to be run on IE 11? I'm using a standard Babel workflow to run my universal React app on major browsers, and am now currently trying to extend support to IE 11. I'd love to know if this is on your roadmap and if I can help out. Using a polyfill script has solved most of my issues so far. However, I'm seeing the following error from this package:

TypeError: Unable to get property 'valueOf' of undefined or null reference

I've investigated and I believe the issue could be related to the implementation of isValue and isObject being too platform-dependent, but that's a guess. When I replaced your isObject with an implementation from the lodash library, the error resolved, but your tests failed.

return Object.prototype.toString.call(arg) !== '[object Null]' && Object.prototype.toString.call(arg) !== '[object Undefined]';

return Boolean(value) && Object.prototype.toString.call(value.valueOf()) === '[object Object]';

How can I build the query to create a customer using the client?

How can I build the query for creating a customer with user and password using the client? It's not in the docs. I assume it has to be something like this:

client.mutation(root => {
    root.add("customerCreate", {
      args: {
        input: { email: "[email protected]", password: "test123" }
      }
    });

But it would be nice if the docs told more about the logic of building these queries with the client.
Thanks

Test is not supported

I'm getting this error. Test mode of Shopify Payment is enabled.
The value of payment.test in checkoutCompleteWithTokenizedPaymentV2 is true. I'm using token is generated from stripe

image

ReferenceError: fetch is not defined

Hi, kinda new to this. I can include the source if it's more helpful, but I basically copied the readme.
Running into this when I run my vue app on localhost.

Nuxt.js Error:

ReferenceError: fetch is not defined
    at Client.fetcher (/Users/bcowell/Documents/GitHub/vue-store/node_modules/graphql-js-client/index.js:1709:12)
    at Client.send (/Users/bcowell/Documents/GitHub/vue-store/node_modules/graphql-js-client/index.js:1892:19)
    at module.exports.__webpack_exports__.default (middleware/shopify.js:27:10)
    at promisify (.nuxt/utils.js:117:14)
    at middlewareSeries (.nuxt/utils.js:97:9)
    at Object._callee$ (.nuxt/server.js:81:27)
    at tryCatch (/Users/bcowell/Documents/GitHub/vue-store/node_modules/regenerator-runtime/runtime.js:65:40)
    at Generator.invoke [as _invoke] (/Users/bcowell/Documents/GitHub/vue-store/node_modules/regenerator-runtime/runtime.js:303:22)
    at Generator.prototype.(anonymous function) [as next] (/Users/bcowell/Documents/GitHub/vue-store/node_modules/regenerator-runtime/runtime.js:117:21)
    at step (~/babel-runtime/helpers/asyncToGenerator.js:17:0)
    at server-bundle.js:816:13
    at <anonymous>

[ERROR] TypeError: trackTypeDependency is not a function

Hi, I was trying to make a very simple client (like the one in the example) but when running the query I get this error:

TypeError: trackTypeDependency is not a function
    at new SelectionSet (/home/lucas/Works/abc/abc-signup/backend/node_modules/graphql-js-client/index.js:644:5)
    at Query.Operation (/home/lucas/Works/abc/abc-signup/backend/node_modules/graphql-js-client/src/operation.js:63:27)
    at new Query (/home/lucas/Works/abc/abc-signup/backend/node_modules/graphql-js-client/index.js:1061:106)
    at Client.query (/home/lucas/Works/abc/abc-signup/backend/node_modules/graphql-js-client/index.js:1802:14)
    at abcIFace._callee$ (/home/lucas/Works/abc/abc-signup/backend/src/services/qiface.js:37:34)
    at tryCatch (/home/lucas/Works/abc/abc-signup/backend/node_modules/regenerator-runtime/runtime.js:64:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (/home/lucas/Works/abc/abc-signup/backend/node_modules/regenerator-runtime/runtime.js:299:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/home/lucas/Works/abc/abc-signup/backend/node_modules/regenerator-runtime/runtime.js:116:21)
    at step (/home/lucas/Works/abc/abc-signup/backend/src/services/qiface.js:28:191)
    at /home/lucas/Works/abc/abc-signup/backend/src/services/qiface.js:28:437
    at abcIFace.<anonymous> (/home/lucas/Works/abc/abc-signup/backend/src/services/qiface.js:28:99)
    at abcIFace.DataByCPF (/home/lucas/Works/abc/abc-signup/backend/src/services/qiface.js:112:21)
    at _callee$ (/home/lucas/Works/abc/abc-signup/backend/src/app.js:109:16)
    at tryCatch (/home/lucas/Works/abc/abc-signup/backend/node_modules/regenerator-runtime/runtime.js:64:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (/home/lucas/Works/abc/abc-signup/backend/node_modules/regenerator-runtime/runtime.js:299:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/home/lucas/Works/abc/abc-signup/backend/node_modules/regenerator-runtime/runtime.js:116:21)

Is that a bug or something I did wrong?

Here is my module:

/**
 * Created by Lucas Teske on 08/05/17.
 * @flow
 */

import GraphQLClient from 'graphql-js-client';
import {
  abcColors,
} from 'abc-commons';

import types from './qiface/types';
import {
  iFaceURL,
} from '../config';

abcColors();

export default class abcIFace {

  _client: any;

  constructor() {
    // $FlowFixMe
    console.log('QIFace -- Initializing GraphQL Client to abc Translation Interface'.info);
    this._client = new GraphQLClient(types, {
      url: iFaceURL,
      fetcherOptions: {
        headers: 'X-Powered-By: abc Signup',
      },
    });
  }

  async DataByCPF(cpf: string) {
    // $FlowFixMe
    console.log(`QIFace -- DataByCPF(${cpf.warn.bold})`.debug);
    try {
      const query = this._client.query((root) => {
        root.add('DataByCPF', { args: { cpf } }, (dataByCPF) => {
          dataByCPF.add('name');
          dataByCPF.add('phone');
          dataByCPF.add('addressAddress');
          dataByCPF.add('addressNumber');
          dataByCPF.add('addressComplement');
          dataByCPF.add('addressDistrict');
          dataByCPF.add('addressPostalCode');
          dataByCPF.add('addressCity');
          dataByCPF.add('addressState');
          dataByCPF.add('cpf');
          dataByCPF.add('gender');
          dataByCPF.add('mother');
          dataByCPF.add('birthdate');
        });
      });

      const objects = await this._client.send(query);
      console.log(objects);
      return objects;
    } catch (e) {
      // $FlowFixMe
      console.log(`QIFace -- DataByCPF(${cpf.warn.bold}) Error: ${e.toString().warn.bold}`.error);
      console.log(e);
      return null;
    }
  }
}

Trouble passing variables to query

Howdy everyone.

I'm attempting to pass a variable into a query, but keep running into issues and I'm not sure exactly why.

My query looks like this...

let queryVar = client.variable('currentTags', 'String!', currentTags); // currentTags = 'camping OR green'
    console.log(queryVar); // echoes out the VariableDefinition, which looks correct
    client.send(gql(client)
      `query ($currentTags: String!) {
         shop {
           products(first: 5, query: $currentTags) {
             pageInfo {
               hasNextPage
               hasPreviousPage
             }
             edges {
               node {
                 id
                 title
                 options {
                   name
                   values
                 }
                 variants(first: 25) {
                   pageInfo {
                     hasNextPage
                     hasPreviousPage
                   }
                   edges {
                     node {
                       title
                       selectedOptions {
                         name
                         value
                       }
                       image {
                         src
                       }
                       price
                     }
                   }
                 }
                 images(first: 5) {
                   pageInfo {
                     hasNextPage
                     hasPreviousPage
                   }
                   edges {
                     node {
                       src
                     }
                   }
                 }
               }
             }
           }
         }
       }
     `, [queryVar]).then((res) => {
       console.log('res is ', res);
    });

But I keep getting issues like expected Hash to be a Array if I pass the variable like [{currentTags: currentTags}] and an error like Variable currentTags of type String! was provided invalid value if I pass the variable like above.

Any suggestions?

Getting 403

I am using angular. here is the initialization of the client itself

  constructor(private userStore:UserStore) {
    this.client = new GraphQLClient(types, {
      url: "https://"+this.userStore.user.me.myShopifyDomain+"/api/2020-07/graphql.json", // also tried /api/graphql as well as /admin/api/2020-07/graphql.json
      fetcherOptions: {
        headers: {
          'X-Shopify-Storefront-Access-Token': this.userStore.user.me.shopifyAccessToken,
        }
      }
    });
  }

then below is the function sends the query using above client

getProducts(): Promise<ProductModel[]> {

    let query = this.client.query((root) => {
      root.add('shop', (shop) => {
        shop.addConnection('products', { args: { first: 10 } }, (products) => {
          products.add('id');
          products.add('title');
          products.addConnection('images', { args: { first: 10 } }, (images) => {
            images.add('src');
            images.add('id');
            images.add('altText');
          })
        })
      })
    });

here is the query that generates (copied from chrome debug window and prettified in shopify graphql app)

{
  shop {
    products(first: 10) {
      pageInfo {
        hasNextPage
        hasPreviousPage
      }
      edges {
        cursor
        node {
          id
          title
          images(first: 10) {
            pageInfo {
              hasNextPage
              hasPreviousPage
            }
            edges {
              cursor
              node {
                src
                id
                altText
              }
            }
          }
        }
      }
    }
  }
}

But I get the 403 response when using the shopify-js-client but i get data if i user the shopify graphql app.
here is the response header
image

What am I doing wrong ???

Node.JS Modules: TypeError: GraphQLJSClient is not a constructor

Hi,

I'm importing the client like this:

import GraphQLJSClient from 'graphql-js-client'


const graphQLClient = new GraphQLJSClient(types, {
    fetcher: function fetcher(graphQLParams) {
        return fetch(url, {
            body: JSON.stringify(graphQLParams),
            method: 'POST',
            mode: 'cors',
            headers
        }).then((response) => response.json());
    }
})

inside a *.mjs file. But I'm getting the exception in the subject.

node index.mjs
TypeError: GraphQLJSClient is not a constructor

Accessing available shipping rates

Hi there, i'm struggling to access the available shipping rates through the query builder. When I try to add the availableShippingRates as a connection or field it fails. Any help would be appreciated.

client.graphQLClient.query(root => {
    root.add('node', { args: { id: cartId} }, node => {
        node.addInlineFragmentOn('Checkout', checkout => {
            checkout.add('availableShippingRates')
        })
    })
})

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.