• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript graphql.validate函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中graphql.validate函数的典型用法代码示例。如果您正苦于以下问题:TypeScript validate函数的具体用法?TypeScript validate怎么用?TypeScript validate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了validate函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: put

  public put(operationDefinition: string): void {
    const ast = parse(operationDefinition);

    function isOperationDefinition(definition): definition is OperationDefinition {
      return definition.kind === OPERATION_DEFINITION;
    }

    if (ast.definitions.length > 1) {
      throw new Error('operationDefinition must contain only one definition');
    }
    const definition = ast.definitions[0];

    if (isOperationDefinition(definition)) {
      const validationErrors = validate(this.schema, ast);
      if (validationErrors.length > 0) {
        const messages = validationErrors.map((e) => e.message);
        const e = new Error(`Validation Errors:\n${messages.join('\n')}`);
        e['originalErrors'] = validationErrors;
        throw e;
      }
      this.storedOperations.set(definition.name.value, ast);
    } else {
      throw new Error(`operationDefinition must contain an OperationDefinition: ${operationDefinition}`);
    }
  }
开发者ID:hlandao,项目名称:apollo-server,代码行数:25,代码来源:operationStore.ts


示例2: put

  public put(operation: string | DocumentNode): void {
    function isOperationDefinition(definition): definition is OperationDefinitionNode {
      return definition.kind === Kind.OPERATION_DEFINITION;
    }

    function isString(definition): definition is string {
      return typeof definition === 'string';
    }

    const ast = isString(operation) ? parse(operation as string) : operation as DocumentNode;

    const definitions = ast.definitions.filter(isOperationDefinition) as OperationDefinitionNode[];
    if (definitions.length === 0) {
      throw new Error('OperationDefinitionNode must contain at least one definition');
    }
    if (definitions.length > 1) {
      throw new Error('OperationDefinitionNode must contain only one definition');
    }

    const validationErrors = validate(this.schema, ast);
    if (validationErrors.length > 0) {
      const messages = validationErrors.map((e) => e.message);
      const err = new Error(`Validation Errors:\n${messages.join('\n')}`);
      err['originalErrors'] = validationErrors;
      throw err;
    }
    this.storedOperations.set(definitions[0].name.value, ast);
  }
开发者ID:convoyinc,项目名称:apollo-server,代码行数:28,代码来源:operationStore.ts


示例3: runQuery

function runQuery(options: QueryOptions): Promise<GraphQLResult> {
    let documentAST: Document;

    function format(errors: Array<Error>): Array<Error> {
        // TODO: fix types! shouldn't have to cast.
        // the blocker is that the typings aren't right atm:
        // GraphQLResult returns Array<GraphQLError>, but the formatError function
        // returns Array<GraphQLFormattedError>
        return errors.map(options.formatError || formatError as any) as Array<Error>;
    }

    // if query is already an AST, don't parse or validate
    if (typeof options.query === 'string') {
        try {
            // TODO: time this with log function
            documentAST = parse(options.query as string);
        } catch (syntaxError) {
            return Promise.resolve({ errors: format([syntaxError]) });
        }

        // TODO: time this with log function

        let rules = specifiedRules;
        if (options.validationRules) {
          rules = rules.concat(options.validationRules);
        }
        const validationErrors = validate(options.schema, documentAST, rules);
        if (validationErrors.length) {
            return Promise.resolve({ errors: format(validationErrors) });
        }
    } else {
        documentAST = options.query as Document;
    }

    try {
        return execute(
            options.schema,
            documentAST,
            options.rootValue,
            options.context,
            options.variables,
            options.operationName
        ).then(gqlResponse => {
            let response = {
                data: gqlResponse.data,
            };
            if (gqlResponse.errors) {
                response['errors'] = format(gqlResponse.errors);
            }
            if (options.formatResponse) {
                response = options.formatResponse(response);
            }
            return response;
        });
    } catch (executionError) {
        return Promise.resolve({ errors: format([executionError]) });
    }
}
开发者ID:nevir,项目名称:apollo-server,代码行数:58,代码来源:runQuery.ts


