由 Kira 出售

Automatically generate a fully functional GraphQL schema from any OpenAPI (Swagger 2.0 or 3.x) specification, with support for nested queries, mutations, subscriptions, and authentication.
This block converts OpenAPI 2/3 specifications into executable GraphQL schemas, complete with auto-generated resolvers that proxy HTTP requests to the underlying REST API. It is aimed at backend engineers who want to expose an existing REST API as GraphQL without hand-writing resolvers or schema definitions.
types/ - TypeScript type definitions for OAS2, OAS3, GraphQL wrappers, operation models, options, and preprocessing dataauth_builder.ts - Builds GraphQL viewer types for authentication (basic auth, API key)graphql_tools.ts - Utility helpers for working with GraphQL types and schemasindex.ts - Main entry point; exports createGraphQLSchema and related public functionsoas_3_tools.ts - Low-level utilities for parsing and navigating OpenAPI 3 specspreprocessor.ts - Converts OAS operations into internal Operation and DataDefinition structuresresolver_builder.ts - Creates GraphQL field resolver functions that execute HTTP requestsschema_builder.ts - Translates JSON Schema definitions into GraphQL (input) object typesutils.ts - Shared helpers: warning handling, string sanitization, common utilitiestypes/graphql.ts - Types for GraphQL arguments, operation types, subscription contexttypes/oas2.ts - Swagger 2.0 type definitionstypes/oas3.ts - OpenAPI 3.x type definitionstypes/operation.ts - Operation and DataDefinition interfacestypes/options.ts - Options, InternalOptions, Report, ConnectOptions, RequestOptions, FileUploadOptionstypes/preprocessing_data.ts - PreprocessingData and ProcessedSecurityScheme interfacesnpm install openapi-to-graphql graphql graphql-scalars graphql-subscriptions graphql-upload
npm install swagger2openapi oas-validator deep-equal debug json-ptr pluralize
npm install jsonpath-plus jsonpointer form-urlencoded form-data url-join cross-fetch
npm install --save-dev @types/node @types/debug typescript
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 738720c533a3002a…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
No native modules, iOS pod installs, or Android linking steps are required. This is a pure Node.js library.
Copy the source/ directory into your project, e.g. src/openapi-to-graphql/.
Update tsconfig.json to include the source in compilation and enable required options:
{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"paths": {
"openapi-to-graphql": ["./src/openapi-to-graphql/index.ts"]
}
},
"include": ["src/**/*"]
}
If you use ESM ("module": "ESNext"), ensure your bundler resolves the cross-fetch and form-data CJS modules correctly, or add them to esmExternals.
No environment variables are required by the library itself. API base URLs are read from the OAS servers field; you can override them via the baseUrl option at runtime.
For subscriptions, ensure a PubSub-compatible broker is reachable and configure the mqtt or webSocket callback options when calling createGraphQLSchema.
import { createGraphQLSchema } from './openapi-to-graphql/index'
import { Oas3 } from './openapi-to-graphql/types/oas3'
import { Options } from './openapi-to-graphql/types/options'
async function createGraphQLSchema<TSource = any, TContext = any, TArgs = any>(
spec: Oas3 | Oas2 | (Oas3 | Oas2)[],
options?: Options<TSource, TContext, TArgs>
): Promise<{ schema: GraphQLSchema; report: Report }>
The primary entry point. Pass one or more OAS/Swagger documents and receive a fully constructed GraphQLSchema plus a report summarising warnings and which operations were translated. Use this whenever you want to mount an OAS-backed GraphQL endpoint.
import { Options } from './openapi-to-graphql/types/options'
type Options<TSource, TContext, TArgs> = {
baseUrl?: string
requestOptions?: RequestOptions
connectOptions?: ConnectOptions
viewer?: boolean
headers?: { [key: string]: string }
qs?: { [key: string]: string }
customResolvers?: { [path: string]: { [method: string]: GraphQLFieldResolver<TSource, TContext, TArgs> } }
// ...and more
}
Controls every aspect of schema generation: base URL overrides, custom resolvers, authentication viewer injection, request-level headers, and query-string defaults. Pass this as the second argument to createGraphQLSchema.
import { Report } from './openapi-to-graphql/types/options'
type Report = {
warnings: string[]
numOps: number
numOpsQuery: number
numOpsMutation: number
numOpsSubscription: number
numQueriesCreated: number
numMutationsCreated: number
numSubscriptionsCreated: number
}
Returned alongside the schema from createGraphQLSchema. Inspect report.warnings to surface OAS incompatibilities at startup, and use the operation counts to verify your spec was fully consumed.
Load a JSON OpenAPI spec from disk, generate a GraphQL schema, and execute a query.
import { createGraphQLSchema } from './openapi-to-graphql/index'
import { graphql } from 'graphql'
import * as fs from 'fs'
async function main() {
const oas = JSON.parse(fs.readFileSync('./petstore.json', 'utf-8'))
const { schema, report } = await createGraphQLSchema(oas, {
baseUrl: 'https://petstore.swagger.io/v2'
})
console.log('Warnings:', report.warnings)
console.log('Queries created:', report.numQueriesCreated)
const result = await graphql({
schema,
source: '{ pets { id name } }'
})
console.log(JSON.stringify(result, null, 2))
}
main().catch(console.error)
Wrap an API that uses API-key auth and mount it behind an Express GraphQL endpoint.
import express from 'express'
import { createHandler } from 'graphql-http/lib/use/express'
import { createGraphQLSchema } from './openapi-to-graphql/index'
import fetch from 'cross-fetch'
async function startServer() {
const oas = await fetch('https://example.com/api/openapi.json').then(r => r.json())
const { schema, report } = await createGraphQLSchema(oas, {
viewer: true, // injects QueryViewer / MutationViewer auth wrappers
baseUrl: 'https://example.com/api'
})
if (report.warnings.length) {
console.warn('OAS warnings:', report.warnings)
}
const app = express()
app.use('/graphql', createHandler({ schema }))
app.listen(4000, () => console.log('GraphQL at http://localhost:4000/graphql'))
}
startServer()
Combine two separate service specs into a single unified GraphQL schema.
import { createGraphQLSchema } from './openapi-to-graphql/index'
import { Oas3 } from './openapi-to-graphql/types/oas3'
import { graphql } from 'graphql'
async function mergedSchema() {
const [usersSpec, ordersSpec]: Oas3[] = await Promise.all([
fetch('/specs/users.json').then(r => r.json()),
fetch('/specs/orders.json').then(r => r.json())
])
const { schema, report } = await createGraphQLSchema([usersSpec, ordersSpec], {
headers: { 'X-Internal-Token': process.env.INTERNAL_TOKEN ?? '' }
})
console.log(`Total operations: ${report.numOps}`)
const result = await graphql({
schema,
source: '{ user(id: "1") { name } order(id: "42") { total } }'
})
return result
}
index.ts - Exports createGraphQLSchema; orchestrates preprocessing, schema building, and auth wiring.preprocessor.ts - Iterates OAS paths/operations, resolves $ref pointers, and produces typed Operation and DataDefinition objects consumed by the builders.oas_3_tools.ts - Stateless helpers for resolving references, normalising server URLs, extracting request/response schemas, and converting Swagger 2 to OAS 3 via swagger2openapi.schema_builder.ts - Maps JSON Schema primitives and objects to GraphQLObjectType, GraphQLInputObjectType, GraphQLEnumType, GraphQLUnionType, and scalars; calls resolver_builder to attach resolvers.resolver_builder.ts - Produces GraphQLFieldResolver closures that build HTTP requests, handle auth injection, process file uploads, and manage PubSub for subscriptions.auth_builder.ts - Generates intermediate QueryViewer/MutationViewer object types that accept security credentials and forward them via the _openAPIToGraphQL object.graphql_tools.ts - Miscellaneous GraphQL utility functions used across builders.utils.ts - handleWarning, MitigationTypes, getCommonPropertyNames, and string sanitization helpers.types/ - Pure TypeScript interfaces; no runtime code. Covers OAS2, OAS3, options, operations, preprocessing data, and GraphQL-specific types.$ref resolution fails at runtime: Ensure the full OAS document (not just a fragment) is passed; oas_3_tools.ts resolves references internally against the root object.swagger2openapi conversion errors on Swagger 2 specs: Install swagger2openapi at exactly the version pinned in the upstream package.json; API surface breaks across major versions.cross-fetch or form-data: Add "esModuleInterop": true in tsconfig.json and import as import crossFetch from 'cross-fetch', not as a namespace import.title field produce colliding type names; use x-openapi-to-graphql-name extension on conflicting schemas to force unique names._openAPIToGraphQL object on each resolver result, not via GraphQL context; do not strip unknown fields from resolver return values.PubSub instance in resolver_builder.ts is module-scoped; your MQTT/WebSocket bridge must publish to the same in-process PubSub topic name, or replace the internal pubsub instance with a shared one via a custom resolver.I am integrating the openapi-to-graphql library (source in `src/openapi-to-graphql/`)
into my existing Node.js/TypeScript/Express project. The USAGE.md at the root of
this block is the authoritative reference for all real exports, file locations,
and working code examples.
Please help me do the following step-by-step:
1. Confirm that all required npm dependencies listed in USAGE.md ## Required dependencies
are present in my package.json and install any that are missing.
2. Update my tsconfig.json to match the settings in USAGE.md ## Project setup,
preserving my existing options where possible.
3. Create a new file `src/graphql/schema.ts` that imports `createGraphQLSchema`
from `src/openapi-to-graphql/index`, loads my OAS spec from `openapi.json`,
and exports the resulting `GraphQLSchema`.
4. Wire the schema into my existing Express app using `graphql-http`,
following the pattern in USAGE.md ## Working examples - Scenario Express server.
5. Log any `report.warnings` at startup so OAS incompatibilities are visible.
6. If my spec uses API-key authentication, enable the `viewer: true` option
as described in USAGE.md ## Public API - Options.
Only use symbols and imports that appear in USAGE.md. Do not invent new APIs.
The upstream package name is `openapi-to-graphql` (ibm_openapi_to_graphql).
The source is licensed under the MIT License (stated in every source file header: https://opensource.org/licenses/MIT). Copyright IBM Corp. 2018.
Upstream repository: ibm/openapi-to-graphql — package openapi-to-graphql on npm. Note that active development has moved to GraphQL Mesh's OpenAPI handler, which is a maintained fork.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费