graphql#GraphQLFieldResolver TypeScript Examples

The following examples show how to use graphql#GraphQLFieldResolver. 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: schema-resolver.ts    From graphql-mesh with MIT License 6 votes vote down vote up
getFieldConfig(operation: SoapOperation): GraphQLFieldConfig<any, any> {
    const args: GraphQLFieldConfigArgumentMap = this.createSoapOperationFieldArgs(operation);
    const returnType: GraphQLOutputType = this.resolveSoapOperationReturnType(operation);
    const resolver: GraphQLFieldResolver<any, any, any> = this.createSoapOperationFieldResolver(operation);
    return {
      type: returnType,
      description: `Operation ${operation.name()}, port ${operation.port().name()}, service ${operation
        .service()
        .name()}`,
      args,
      resolve: resolver,
    };
  }
Example #2
Source File: schema-resolver.ts    From graphql-mesh with MIT License 6 votes vote down vote up
createSoapOperationFieldResolver<TSource, TContext>(
    operation: SoapOperation
  ): GraphQLFieldResolver<TSource, { [argName: string]: any }, TContext> {
    return async (
      graphqlSource: TSource,
      graphqlArgs: { [argName: string]: any },
      graphqlContext: TContext,
      graphqlInfo: GraphQLResolveInfo
    ) => {
      return this.soapCaller.call({
        operation,
        graphqlSource,
        graphqlArgs,
        graphqlContext,
        graphqlInfo,
      });
    };
  }
Example #3
Source File: addExecutionLogicToComposer.ts    From graphql-mesh with MIT License 6 votes vote down vote up
function linkResolver(
  linkObjArgs: any,
  actualResolver: GraphQLFieldResolver<any, any>,
  root: any,
  args: any,
  context: any,
  info: GraphQLResolveInfo
) {
  for (const argKey in linkObjArgs) {
    const argInterpolation = linkObjArgs[argKey];
    const actualValue = stringInterpolator.parse(argInterpolation, {
      root,
      args,
      context,
      info,
      env: process.env,
    });
    lodashSet(args, argKey, actualValue);
    lodashSet(args, `input.${argKey}`, actualValue);
  }
  return actualResolver(root, args, context, info);
}
Example #4
Source File: index.ts    From graphql-mesh with MIT License 5 votes vote down vote up
defaultHoistFieldComposer =
  (next: GraphQLFieldResolver<any, any, any>, targetFieldName: string) =>
  async (root: any, args: any, context: any, info: any) => {
    const rawResult = await next(root, args, context, info);
    return rawResult && rawResult[targetFieldName];
  }
Example #5
Source File: resolver_builder.ts    From graphql-mesh with MIT License 4 votes vote down vote up
/*
 * If operationType is Subscription, creates and returns a resolver object that
 * contains subscribe to perform subscription and resolve to execute payload
 * transformation
 */
export function getSubscribe<TSource, TContext, TArgs>({
  operation,
  payloadName,
  data,
  baseUrl,
  connectOptions,
  pubsub,
  logger,
}: GetSubscribeParams<TSource, TContext, TArgs>): GraphQLFieldResolver<TSource, SubscriptionContext, TArgs> {
  const translationLogger = logger.child('translation');
  const pubSubLogger = logger.child('pubsub');

  // Determine the appropriate URL:
  if (typeof baseUrl === 'undefined') {
    baseUrl = Oas3Tools.getBaseUrl(operation, logger);
  }

  // Return custom resolver if it is defined
  const customResolvers = data.options.customSubscriptionResolvers;
  const title = operation.oas.info?.title;
  const path = operation.path;
  const method = operation.method;

  if (
    typeof customResolvers === 'object' &&
    typeof customResolvers[title] === 'object' &&
    typeof customResolvers[title][path] === 'object' &&
    typeof customResolvers[title][path][method] === 'object' &&
    typeof customResolvers[title][path][method].subscribe === 'function'
  ) {
    translationLogger.debug(`Use custom publish resolver for ${operation.operationString}`);

    return customResolvers[title][path][method].subscribe;
  }

  return (root, args, context, info) => {
    try {
      /**
       * Determine possible topic(s) by resolving callback path
       *
       * GraphQL produces sanitized payload names, so we have to sanitize before
       * lookup here
       */
      const paramName = Oas3Tools.sanitize(payloadName, Oas3Tools.CaseStyle.camelCase);

      const resolveData: any = {};

      if (payloadName && typeof payloadName === 'string') {
        // The option genericPayloadArgName will change the payload name to "requestBody"
        const sanePayloadName = data.options.genericPayloadArgName
          ? 'requestBody'
          : Oas3Tools.sanitize(payloadName, Oas3Tools.CaseStyle.camelCase);

        if (sanePayloadName in args) {
          if (typeof args[sanePayloadName] === 'object') {
            const rawPayload = Oas3Tools.desanitizeObjectKeys(args[sanePayloadName], data.saneMap);
            resolveData.usedPayload = rawPayload;
          } else {
            const rawPayload = JSON.parse(args[sanePayloadName]);
            resolveData.usedPayload = rawPayload;
          }
        }
      }

      if (connectOptions) {
        resolveData.usedRequestOptions = connectOptions;
      } else {
        resolveData.usedRequestOptions = {
          method: resolveData.usedPayload.method ? resolveData.usedPayload.method : method.toUpperCase(),
        };
      }

      pubSubLogger.debug(`Subscription schema: `, resolveData.usedPayload);

      let value = path;
      let paramNameWithoutLocation = paramName;
      if (paramName.indexOf('.') !== -1) {
        paramNameWithoutLocation = paramName.split('.')[1];
      }

      // See if the callback path contains constants expression
      if (value.search(/{|}/) === -1) {
        args[paramNameWithoutLocation] = isRuntimeExpression(value)
          ? resolveRuntimeExpression(paramName, value, resolveData, root, args, logger)
          : value;
      } else {
        // Replace callback expression with appropriate values
        const cbParams = value.match(/{([^}]*)}/g);
        pubSubLogger.debug(`Analyzing subscription path: ${cbParams.toString()}`);

        cbParams.forEach(cbParam => {
          value = value.replace(
            cbParam,
            resolveRuntimeExpression(
              paramName,
              cbParam.substring(1, cbParam.length - 1),
              resolveData,
              root,
              args,
              logger
            )
          );
        });
        args[paramNameWithoutLocation] = value;
      }

      const topic = args[paramNameWithoutLocation] || 'test';
      pubSubLogger.debug(`Subscribing to: ${topic}`);
      return pubsub.asyncIterator(topic);
    } catch (e) {
      console.error(e);
      throw e;
    }
  };
}
Example #6
Source File: resolver_builder.ts    From graphql-mesh with MIT License 4 votes vote down vote up
/*
 * If operationType is Subscription, creates and returns a resolver function
 * triggered after a message has been published to the corresponding subscribe
 * topic(s) to execute payload transformation
 */
