Mirror of https://github.com/roostorg/coop
github.com/roostorg/coop
1import { type CoopError, type CoopErrorName } from '../../utils/errors.js';
2
3/**
4 * Takes a result from our data fetching/model layer and returns an object that
5 * can be used to serialize the result to GraphQL, as a "success" constituent of
6 * a result union type.
7 *
8 * This assumes that, for a given mutation, the GQL return type will be a union
9 * type with some success cases (probably only one) and some error cases. To
10 * serialize the success data from the model layer, though, we need to "tag" it
11 * with the name of the success case's type, which the model layer shouldn't
12 * know how to do. So this function handles that.
13 *
14 * @param result The success data.
15 * @param name The name of the GraphQL type in the union that represents success.
16 */
17export function gqlSuccessResult<T extends object, U extends string>(
18 result: T,
19 name: U,
20) {
21 return {
22 __typename: name,
23 ...result,
24 };
25}
26
27/**
28 * Takes an error from our data fetching/model layer and returns an object that
29 * can be used to serialize the result to GraphQL, as an error constituent of a
30 * result union type.
31 *
32 * This assumes that, for a given mutation, the GQL return type will be a union
33 * type with some success cases (probably only one) and some error cases. To
34 * serialize the error from the model layer, though, we need to "tag" it with
35 * the name of the error's GQL type, which the model layer shouldn't know how
36 * to do, and augment it with other info that's only available at the graphql
37 * layer (like the pointer to the input data that triggered the error
38 * function handles that.
39 */
40export function gqlErrorResult<T extends CoopErrorName>(
41 error: CoopError<T>,
42 sourcePointer?: string,
43 requestId?: string,
44) {
45 return {
46 __typename: error.name,
47 ...error,
48 requestId,
49 pointer: sourcePointer ?? error.pointer,
50 };
51}