示例4: validate

  function validate(document: DocumentNode): ReadonlyArray<GraphQLError> {
    let rules = specifiedRules;
    if (config.validationRules) {
      rules = rules.concat(config.validationRules);
    }

    const validationDidEnd = extensionStack.validationDidStart();

    try {
      return graphql.validate(config.schema, document, rules);
    } finally {
      validationDidEnd();
    }
  }
开发者ID:apollostack,项目名称:apollo-server,代码行数:14,代码来源:requestPipeline.ts


示例5: calculateQueryHash

  const parseQuery = (
    gqlSchema: GraphQLSchema,
    queryString: string,
  ): {
    queryDocumentAst: DocumentNode;
    validationErrors: ReadonlyArray<GraphQLError>;
  } => {
    if (gqlSchema !== lastGqlSchema) {
      queryCache.reset();
      lastGqlSchema = gqlSchema;
    }

    // Only cache queries that are less than 100kB, we don't want DOS attacks
    // attempting to exhaust our memory.
    const canCache = queryCacheMaxSize > 0 && queryString.length < 100000;

    const hash = canCache ? calculateQueryHash(queryString) : null;
    const result = canCache ? queryCache.get(hash!) : null;
    if (result) {
      return result;
    } else {
      const source = new Source(queryString, 'GraphQL Http Request');
      let queryDocumentAst: DocumentNode | void;

      // Catch an errors while parsing so that we can set the `statusCode` to
      // 400. Otherwise we don’t need to parse this way.
      try {
        queryDocumentAst = parseGraphql(source);
      } catch (error) {
        error.statusCode = 400;
        throw error;
      }

      if (debugRequest.enabled) debugRequest('GraphQL query is parsed.');

      // Validate our GraphQL query using given rules.
      const validationErrors = validateGraphql(gqlSchema, queryDocumentAst, staticValidationRules);
      const cacheResult: CacheEntry = {
        queryDocumentAst,
        validationErrors,
        length: queryString.length,
      };
      if (canCache) {
        queryCache.set(hash!, cacheResult);
      }
      return cacheResult;
    }
  };
开发者ID:calebmer,项目名称:postgraphql,代码行数:48,代码来源:createPostGraphileHttpRequestHandler.ts


示例6: require

import graphqlDepthLimit = require('graphql-depth-limit');
import {
    GraphQLSchema,
    DocumentNode,
    buildSchema,
    Source,
    parse,
    validate,
    specifiedRules
} from 'graphql';

const schema: GraphQLSchema = buildSchema(`
  # graphql schema goes here...
`);
const document: DocumentNode = parse(new Source(`
  # graphql query goes here...
`, 'GraphQL request'));

validate(schema, document, [ graphqlDepthLimit(5) ]);

validate(schema, document, [ ...specifiedRules, graphqlDepthLimit(10) ]);

validate(schema, document, [ graphqlDepthLimit(
    10,
    { ignore: [ /_trusted$/, 'idontcare' ] },
    (depths: any) => {
        // do something....
    },
)]);
开发者ID:AlexGalays,项目名称:DefinitelyTyped,代码行数:29,代码来源:graphql-depth-limit-tests.ts


示例7: delegateToSchemaImplementation

