当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript graphql.printSchema函数代码示例

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


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

示例1: exportPostGraphileSchema

/**
 * Exports a PostGraphile schema by looking at a Postgres client.
 */
export default async function exportPostGraphileSchema(
  schema: GraphQLSchema,
  options: PostGraphileOptions = {},
): Promise<void> {
  const jsonPath =
    typeof options.exportJsonSchemaPath === 'string' ? options.exportJsonSchemaPath : null;
  const graphqlPath =
    typeof options.exportGqlSchemaPath === 'string' ? options.exportGqlSchemaPath : null;

  // Sort schema, if requested
  const finalSchema =
    options.sortExport && lexicographicSortSchema && (jsonPath || graphqlPath)
      ? lexicographicSortSchema(schema)
      : schema;

  // JSON version
  if (jsonPath) {
    const result = await graphql(finalSchema, introspectionQuery);
    await writeFileAsync(jsonPath, JSON.stringify(result, null, 2));
  }

  // Schema language version
  if (graphqlPath) {
    await writeFileAsync(graphqlPath, printSchema(finalSchema));
  }
}
开发者ID:calebmer,项目名称:postgraphql,代码行数:29,代码来源:exportPostGraphileSchema.ts

示例2: writeSchema

export async function writeSchema(
  path: string,
  schema: GraphQLSchema,
  schemaExtensions?: { [name: string]: string },
): Promise<void> {
  schema = valueToSchema(schema)
  let data: string
  switch (extname(path)) {
    case '.graphql':
      data = ''
      if (schemaExtensions) {
        for (const name in schemaExtensions) {
          data += `# ${name}: ${schemaExtensions[name]}\n`
        }
        data += '\n'
      }
      data += printSchema(schema)
      break
    case '.json':
      const introspection = await schemaToIntrospection(schema)
      introspection.extensions = {
        ['graphql-config']: schemaExtensions,
      }
      data = JSON.stringify(introspection, null, 2)
      break
    default:
      throw new Error(
        'Unsupported schema file extention. Only ".graphql" and ".json" are supported',
      )
  }
  writeFileSync(path, data, 'utf-8')
}
开发者ID:graphcool,项目名称:graphql-config,代码行数:32,代码来源:utils.ts

示例3: getIntrospection

  return getIntrospection().then(introspection => {
    const introspectionSchema = buildClientSchema(introspection.data);
    const introspectionIDL = printSchema(introspectionSchema);

    return [introspectionIDL, (serverSchema, extensionIDL) => {
      const extensionAST = parse(extensionIDL);
      const extensionFields = getExtensionFields(extensionAST);
      const schema = extendSchema(serverSchema, extensionAST);
      fakeSchema(schema);

      //TODO: proxy extensions
      return {
        schema,
        rootValue: (info: RequestInfo) => {
          // TODO copy headers
          const operationName = info.operationName;
          const variables = info.variables;
          const query = stripQuery(
            schema, info.document, operationName, extensionFields
          );

          return remoteServer(query, variables, operationName)
            .then(buildRootValue);
        },
      };
    }];
  });
开发者ID:codeaudit,项目名称:graphql-faker,代码行数:27,代码来源:proxy.ts

示例4: test

test('reads single schema', t => {
  const config = getGraphQLConfig(__dirname)

  const typeDefs = `\
schema {
  query: RootQueryType
}

type Bar {
  widgets: [Widget]
}

type RootQueryType {
  foo: String
  bar: Bar
}

type Widget {
  count: Int
}
`

  t.is(
    printSchema(config.getProjectConfig('testSchemaA').getSchema()),
    typeDefs,
  )
})
开发者ID:graphcool,项目名称:graphql-config,代码行数:27,代码来源:getSchema.ts

示例5: handler

export async function handler (context: Context, argv: {endpoint: string, target: string}) {
  const config = await context.getProjectConfig()
  if (!config.endpointsExtension) {
    throw noEndpointError
  }

  const endpoint = config.endpointsExtension.getEndpoint(argv.endpoint)
  const fromDesc = `${argv.endpoint} (${endpoint.url})`
  const fromSchema = await endpoint.resolveSchema()
  let toSchema
  let toDesc

  if (argv.target) {
    const target = config.endpointsExtension.getEndpoint(argv.target)
    toDesc = `${argv.target} (${target.url})`
    toSchema = await target.resolveSchema()
  } else {
    toDesc = relative(process.cwd(), config.schemaPath as string)
    toSchema = config.getSchema()
  }

  const fromSDL = printSchema(fromSchema)
  const toSDL = printSchema(toSchema)
  if (fromSDL === toSDL) {
    console.log(chalk.green('✔ No changes'))
    return
  }

  let diff = disparity.unified(fromSDL, toSDL, { paths: [fromDesc, toDesc] })
  console.log(diff)

  const dangerousChanges = findDangerousChanges(fromSchema, toSchema)
  if (dangerousChanges.length !== 0) {
    console.log(chalk.yellow('Dangerous changes:'))
    for (const change of dangerousChanges) {
      console.log(chalk.yellow('  ⚠ ' + change.description))
    }
  }

  const breakingChanges = findBreakingChanges(fromSchema, toSchema)
  if (breakingChanges.length !== 0) {
    console.log(chalk.red('BREAKING CHANGES:'))
    for (const change of breakingChanges) {
      console.log(chalk.red('  ✖ ' + change.description))
    }
  }
}
开发者ID:koddsson,项目名称:graphql-cli,代码行数:47,代码来源:diff.ts

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

