當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。