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

TypeScript graphql.parse函数代码示例

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

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



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

示例1: it

    it('should remove empty selection sets on wrapped objects (non-nullable/lists)', async () => {
      const query = parse(`
      query bookingQuery($id: ID!) {
        bookingById(id: $id) {
          id
          propertyId
          customer {
            favoriteFood
          }
        }
      }
      `);
      const filteredQuery = filter.transformRequest({
        document: query,
        variables: {
          id: 'b1'
        }
      });

      const expected = parse(`
      query bookingQuery($id: ID!) {
        bookingById(id: $id) {
          id
          propertyId
        }
      }
      `);
      expect(print(filteredQuery.document)).to.equal(print(expected));
    });
开发者ID:apollostack,项目名称:graphql-tools,代码行数:29,代码来源:testTransforms.ts


示例2: it

    it("the documentStore calculates the DocumentNode's length by its JSON.stringify'd representation", async () => {
      expect.assertions(14);
      const {
        plugins,
        events: { parsingDidStart, validationDidStart },
      } = createLifecyclePluginMocks();

      const queryLarge = forgeLargerTestQuery(3, 'large');
      const querySmall1 = forgeLargerTestQuery(1, 'small1');
      const querySmall2 = forgeLargerTestQuery(1, 'small2');

      // We're going to create a smaller-than-default cache which will be the
      // size of the two smaller queries.  All three of these queries will never
      // fit into this cache, so we'll roll through them all.
      const maxSize =
        approximateObjectSize(parse(querySmall1)) +
        approximateObjectSize(parse(querySmall2));

      const documentStore = new InMemoryLRUCache<DocumentNode>({
        maxSize,
        sizeCalculator: approximateObjectSize,
      });

      await runRequest({ plugins, documentStore, queryString: querySmall1 });
      expect(parsingDidStart.mock.calls.length).toBe(1);
      expect(validationDidStart.mock.calls.length).toBe(1);

      await runRequest({ plugins, documentStore, queryString: querySmall2 });
      expect(parsingDidStart.mock.calls.length).toBe(2);
      expect(validationDidStart.mock.calls.length).toBe(2);

      // This query should be large enough to evict both of the previous
      // from the LRU cache since it's larger than the TOTAL limit of the cache
      // (which is capped at the length of small1 + small2) — though this will
      // still fit (barely).
      await runRequest({ plugins, documentStore, queryString: queryLarge });
      expect(parsingDidStart.mock.calls.length).toBe(3);
      expect(validationDidStart.mock.calls.length).toBe(3);

      // Make sure the large query is still cached (No incr. to parse/validate.)
      await runRequest({ plugins, documentStore, queryString: queryLarge });
      expect(parsingDidStart.mock.calls.length).toBe(3);
      expect(validationDidStart.mock.calls.length).toBe(3);

      // This small (and the other) should both trigger parse/validate since
      // the cache had to have evicted them both after accommodating the larger.
      await runRequest({ plugins, documentStore, queryString: querySmall1 });
      expect(parsingDidStart.mock.calls.length).toBe(4);
      expect(validationDidStart.mock.calls.length).toBe(4);

      await runRequest({ plugins, documentStore, queryString: querySmall2 });
      expect(parsingDidStart.mock.calls.length).toBe(5);
      expect(validationDidStart.mock.calls.length).toBe(5);

      // Finally, make sure that the large query is gone (it should be, after
      // the last two have taken its spot again.)
      await runRequest({ plugins, documentStore, queryString: queryLarge });
      expect(parsingDidStart.mock.calls.length).toBe(6);
      expect(validationDidStart.mock.calls.length).toBe(6);
    });
开发者ID:apollostack,项目名称:apollo-server,代码行数:60,代码来源:runQuery.test.ts


示例3: parseFragmentToInlineFragment