示例7: test

test('reads single schema', t => {
  const typeDefs = `\
type Query {
  hello: String!
}
`

  t.is(
    printSchema(config.getProjectConfig('testSchemaA').getSchema()),
    typeDefs,
  )
})
开发者ID:graphcool,项目名称:graphql-config,代码行数:12,代码来源:getGraphQLConfig.ts

示例8: updateSingleProjectEndpoint

async function updateSingleProjectEndpoint(
  config: GraphQLProjectConfig | undefined,
  endpoint: GraphQLEndpoint,
  endpointName: string,
  argv: Arguments,
): Promise<void> {
  log(`Downloading introspection from ${chalk.blue(endpoint.url)}`)
  let newSchemaResult
  try {
    newSchemaResult = argv.json
      ? await endpoint.resolveIntrospection()
      : await endpoint.resolveSchema()

    // Do not save an invalid schema
    const clientSchema = argv.json
      ? buildClientSchema(newSchemaResult)
      : newSchemaResult
    const errors = validateSchema(clientSchema)
    if (errors.length > 0) {
      console.error(chalk.red(`${os.EOL}GraphQL endpoint generated invalid schema: ${errors}`))
      setTimeout(() => {
        process.exit(1)
      }, 500)
      return
    }
  } catch (err) {
    emitter.emit('warning', err.message)
    return
  }

  let oldSchema: string | undefined
  if (!argv.console) {
    try {
      oldSchema = argv.output
        ? fs.readFileSync(argv.output, 'utf-8')
        : config!.getSchemaSDL()
    } catch (e) {
      // ignore error if no previous schema file existed
      if (e.message === 'Unsupported schema file extention. Only ".graphql" and ".json" are supported') {
        console.error(e.message)
        setTimeout(() => {
          process.exit(1)
        }, 500)
      }
      // TODO: Add other non-blocking errors to this list
      if (e.message.toLowerCase().indexOf('syntax error') > -1) {
        console.log(`${os.EOL}Ignoring existing schema because it is invalid: ${chalk.red(e.message)}`)
      } else if (e.code !== 'ENOENT') {
        throw e
      }
    }

    if (oldSchema) {
      const newSchema = argv.json
        ? JSON.stringify(newSchemaResult, null, 2)
        : printSchema(newSchemaResult as GraphQLSchema)
      if (newSchema === oldSchema) {
        log(
          chalk.green(
            `${
              config && config.projectName && config.projectName !== 'unnamed'
                ? `project ${chalk.blue(config.projectName)} - `
                : ''
            }${
              endpointName && endpointName !== 'unnamed'
                ? `endpoint ${chalk.blue(endpointName)} - `
                : ''
            }No changes`,
          ),
        )
        emitter.emit('checked')
        return
      }
    }
  }

  let schemaPath = argv.output
  if (argv.console) {
    console.log(
      argv.json
        ? JSON.stringify(newSchemaResult, null, 2)
        : printSchema(newSchemaResult as GraphQLSchema),
    )
  } else if (argv.json) {
    if (!fs.existsSync(schemaPath)) {
      mkdirp.sync(dirname(schemaPath))
    }
    fs.writeFileSync(argv.output, JSON.stringify(newSchemaResult, null, 2))
  } else {
    schemaPath = schemaPath || config!.schemaPath
    if (!fs.existsSync(schemaPath)) {
      mkdirp.sync(dirname(schemaPath))
    }
    await writeSchema(schemaPath as string, newSchemaResult as GraphQLSchema, {
      source: endpoint.url,
      timestamp: new Date().toString(),
    })
  }

  if (schemaPath) {
//.........这里部分代码省略.........
开发者ID:koddsson,项目名称:graphql-cli,代码行数:101,代码来源:get-schema.ts

示例9: getSchemaSDL

 getSchemaSDL(): string {
   return printSchema(this.getSchema())
 }
开发者ID:graphcool,项目名称:graphql-config,代码行数:3,代码来源:GraphQLProjectConfig.ts


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