UNPKG

2.75 kBPlain TextView Raw
1import {
2 InputDefinitionBlock,
3 OutputDefinitionBlock,
4} from "./definitions/definitionBlocks";
5import { withNexusSymbol, NexusTypes } from "./definitions/_types";
6import { PluginBuilderLens } from "./builder";
7
8export type OutputFactoryConfig<T> = {
9 stage: "walk" | "build";
10 args: any[];
11 builder: PluginBuilderLens;
12 typeDef: OutputDefinitionBlock<any>;
13 /**
14 * The name of the type this field is being declared on
15 */
16 typeName: string;
17};
18
19export type InputFactoryConfig<T> = {
20 args: any[];
21 builder: PluginBuilderLens;
22 typeDef: InputDefinitionBlock<any>;
23 /**
24 * The name of the type this field is being declared on
25 */
26 typeName: string;
27};
28
29export interface BaseExtensionConfig<T extends string> {
30 /**
31 * The name of the "extension", the field made
32 * available on the builders
33 */
34 name: T;
35 /**
36 * The full type definition for the options, including generic
37 * signature for the type
38 */
39 typeDefinition?: string;
40}
41
42export interface DynamicOutputMethodConfig<T extends string>
43 extends BaseExtensionConfig<T> {
44 /**
45 * Invoked when the field is called
46 */
47 factory(config: OutputFactoryConfig<T>): any;
48}
49
50export interface DynamicInputMethodConfig<T extends string>
51 extends BaseExtensionConfig<T> {
52 /**
53 * Invoked when the field is called
54 */
55 factory(config: InputFactoryConfig<T>): any;
56}
57
58export class DynamicInputMethodDef<Name extends string> {
59 constructor(
60 readonly name: Name,
61 protected config: DynamicInputMethodConfig<Name>
62 ) {}
63 get value() {
64 return this.config;
65 }
66}
67withNexusSymbol(DynamicInputMethodDef, NexusTypes.DynamicInput);
68
69export class DynamicOutputMethodDef<Name extends string> {
70 constructor(
71 readonly name: Name,
72 protected config: DynamicOutputMethodConfig<Name>
73 ) {}
74 get value() {
75 return this.config;
76 }
77}
78withNexusSymbol(DynamicOutputMethodDef, NexusTypes.DynamicOutputMethod);
79
80/**
81 * Defines a new property on the object definition block
82 * for an output type, taking arbitrary input to define
83 * additional types. See the connectionPlugin:
84 *
85 * t.connectionField('posts', {
86 * nullable: true,
87 * totalCount(root, args, ctx, info) {
88 * return ctx.user.getTotalPostCount(root.id, args)
89 * },
90 * nodes(root, args, ctx, info) {
91 * return ctx.user.getPosts(root.id, args)
92 * }
93 * })
94 */
95export function dynamicOutputMethod<T extends string>(
96 config: DynamicOutputMethodConfig<T>
97) {
98 return new DynamicOutputMethodDef(config.name, config);
99}
100
101/**
102 * Same as the outputFieldExtension, but for fields that
103 * should be added on as input types.
104 */
105export function dynamicInputMethod<T extends string>(
106 config: DynamicInputMethodConfig<T>
107) {
108 return new DynamicInputMethodDef(config.name, config);
109}