Skip to content

Commit

Permalink
feat: connection add context type
Browse files Browse the repository at this point in the history
  • Loading branch information
productdevbook committed Nov 4, 2023
1 parent ec1922a commit 03dcc0d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 7 deletions.
4 changes: 2 additions & 2 deletions playground/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ export const schema = createSchema({
edges: [LibraryEdge!]!
pageInfo: PageInfo!
}
type Query {
libraries(
first: Int
after: Cursor
last: Int
before: Cursor
): LibraryConnection
): LibraryConnection
}
`,
resolvers: {
Expand Down
10 changes: 6 additions & 4 deletions src/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,14 @@ export function offsetForArgs(options: ResolveOffsetConnectionOptions) {
export async function resolveOffsetConnection<
T,
U extends Promise<readonly T[] | null> | readonly T[] | null,
I,
>(
options: ResolveOffsetConnectionOptions,
resolve: (params: {
offset: number
limit: number
}) => U & (MaybePromise<readonly T[] | null> | null),
): Promise<Connection<T>> {
): Promise<Connection<T, I>> {
const { limit, offset, expectedSize, hasPreviousPage, hasNextPage } = offsetForArgs(options)

const nodes = (await resolve({ offset, limit })) as T[] | null
Expand Down Expand Up @@ -90,10 +91,10 @@ export function offsetToCursor(offset: number): string {
return Buffer.from(`${OFFSET_CURSOR_PREFIX}${offset}`).toString('base64')
}

export function resolveArrayConnection<T>(
export function resolveArrayConnection<T, I>(
options: ResolveArrayConnectionOptions,
array: readonly T[],
): Connection<T> {
): Connection<T, I> {
const { limit, offset, expectedSize, hasPreviousPage, hasNextPage } = offsetForArgs(options)

const nodes = array.slice(offset, offset + limit)
Expand Down Expand Up @@ -149,10 +150,11 @@ type NodeType<T> = T extends Promise<(infer N)[] | null> | (infer N)[] | null ?

export async function resolveCursorConnection<
U extends Promise<readonly unknown[] | null> | readonly unknown[] | null,
I,
>(
options: ResolveCursorConnectionOptions<NodeType<U>>,
resolve: (params: ResolveCursorConnectionArgs) => U,
): Promise<Connection<NodeType<U>>> {
): Promise<Connection<NodeType<U>, I>> {
const { before, after, limit, inverted, expectedSize, hasPreviousPage, hasNextPage }
= parseCurserArgs(options)

Expand Down
3 changes: 2 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ export interface ResolveArrayConnectionOptions {
/**
* A type designed to be exposed as a `Connection` over GraphQL.
*/
export interface Connection<T> {
export interface Connection<T, I> {
edges: Array<Edge<T>>
pageInfo: PageInfo
context?: I
}

/**
Expand Down

0 comments on commit 03dcc0d

Please sign in to comment.