async function delegateToSchemaImplementation(
  options: IDelegateToSchemaOptions,
): Promise<any> {
  const { info, args = {} } = options;
  const operation = options.operation || info.operation.operation;
  const rawDocument: DocumentNode = createDocument(
    options.fieldName,
    operation,
    info.fieldNodes,
    Object.keys(info.fragments).map(
      fragmentName => info.fragments[fragmentName],
    ),
    info.operation.variableDefinitions,
    info.operation.name,
  );

  const rawRequest: Request = {
    document: rawDocument,
    variables: info.variableValues as Record<string, any>,
  };

  let transforms = [
    ...(options.transforms || []),
    new ExpandAbstractTypes(info.schema, options.schema),
  ];

  if (info.mergeInfo && info.mergeInfo.fragments) {
    transforms.push(
      new ReplaceFieldWithFragment(options.schema, info.mergeInfo.fragments),
    );
  }

  transforms = transforms.concat([
    new AddArgumentsAsVariables(options.schema, args),
    new FilterToSchema(options.schema),
    new AddTypenameToAbstract(options.schema),
    new CheckResultAndHandleErrors(info, options.fieldName),
  ]);

  if (isEnumType(options.info.returnType)) {
    transforms = transforms.concat(
      new ConvertEnumResponse(options.info.returnType),
    );
  }

  const processedRequest = applyRequestTransforms(rawRequest, transforms);

  if (!options.skipValidation) {
    const errors = validate(options.schema, processedRequest.document);
    if (errors.length > 0) {
      throw errors;
    }
  }

  if (operation === 'query' || operation === 'mutation') {
    return applyResultTransforms(
      await execute(
        options.schema,
        processedRequest.document,
        info.rootValue,
        options.context,
        processedRequest.variables,
      ),
      transforms,
    );
  }

  if (operation === 'subscription') {
    const executionResult = (await subscribe(
      options.schema,
      processedRequest.document,
      info.rootValue,
      options.context,
      processedRequest.variables,
    )) as AsyncIterator<ExecutionResult>;

    // "subscribe" to the subscription result and map the result through the transforms
    return mapAsyncIterator<ExecutionResult, any>(executionResult, result => {
      const transformedResult = applyResultTransforms(result, transforms);
      const subscriptionKey = Object.keys(result.data)[0];

      // for some reason the returned transformedResult needs to be nested inside the root subscription field
      // does not work otherwise...
      return {
        [subscriptionKey]: transformedResult,
      };
    });
  }
}
开发者ID:apollostack,项目名称:graphql-tools,代码行数:89,代码来源:delegateToSchema.ts


示例8: doRunQuery

