Skip to content

Instantly share code, notes, and snippets.

@DanielCender
Created November 24, 2019 04:46
Show Gist options
  • Save DanielCender/df4f1a27ef560fcff720af5b4aab1be5 to your computer and use it in GitHub Desktop.
Save DanielCender/df4f1a27ef560fcff720af5b4aab1be5 to your computer and use it in GitHub Desktop.
A recursive function calling AppSyncClient GraphQL requests for ReactNative apps
import { Logger } from 'aws-amplify';
const logger = new Logger('fetchItemsNextToken', 'VERBOSE');
/**
* @desc Recursively fetch all items in a list query using nextToken
* @param {Object} client An AppSyncClient instantiation
* @returns {Object} { items, key } Items are results,
* key is the name of the query called.
*/
function getFullFetch(client) {
/**
*
* @param {*} query Query gql document
* @param {*} variables Query vars
* @param {array} items Returned items
* @param {String} fetchPolicy The chosen fetch-policy, from Apollo Client.
*/
const fetchItemsNextToken = async ({
query,
variables,
items = [],
fetchPolicy = 'cache-first',
}) => {
try {
const { data } = await client.query({ query, variables, fetchPolicy });
if (!data) return items;
const key = Object.keys(data).find(k => k.includes('list'));
if (!key) return items; // just in case error handling
const res = data[key]; // res = { items: [], nextToken: '' }
// To handle cases of listScopesByGroup and others that don't have Connection (...items) objects
if (res.items) items.push(...res.items);
else items.push(...res);
if (!res.nextToken) return items;
// eslint-disable-next-line no-param-reassign
variables.nextToken = res.nextToken;
return fetchItemsNextToken({ query, variables, items, fetchPolicy });
} catch (err) {
logger.error(err);
return items;
}
};
return fetchItemsNextToken;
}
export default getFullFetch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment