Skip to content

Instantly share code, notes, and snippets.

@RStankov
Created November 25, 2020 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RStankov/4a6339eb8fc94c197947e7e7a9e15d6c to your computer and use it in GitHub Desktop.
Save RStankov/4a6339eb8fc94c197947e7e7a9e15d6c to your computer and use it in GitHub Desktop.
import { ApolloClient } from 'apollo-boost';
import { get as lodashGet } from 'lodash';
interface INode<T> {
node: T;
}
interface IHaveNextPage {
pageInfo: {
hasNextPage: boolean;
};
}
export interface IConnectionPartial<T> {
edges: INode<T>[];
}
export interface IConnection<T> {
edges: INode<T>[];
pageInfo: {
hasNextPage: boolean;
endCursor: string | null;
};
}
export type IArrayOrConnection<T> = T[] | IConnectionPartial<T>;
export function map<T, R>(
list: IArrayOrConnection<T>,
fn: (node: T, i: number) => R,
) {
return Array.isArray(list)
? list.map(fn)
: list.edges.map(({ node }, i) => fn(node, i));
}
export function forEach<T>(
list: IArrayOrConnection<T>,
fn: (node: T, i: number) => void,
) {
return Array.isArray(list)
? list.forEach(fn)
: list.edges.forEach(({ node }, i) => fn(node, i));
}
export function toArray<T>(list: IArrayOrConnection<T>): T[] {
return map(list, (node) => node);
}
export function length(list: IArrayOrConnection<any>) {
return Array.isArray(list) ? list.length : list.edges.length;
}
export function get<T>(list: IArrayOrConnection<T>, i: number): T | null {
if (Array.isArray(list)) {
return list[i] || null;
}
return list.edges[i] ? list.edges[i].node : null;
}
export function first<T>(list: IArrayOrConnection<T>): T | null {
return get(list, 0);
}
export function isEmpty(list: IArrayOrConnection<any>) {
return length(list) === 0;
}
export function isPresent(list: IArrayOrConnection<any>) {
return length(list) > 0;
}
export function hasNextPage(connection: IHaveNextPage) {
return connection.pageInfo.hasNextPage;
}
export function polymorphicInput(
name: string,
subject: { id: string; __typename: string },
) {
return {
[`${name}Id`]: subject.id,
[`${name}Type`]: subject.__typename,
};
}
export function responseNode(response: any) {
return response?.data?.response?.node;
}
export function responseErrors(response: any) {
if (
!response ||
!response.data ||
!response.data.response ||
!response.data.response.errors ||
response.data.response.errors.length === 0
) {
return null;
}
return response.data.response.errors.reduce((acc: any, error: any) => {
acc[error.field] = error.message;
return acc;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment