aboutsummaryrefslogtreecommitdiff
path: root/source/common.ts
blob: 902bdd06f5a9d3187e2eb1670d6fe5de23cf8a27 (plain) (blame)
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
/*** IMPORT ------------------------------------------- ***/

import { graphql, type ExecutionResult } from "graphql";

/*** UTILITY ------------------------------------------ ***/

import type {
  GQLOptions,
  GQLRequest,
  GraphQLParams
} from "./utility/types.ts";

/*** EXPORT ------------------------------------------- ***/

/**
 * Executes a GraphQL query or mutation against the provided schema.
 *
 * Resolves `options.context` (if given) with the incoming request, then
 * forwards `query`/`mutation`, `operationName`, and `variables` to `graphql()`.
 *
 * @typeParam Req - Request shape; defaults to {@link GQLRequest}.
 * @typeParam Ctx - Context value passed to resolvers; defaults to `{ request }`.
 * @param params - Parsed GraphQL params (query or mutation, with optional vars).
 * @param options - Executable schema plus optional context builder.
 * @param request - The inbound HTTP request (used to build context).
 * @returns The raw {@link ExecutionResult} from `graphql-js`.
 */
export async function runHttpQuery<
  Req extends GQLRequest = GQLRequest,
  Ctx = { request: Req }>(
    params: GraphQLParams,
    options: GQLOptions<Ctx, Req>,
    request: Req): Promise<ExecutionResult> {
  const contextValue = options.context ?
    await options.context(request) :
    { request } as Ctx;
  const source = params.query! || params.mutation!;

  return await graphql({
    source,
    ...options,
    contextValue,
    operationName: params.operationName,
    variableValues: params.variables
  });
}