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

TypeScript graphql.execute函数代码示例

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

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



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

示例1: function

export const jsSchemaLoader: SchemaLoader = async function (options: TJsSchemaLoaderOptions) {

    const schemaPath = resolve(options.schemaFile);
    let schemaModule = require(schemaPath);
    let schema: string;

    // check if exist default in module
    if (typeof schemaModule === 'object') {
        schemaModule = schemaModule.default
    }

    // check for array of definition
    if (Array.isArray(schemaModule)){
        schema = schemaModule.join('');

    // check for array array wrapped in a function
    } else if  (typeof schemaModule === 'function')  {
        schema = schemaModule().join('');

    } else {
        throw new Error(`Unexpected schema definition on "${schemaModule}", must be an array or function`)
    }

    const introspection = await execute(
        buildSchema(schema),
        parse(introspectionQuery)
    ) as Introspection;

    return introspection.data.__schema;
};
开发者ID:2fd,项目名称:graphdoc,代码行数:30,代码来源:js.ts


示例2: execute

  async function execute(
    document: DocumentNode,
    operationName: GraphQLRequest['operationName'],
    variables: GraphQLRequest['variables'],
  ): Promise<ExecutionResult> {
    const executionArgs: ExecutionArgs = {
      schema: config.schema,
      document,
      rootValue:
        typeof config.rootValue === 'function'
          ? config.rootValue(document)
          : config.rootValue,
      contextValue: requestContext.context,
      variableValues: variables,
      operationName,
      fieldResolver: config.fieldResolver,
    };

    const executionDidEnd = extensionStack.executionDidStart({
      executionArgs,
    });

    try {
      return await graphql.execute(executionArgs);
    } finally {
      executionDidEnd();
    }
  }
开发者ID:apollostack,项目名称:apollo-server,代码行数:28,代码来源:requestPipeline.ts


示例3: execute

 return new Observable<FetchResult>(observer => {
   Promise.resolve(
     execute(
       this.schema,
       operation.query,
       this.rootValue,
       typeof this.context === 'function'
         ? this.context(operation)
         : this.context,
       operation.variables,
       operation.operationName,
     ),
   )
     .then(data => {
       if (!observer.closed) {
         observer.next(data);
         observer.complete();
       }
     })
     .catch(error => {
       if (!observer.closed) {
         observer.error(error);
       }
     });
 });
开发者ID:SET001,项目名称:apollo-link,代码行数:25,代码来源:schemaLink.ts


示例4: 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


示例5: function

export const idlSchemaLoader: SchemaLoader = async function (options: TIDLSchemaLoaderOptions) {

    const schemaPath = resolve(options.schemaFile);
    const idl = await readFile(schemaPath, 'utf8');
    const introspection = await execute(
        buildSchema(idl),
        parse(introspectionQuery)
    ) as Introspection;

    return introspection.data.__schema;
};
开发者ID:2fd,项目名称:graphdoc,代码行数:11,代码来源:idl.ts


示例6: executeGraphql

 (graphqlContext: any) => {
   pgRole = graphqlContext.pgRole;
   return executeGraphql(
     gqlSchema,
     queryDocumentAst!,
     null,
     graphqlContext,
     params.variables,
     params.operationName,
   );
 },
开发者ID:calebmer,项目名称:postgraphql,代码行数:11,代码来源:createPostGraphileHttpRequestHandler.ts


示例7: async

  const render = async (key: I.Key, mri: number): Promise<{outKey: string, result?: any}> => {
    const {type, _doc, reduce, getOutputKey} = opts.mapReduces[mri]
    const docsRead = new Set<I.Key>()
    const txn: TxnLike<any> = {
      get(key) {
        docsRead.add(key)
        return allDocs.get(key)
      }
    }
    const value = txn.get(key)
    console.log('render', key, value)
    if (value == null) {
      return {outKey: keyFor[mri].get(key)!, result: undefined}
    }
    
    const res = await gql.execute(opts.schema, _doc!, null, {txn, [type]: value})
    docsRead.delete(key) // This is implied.

    console.log('res data', res.data)
    const mapped = reduce(res.data)
    const outKey = getOutputKey(key, res.data)
    // const outKey = outPrefix + key

    // Remove old deps
    const oldDeps = deps[mri].get(key)
    console.log('oldDeps', deps[mri])
    console.log('usedBy', usedBy)
    if (oldDeps) for (const k of oldDeps) {
      usedBy.get(k)!.delete(mri, key)
    }

    docsRead.forEach(k => {
      // if (k === key) return // This is implied.
      let s = usedBy.get(k)
      if (s == null) {
        s = new Set2()
        usedBy.set(k, s)
      }
      s.add(mri, key)
    })

    deps[mri].set(key, docsRead)
    keyFor[mri].set(key, outKey)
    console.log('kv', key, docsRead, mapped)
    return {outKey, result: mapped}
  }
开发者ID:josephg,项目名称:statecraft,代码行数:46,代码来源:graphqlmapreduce.ts


示例8: async

 const mapSourceToResponse = async (payload: any) => {
   /*
    * GRAPHILE FORK
    *
    * We need to tell Graphile Engine when the execution has completed
    * (because we cannot detect this from inside the GraphQL execution) so
    * that it can clean up old listeners; we do this with the `finally` block.
    */
   try {
     return await execute(
       schema,
       document,
       payload,
       contextValue,
       variableValues,
       operationName,
       fieldResolver,
     );
   } finally {
     if (payload && typeof payload.release === 'function') {
       payload.release();
     }
   }
 };
开发者ID:calebmer,项目名称:postgraphql,代码行数:24,代码来源:liveSubscribe.ts


示例9: delegateToSchema

async function delegateToSchema(
  schema: GraphQLSchema,
  fragmentReplacements: {
    [typeName: string]: { [fieldName: string]: InlineFragmentNode };
  },
  operation: 'query' | 'mutation',
  fieldName: string,
  args: { [key: string]: any },
  context: { [key: string]: any },
  info: GraphQLResolveInfo,
): Promise<any> {
  let type;
  if (operation === 'mutation') {
    type = schema.getMutationType();
  } else {
    type = schema.getQueryType();
  }
  if (type) {
    const graphqlDoc: DocumentNode = createDocument(
      schema,
      fragmentReplacements,
      type,
      fieldName,
      operation,
      info.fieldNodes,
      info.fragments,
      info.operation.variableDefinitions,
    );

    const operationDefinition = graphqlDoc.definitions.find(
      ({ kind }) => kind === Kind.OPERATION_DEFINITION,
    );
    let variableValues = {};
    if (
      operationDefinition &&
      operationDefinition.kind === Kind.OPERATION_DEFINITION &&
      operationDefinition.variableDefinitions
    ) {
      operationDefinition.variableDefinitions.forEach(definition => {
        const key = definition.variable.name.value;
        // (XXX) This is kinda hacky
        let actualKey = key;
        if (actualKey.startsWith('_')) {
          actualKey = actualKey.slice(1);
        }
        const value = args[actualKey] || args[key] || info.variableValues[key];
        variableValues[key] = value;
      });
    }

    const result = await execute(
      schema,
      graphqlDoc,
      info.rootValue,
      context,
      variableValues,
    );

    return checkResultAndHandleErrors(result, info, fieldName);
  }

  throw new Error('Could not forward to merged schema');
}
开发者ID:sventschui,项目名称:graphql-tools,代码行数:63,代码来源:mergeSchemas.ts


示例10: 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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
TypeScript graphql.formatError函数代码示例发布时间:2022-05-25
下一篇:
TypeScript graphql.buildSchema函数代码示例发布时间: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