graphql#GraphQLEnumTypeConfig TypeScript Examples

The following examples show how to use graphql#GraphQLEnumTypeConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From graphql-mesh with MIT License 4 votes vote down vote up
visit({
    nested,
    name,
    currentPath,
    rootJson,
    creds,
    grpcObject,
    rootLogger: logger,
  }: {
    nested: AnyNestedObject;
    name: string;
    currentPath: string[];
    rootJson: protobufjs.INamespace;
    creds: ChannelCredentials;
    grpcObject: ReturnType<typeof loadPackageDefinition>;
    rootLogger: Logger;
  }) {
    const pathWithName = [...currentPath, ...name.split('.')].filter(Boolean);
    if ('nested' in nested) {
      for (const key in nested.nested) {
        logger.debug(`Visiting ${currentPath}.nested[${key}]`);
        const currentNested = nested.nested[key];
        this.visit({
          nested: currentNested,
          name: key,
          currentPath: pathWithName,
          rootJson,
          creds,
          grpcObject,
          rootLogger: logger,
        });
      }
    }
    const typeName = pathWithName.join('_');
    if ('values' in nested) {
      const enumTypeConfig: GraphQLEnumTypeConfig = {
        name: typeName,
        values: {},
        description: (nested as any).comment,
      };
      const commentMap = (nested as any).comments;
      for (const [key, value] of Object.entries(nested.values)) {
        logger.debug(`Visiting ${currentPath}.nested.values[${key}]`);
        enumTypeConfig.values[key] = {
          value,
          description: commentMap?.[key],
        };
      }
      this.schemaComposer.createEnumTC(enumTypeConfig);
    } else if ('fields' in nested) {
      const inputTypeName = typeName + '_Input';
      const outputTypeName = typeName;
      const description = (nested as any).comment;
      const fieldEntries = Object.entries(nested.fields) as [string, protobufjs.IField & { comment: string }][];
      if (fieldEntries.length) {
        const inputTC = this.schemaComposer.createInputTC({
          name: inputTypeName,
          description,
          fields: {},
        });
        const outputTC = this.schemaComposer.createObjectTC({
          name: outputTypeName,
          description,
          fields: {},
        });
        for (const [fieldName, { type, rule, comment }] of fieldEntries) {
          logger.debug(`Visiting ${currentPath}.nested.fields[${fieldName}]`);
          const baseFieldTypePath = type.split('.');
          inputTC.addFields({
            [fieldName]: {
              type: () => {
                const fieldTypePath = this.walkToFindTypePath(rootJson, pathWithName, baseFieldTypePath);
                const fieldInputTypeName = getTypeName(this.schemaComposer, fieldTypePath, true);
                return rule === 'repeated' ? `[${fieldInputTypeName}]` : fieldInputTypeName;
              },
              description: comment,
            },
          });
          outputTC.addFields({
            [fieldName]: {
              type: () => {
                const fieldTypePath = this.walkToFindTypePath(rootJson, pathWithName, baseFieldTypePath);
                const fieldTypeName = getTypeName(this.schemaComposer, fieldTypePath, false);
                return rule === 'repeated' ? `[${fieldTypeName}]` : fieldTypeName;
              },
              description: comment,
            },
          });
        }
      } else {
        this.schemaComposer.createScalarTC({
          ...GraphQLJSON.toConfig(),
          name: inputTypeName,
          description,
        });
        this.schemaComposer.createScalarTC({
          ...GraphQLJSON.toConfig(),
          name: outputTypeName,
          description,
        });
      }
    } else if ('methods' in nested) {
      const objPath = pathWithName.join('.');
      const ServiceClient = lodashGet(grpcObject, objPath);
      if (typeof ServiceClient !== 'function') {
        throw new Error(`Object at path ${objPath} is not a Service constructor`);
      }
      const client = new ServiceClient(
        stringInterpolator.parse(this.config.endpoint, { env: process.env }) ?? this.config.endpoint,
        creds
      );
      for (const methodName in nested.methods) {
        const method = nested.methods[methodName];
        const rootFieldName = [...pathWithName, methodName].join('_');
        const fieldConfig: ObjectTypeComposerFieldConfigAsObjectDefinition<any, any> = {
          type: () => {
            const baseResponseTypePath = method.responseType?.split('.');
            if (baseResponseTypePath) {
              const responseTypePath = this.walkToFindTypePath(rootJson, pathWithName, baseResponseTypePath);
              return getTypeName(this.schemaComposer, responseTypePath, false);
            }
            return 'Void';
          },
          description: method.comment,
        };
        fieldConfig.args = {
          input: () => {
            if (method.requestStream) {
              return 'File';
            }
            const baseRequestTypePath = method.requestType?.split('.');
            if (baseRequestTypePath) {
              const requestTypePath = this.walkToFindTypePath(rootJson, pathWithName, baseRequestTypePath);
              const requestTypeName = getTypeName(this.schemaComposer, requestTypePath, true);
              return requestTypeName;
            }
            return undefined;
          },
        };
        if (method.responseStream) {
          this.schemaComposer.Subscription.addFields({
            [rootFieldName]: {
              ...fieldConfig,
              subscribe: (__, args: Record<string, unknown>, context: Record<string, unknown>) =>
                addMetaDataToCall(client[methodName].bind(client), args.input, context, this.config.metaData, true),
              resolve: (payload: unknown) => payload,
            },
          });
        } else {
          const methodNameLowerCased = methodName.toLowerCase();
          const rootTypeComposer = QUERY_METHOD_PREFIXES.some(prefix => methodNameLowerCased.startsWith(prefix))
            ? this.schemaComposer.Query
            : this.schemaComposer.Mutation;
          rootTypeComposer.addFields({
            [rootFieldName]: {
              ...fieldConfig,
              resolve: (_, args: Record<string, unknown>, context: Record<string, unknown>) =>
                addMetaDataToCall(client[methodName].bind(client), args.input, context, this.config.metaData),
            },
          });
        }
      }
      const connectivityStateFieldName = pathWithName.join('_') + '_connectivityState';
      this.schemaComposer.Query.addFields({
        [connectivityStateFieldName]: {
          type: 'ConnectivityState',
          args: {
            tryToConnect: {
              type: 'Boolean',
            },
          },
          resolve: (_, { tryToConnect }) => client.getChannel().getConnectivityState(tryToConnect),
        },
      });
    }
  }