function doRunQuery(options: QueryOptions): Promise<GraphQLResponse> {
  let documentAST: DocumentNode;

  const logFunction =
    options.logFunction ||
    function() {
      return null;
    };
  const debugDefault =
    process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';
  const debug = options.debug !== undefined ? options.debug : debugDefault;

  logFunction({ action: LogAction.request, step: LogStep.start });

  const context = options.context || {};
  let extensions = [];
  if (options.tracing) {
    extensions.push(TracingExtension);
  }
  if (options.cacheControl === true) {
    extensions.push(CacheControlExtension);
  } else if (options.cacheControl) {
    extensions.push(new CacheControlExtension(options.cacheControl));
  }
  const extensionStack =
    extensions.length > 0 && new GraphQLExtensionStack(extensions);

  if (extensionStack) {
    context._extensionStack = extensionStack;
    enableGraphQLExtensions(options.schema);

    extensionStack.requestDidStart();
  }

  const qry =
    typeof options.query === 'string' ? options.query : print(options.query);
  logFunction({
    action: LogAction.request,
    step: LogStep.status,
    key: 'query',
    data: qry,
  });
  logFunction({
    action: LogAction.request,
    step: LogStep.status,
    key: 'variables',
    data: options.variables,
  });
  logFunction({
    action: LogAction.request,
    step: LogStep.status,
    key: 'operationName',
    data: options.operationName,
  });

  // if query is already an AST, don't parse or validate
  // XXX: This refers the operations-store flow.
  if (typeof options.query === 'string') {
    try {
      logFunction({ action: LogAction.parse, step: LogStep.start });
      documentAST = parse(options.query as string);
      logFunction({ action: LogAction.parse, step: LogStep.end });
    } catch (syntaxError) {
      logFunction({ action: LogAction.parse, step: LogStep.end });
      return Promise.resolve({
        errors: format([syntaxError], options.formatError),
      });
    }
  } else {
    documentAST = options.query as DocumentNode;
  }

  let rules = specifiedRules;
  if (options.validationRules) {
    rules = rules.concat(options.validationRules);
  }
  logFunction({ action: LogAction.validation, step: LogStep.start });
  const validationErrors = validate(options.schema, documentAST, rules);
  logFunction({ action: LogAction.validation, step: LogStep.end });
  if (validationErrors.length) {
    return Promise.resolve({
      errors: format(validationErrors, options.formatError),
    });
  }

  if (extensionStack) {
    extensionStack.executionDidStart();
  }

  try {
    logFunction({ action: LogAction.execute, step: LogStep.start });
    return Promise.resolve(
      execute(
        options.schema,
        documentAST,
        options.rootValue,
        context,
        options.variables,
        options.operationName,
        options.fieldResolver,
//.........这里部分代码省略.........
开发者ID:chentsulin,项目名称:apollo-server,代码行数:101,代码来源:runQuery.ts


示例9: doRunQuery

function doRunQuery(options: QueryOptions): Promise<GraphQLResult> {
    let documentAST: Document;

    const logFunction = options.logFunction || function(){ return null; };
    const debugDefault = process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';
    const debug = typeof options.debug !== 'undefined' ? options.debug : debugDefault;

    logFunction({action: LogAction.request, step: LogStep.start});

    function format(errors: Array<Error>): Array<Error> {
        // TODO: fix types! shouldn't have to cast.
        // the blocker is that the typings aren't right atm:
        // GraphQLResult returns Array<GraphQLError>, but the formatError function
        // returns Array<GraphQLFormattedError>
        return errors.map(options.formatError || formatError as any) as Array<Error>;
    }

    function printStackTrace(error: Error) {
      console.error(error.stack);
    }

    const qry = typeof options.query === 'string' ? options.query : print(options.query);
    logFunction({action: LogAction.request, step: LogStep.status, key: 'query', data: qry});
    logFunction({action: LogAction.request, step: LogStep.status, key: 'variables', data: options.variables});
    logFunction({action: LogAction.request, step: LogStep.status, key: 'operationName', data: options.operationName});

    // if query is already an AST, don't parse or validate
    if (typeof options.query === 'string') {
        try {
            // TODO: time this with log function
            logFunction({action: LogAction.parse, step: LogStep.start});
            documentAST = parse(options.query as string);
            logFunction({action: LogAction.parse, step: LogStep.end});
        } catch (syntaxError) {
            logFunction({action: LogAction.parse, step: LogStep.end});
            return Promise.resolve({ errors: format([syntaxError]) });
        }

        // TODO: time this with log function

        let rules = specifiedRules;
        if (options.validationRules) {
          rules = rules.concat(options.validationRules);
        }
        logFunction({action: LogAction.validation, step: LogStep.start});
        const validationErrors = validate(options.schema, documentAST, rules);
        logFunction({action: LogAction.validation, step: LogStep.end});
        if (validationErrors.length) {
            return Promise.resolve({ errors: format(validationErrors) });
        }
    } else {
        documentAST = options.query as Document;
    }

    try {
        logFunction({action: LogAction.execute, step: LogStep.start});
        return execute(
            options.schema,
            documentAST,
            options.rootValue,
            options.context,
            options.variables,
            options.operationName
        ).then(gqlResponse => {
            logFunction({action: LogAction.execute, step: LogStep.end});
            logFunction({action: LogAction.request, step: LogStep.end});
            let response = {
                data: gqlResponse.data,
            };
            if (gqlResponse.errors) {
                response['errors'] = format(gqlResponse.errors);
                if (debug) {
                  gqlResponse.errors.map(printStackTrace);
                }
            }
            if (options.formatResponse) {
                response = options.formatResponse(response, options);
            }
            return response;
        });
    } catch (executionError) {
        logFunction({action: LogAction.execute, step: LogStep.end});
        logFunction({action: LogAction.request, step: LogStep.end});
        return Promise.resolve({ errors: format([executionError]) });
    }
}
开发者ID:HriBB,项目名称:apollo-server,代码行数:86,代码来源:runQuery.ts


示例10: enhanceHttpServerWithSubscriptions


//.........这里部分代码省略.........
           * reasons (e.g. we don't want to allow overriding of Origin /
           * Referer / etc)
           */
          request.headers.authorization = String(normalizedConnectionParams['authorization']);
        }

        socket['postgraphileHeaders'] = {
          ...normalizedConnectionParams,
          // The original headers must win (for security)
          ...request.headers,
        };
      },
      // tslint:disable-next-line no-any
      async onOperation(message: any, params: ExecutionParams, socket: WebSocket) {
        const opId = message.id;
        const context = await getContext(socket, opId);

        // Override schema (for --watch)
        params.schema = await getGraphQLSchema();

        Object.assign(params.context, context);

        const { req, res } = await reqResFromSocket(socket);
        const meta = {};
        const formatResponse = (response: ExecutionResult) => {
          if (response.errors) {
            response.errors = handleErrors(response.errors, req, res);
          }
          if (!isEmpty(meta)) {
            response['meta'] = meta;
          }

          return response;
        };
        params.formatResponse = formatResponse;
        const hookedParams = options.pluginHook
          ? options.pluginHook('postgraphile:ws:onOperation', params, {
              message,
              params,
              socket,
              options,
            })
          : params;
        const finalParams: typeof hookedParams & { query: DocumentNode } = {
          ...hookedParams,
          query:
            typeof hookedParams.query !== 'string' ? hookedParams.query : parse(hookedParams.query),
        };

        // You are strongly encouraged to use
        // `postgraphile:validationRules:static` if possible - you should
        // only use this one if you need access to variables.
        const moreValidationRules = pluginHook('postgraphile:validationRules', [], {
          options,
          req,
          res,
          variables: params.variables,
          operationName: params.operationName,
          meta,
        });
        if (moreValidationRules.length) {
          const validationErrors: ReadonlyArray<GraphQLError> = validate(
            params.schema,
            finalParams.query,
            moreValidationRules,
          );
          if (validationErrors.length) {
            const error = new Error(
              'Query validation failed: \n' + validationErrors.map(e => e.message).join('\n'),
            );
            error['errors'] = validationErrors;
            return Promise.reject(error);
          }
        }

        return finalParams;
      },
      onOperationComplete(socket: WebSocket, opId: string) {
        releaseContextForSocketAndOpId(socket, opId);
      },

      /*
       * Heroku times out after 55s:
       *   https://devcenter.heroku.com/articles/error-codes#h15-idle-connection
       *
       * The subscriptions-transport-ws client times out by default 30s after last keepalive:
       *   https://github.com/apollographql/subscriptions-transport-ws/blob/52758bfba6190169a28078ecbafd2e457a2ff7a8/src/defaults.ts#L1
       *
       * GraphQL Playground times out after 20s:
       *   https://github.com/prisma/graphql-playground/blob/fa91e1b6d0488e6b5563d8b472682fe728ee0431/packages/graphql-playground-react/src/state/sessions/fetchingSagas.ts#L81
       *
       * Pick a number under these ceilings.
       */
      keepAlive: 15000,

      ...subscriptionServerOptions,
    },
    wss,
  );
}
开发者ID:calebmer,项目名称:postgraphql,代码行数:101,代码来源:subscriptions.ts



注:本文中的graphql.validate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript graphql.visit函数代码示例发布时间:2022-05-25
下一篇:
TypeScript graphql.responsePathAsArray函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap