This repository has been archived by the owner on Dec 22, 2018. It is now read-only.
/
lib.js
65 lines (55 loc) · 1.6 KB
/
lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { GraphQLClient } from 'graphql-request'
import prettyjson from 'prettyjson'
import { get, last } from 'lodash/fp'
/**
* Create a Shopify Storefront GraphQL client for the provided name and token.
*/
export const createClient = (shopName, accessToken) =>
new GraphQLClient(`https://${shopName}.myshopify.com/api/graphql`, {
headers: {
'X-Shopify-Storefront-Access-Token': accessToken,
},
})
/**
* Print an error from a GraphQL client
*/
export const printGraphQLError = e => {
const prettyjsonOptions = { keysColor: 'red', dashColor: 'red' }
if (e.response && e.response.errors)
console.error(prettyjson.render(e.response.errors, prettyjsonOptions))
if (e.request) console.error(prettyjson.render(e.request, prettyjsonOptions))
}
/**
* Request a query from a client.
*/
export const queryOnce = async (client, query, first = 250, after) =>
await client.request(query, { first, after })
/**
* Get all paginated data from a query. Will execute multiple requests as
* needed.
*/
export const queryAll = async (
client,
path,
query,
first = 250,
after,
aggregatedResponse,
) => {
const data = await queryOnce(client, query, first, after)
const edges = get([...path, 'edges'], data)
const nodes = edges.map(edge => edge.node)
aggregatedResponse
? (aggregatedResponse = aggregatedResponse.concat(nodes))
: (aggregatedResponse = nodes)
if (get([...path, 'pageInfo', 'hasNextPage'], false, data))
return queryAll(
client,
path,
query,
first,
last(edges).cursor,
aggregatedResponse,
)
return aggregatedResponse
}