export function getPublishResolver<TSource, TContext, TArgs>({
  operation,
  responseName,
  data,
  logger,
}: GetResolverParams<TSource, TContext, TArgs>): GraphQLFieldResolver<TSource, TContext, TArgs> {
  const translationLogger = logger.child('translation');
  const pubSubLogger = logger.child('pubsub');

  // Return custom resolver if it is defined
  const customResolvers = data.options.customSubscriptionResolvers;
  const title = operation.oas.info?.title;
  const path = operation.path;
  const method = operation.method;

  if (
    typeof customResolvers === 'object' &&
    typeof customResolvers[title] === 'object' &&
    typeof customResolvers[title][path] === 'object' &&
    typeof customResolvers[title][path][method] === 'object' &&
    typeof customResolvers[title][path][method].resolve === 'function'
  ) {
    translationLogger.debug(`Use custom publish resolver for ${operation.operationString}`);

    return customResolvers[title][path][method].resolve;
  }

  return (payload, args, context, info) => {
    // Validate and format based on operation.responseDefinition
    const typeOfResponse = operation.responseDefinition.targetGraphQLType;
    pubSubLogger.debug(`Message received: `, responseName, typeOfResponse, payload);

    let responseBody;
    let saneData: any;

    if (typeof payload === 'object') {
      if (typeOfResponse === 'object') {
        if (Buffer.isBuffer(payload)) {
          try {
            responseBody = JSON.parse(payload.toString());
          } catch (e) {
            const errorString =
              `Cannot JSON parse payload` +
              `operation ${operation.operationString} ` +
              `even though it has content-type 'application/json'`;

            pubSubLogger.debug(errorString);
            return null;
          }
        } else {
          responseBody = payload;
        }
        saneData = Oas3Tools.sanitizeObjectKeys(payload);
      } else if ((Buffer.isBuffer(payload) || Array.isArray(payload)) && typeOfResponse === 'string') {
        saneData = payload.toString();
      }
    } else if (typeof payload === 'string') {
      if (typeOfResponse === 'object') {
        try {
          responseBody = JSON.parse(payload);
          saneData = Oas3Tools.sanitizeObjectKeys(responseBody);
        } catch (e) {
          const errorString =
            `Cannot JSON parse payload` +
            `operation ${operation.operationString} ` +
            `even though it has content-type 'application/json'`;

          pubSubLogger.debug(errorString);
          return null;
        }
      } else if (typeOfResponse === 'string') {
        saneData = payload;
      }
    }

    pubSubLogger.debug(`Message forwarded: `, saneData || payload);
    return saneData || payload;
  };
}
Example #7
Source File: index.ts    From graphql-mesh with MIT License 4 votes vote down vote up
transformSchema(schema: GraphQLSchema) {
    const configIf = this.config != null && 'if' in this.config ? this.config.if : true;
    if (configIf) {
      const mocks: IMocks = {
        ...graphqlScalarsMocks,
      };
      const resolvers: any = {};
      const typeMap = schema.getTypeMap();
      for (const typeName in typeMap) {
        const type = typeMap[typeName];
        const examples = type.extensions.examples as any[];
        if (examples?.length) {
          mocks[typeName] = () => examples[Math.floor(Math.random() * examples.length)];
        }
      }
      if (this.config?.mocks?.length) {
        for (const fieldConfig of this.config.mocks) {
          const fieldConfigIf = 'if' in fieldConfig ? fieldConfig.if : true;
          if (fieldConfigIf) {
            const [typeName, fieldName] = fieldConfig.apply.split('.');
            if (fieldName) {
              if (fieldConfig.faker) {
                let fakerFn: Function; // eslint-disable-line
                const [service, method] = fieldConfig.faker.split('.');
                if (service in faker) {
                  fakerFn = () => (faker as any)[service][method]();
                } else {
                  fakerFn = () => faker.fake(fieldConfig.faker || '');
                }
                resolvers[typeName] = resolvers[typeName] || {};
                resolvers[typeName][fieldName] = fakerFn;
              } else if (fieldConfig.custom) {
                const exportedVal$ = loadFromModuleExportExpression<any>(fieldConfig.custom, {
                  cwd: this.baseDir,
                  defaultExportName: 'default',
                  importFn: this.importFn,
                });
                resolvers[typeName] = resolvers[typeName] || {};
                resolvers[typeName][fieldName] = (root: any, args: any, context: any, info: GraphQLResolveInfo) => {
                  context = context || {};
                  context.mockStore = store;
                  return exportedVal$.then(exportedVal =>
                    typeof exportedVal === 'function' ? exportedVal(root, args, context, info) : exportedVal
                  );
                };
              } else if ('length' in fieldConfig) {
                resolvers[typeName] = resolvers[typeName] || {};
                resolvers[typeName][fieldName] = () => new Array(fieldConfig.length).fill({});
              } else if ('updateStore' in fieldConfig) {
                const getFromStoreKeyFactory = getInterpolatedStringFactory(fieldConfig.store.key);
                const updateStoreFactories = fieldConfig.updateStore.map(updateStoreConfig => ({
                  updateStoreConfig,
                  keyFactory: getInterpolatedStringFactory(updateStoreConfig.key),
                  valueFactory: getInterpolatedStringFactory(updateStoreConfig.value),
                }));
                resolvers[typeName] = resolvers[typeName] || {};
                resolvers[typeName][fieldName] = (root: any, args: any, context: any, info: GraphQLResolveInfo) => {
                  const resolverData = { root, args, context, info, random: Date.now().toString(), env: process.env };
                  updateStoreFactories.forEach(({ updateStoreConfig, keyFactory, valueFactory }) => {
                    const key = keyFactory(resolverData);
                    const value = valueFactory(resolverData);
                    store.set(updateStoreConfig.type, key, updateStoreConfig.fieldName, value);
                  });
                  const key = getFromStoreKeyFactory(resolverData);
                  return store.get(fieldConfig.store.type, key, fieldConfig.store.fieldName);
                };
              } else if ('store' in fieldConfig) {
                const keyFactory = getInterpolatedStringFactory(fieldConfig.store.key);
                resolvers[typeName] = resolvers[typeName] || {};
                resolvers[typeName][fieldName] = (root: any, args: any, context: any, info: GraphQLResolveInfo) => {
                  const key = keyFactory({ root, args, context, info, env: process.env });
                  return store.get(fieldConfig.store.type, key, fieldConfig.store.fieldName);
                };
              }
            } else {
              if (fieldConfig.faker) {
                let fakerFn: GraphQLFieldResolver<any, any, { [argName: string]: any }>;
                const [service, method] = fieldConfig.faker.split('.');
                if (service in faker) {
                  fakerFn = () => (faker as any)[service][method]();
                } else {
                  fakerFn = () => faker.fake(fieldConfig.faker || '');
                }
                mocks[typeName] = fakerFn;
              } else if (fieldConfig.custom) {
                const exportedVal$ = loadFromModuleExportExpression<any>(fieldConfig.custom, {
                  cwd: this.baseDir,
                  defaultExportName: 'default',
                  importFn: this.importFn,
                });
                mocks[typeName] = () => {
                  return exportedVal$.then(exportedVal =>
                    typeof exportedVal === 'function' ? exportedVal(store) : exportedVal
                  );
                };
              }
            }
          }
        }
      }
      const store = createMockStore({ schema, mocks });
      if (this.config?.initializeStore) {
        const initializeStoreFn$ = loadFromModuleExportExpression(this.config.initializeStore, {
          cwd: this.baseDir,
          defaultExportName: 'default',
          importFn: this.importFn,
        });
        // eslint-disable-next-line no-void
        void initializeStoreFn$.then(fn => fn(store));
      }
      return addMocksToSchema({
        schema,
        store,
        mocks,
        resolvers,
        preserveResolvers: this.config?.preserveResolvers,
      });
    }
    return schema;
  }