function parseFragmentToInlineFragment(
  definitions: string,
): InlineFragmentNode {
  if (definitions.trim().startsWith('fragment')) {
    const document = parse(definitions);
    for (const definition of document.definitions) {
      if (definition.kind === Kind.FRAGMENT_DEFINITION) {
        return {
          kind: Kind.INLINE_FRAGMENT,
          typeCondition: definition.typeCondition,
          selectionSet: definition.selectionSet,
        };
      }
    }
  }

  const query = parse(`{${definitions}}`)
    .definitions[0] as OperationDefinitionNode;
  for (const selection of query.selectionSet.selections) {
    if (selection.kind === Kind.INLINE_FRAGMENT) {
      return selection;
    }
  }

  throw new Error('Could not parse fragment');
}
开发者ID:apollostack,项目名称:graphql-tools,代码行数:26,代码来源:ReplaceFieldWithFragment.ts


示例4: fetchAndPrintSchema

export async function fetchAndPrintSchema(
  client: Client,
  serviceName: string,
  stageName: string,
  token?: string,
): Promise<string> {
  const introspection = await client.introspect(serviceName, stageName, token)
  const schema = buildClientSchema(introspection)

  const sdl = printSchema(schema)
  const document = parse(sdl)
  const groupedDefinitions = groupBy(document.definitions, classifyDefinition)
  let sortedDefinitions: DefinitionNode[] = []

  typesOrder.map(type => {
    const definitions = groupedDefinitions[type]
    sortedDefinitions = sortedDefinitions.concat(definitions)
  })

  let newSdl = print({
    kind: Kind.DOCUMENT,
    definitions: sortedDefinitions,
  })

  const newDocument = parse(newSdl)

  // add comments to document
  let countOffset = 0
  let charOffset = 0
  typesOrder.forEach((type, index) => {
    if (!groupedDefinitions[type]) {
      return
    }
    const definitionCount = groupedDefinitions[type].length
    const definitions = newDocument.definitions.slice(
      countOffset,
      definitionCount,
    )
    const start = definitions[0].loc!.start

    const comment = `\
${index > 0 ? '\n' : ''}#
# ${descriptions[type]}
#\n\n`

    newSdl =
      newSdl.slice(0, start + charOffset) +
      comment +
      newSdl.slice(start + charOffset)

    charOffset += comment.length
    countOffset += definitionCount
  })

  const header = `# THIS FILE HAS BEEN AUTO-GENERATED BY "PRISMA DEPLOY"
# DO NOT EDIT THIS FILE DIRECTLY\n\n`

  return header + newSdl
}
开发者ID:ahmb84,项目名称:prisma,代码行数:59,代码来源:printSchema.ts


示例5: blackBoxTest

export default function blackBoxTest(name: string) {
  const generators = new Generators()

  const modelPath = path.join(__dirname, `cases/${name}/model.graphql`)
  const prismaPath = path.join(__dirname, `cases/${name}/prisma.graphql`)

  expect(fs.existsSync(modelPath))
  expect(fs.existsSync(prismaPath))

  const model = fs.readFileSync(modelPath, { encoding: 'UTF-8' })
  const prisma = fs.readFileSync(prismaPath, { encoding: 'UTF-8' })

  const types = DatamodelParser.parseFromSchemaString(model)
  const ourSchema = generators.schema.generate(types, {})


  const ourPrintedSchema = printSchema(ourSchema)

  // Write a copy of the generated schema to the FS, for debugging
  fs.writeFileSync(
    path.join(__dirname, `cases/${name}/generated.graphql`),
    ourPrintedSchema,
    { encoding: 'UTF-8' },
  )

  // Check if our schema equals the prisma schema. 
  const prismaSchema = buildSchema(prisma)
  AstTools.assertTypesEqual(prismaSchema, ourSchema)

  // Check if we can parse the schema we build (e.g. it's syntactically valid).
  parse(ourPrintedSchema)
}
开发者ID:nunsie,项目名称:prisma,代码行数:32,代码来源:blackBoxTest.ts


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


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


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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