# Swagger2GQL
**Swagger2GQL** is a robust library that converts Swagger (OpenAPI) specifications into GraphQL schemas. This library allows you to expose only the necessary operations while providing flexibility in customizing backend API calls. Additionally, it supports creating discrete filter types for each query, enabling fine-grained control over query filtering. It also allows you to specify `@key` directives for types in a federated schema, with configurable federation support.
## Features
- **Convert Swagger to GraphQL**: Automatically generate GraphQL schemas from Swagger (OpenAPI) specifications.
- **Selective Exposure**: Choose to include or exclude specific queries and mutations based on your application's needs.
- **Configurable Federation Support**: Optionally generate schemas suitable for federated GraphQL architectures by enabling federation features.
- **Flexible Type Mapping**: Automatically maps JSON schema types from Swagger to GraphQL types.
- **Discrete Filter Types**: Each query can have its own unique filter type, avoiding naming collisions and allowing for tailored filtering logic.
- **Optional Filtering**: Control whether filtering is enabled or disabled based on your application needs.
- **@key and @shareable Directive Support**: Specify the `@key` directive for types, and optionally include the `@shareable` directive when federation support is enabled.
## Installation
Install the library via npm:
```bash
npm install @maka/swagger2gql
Here’s how to use Swagger2GQL
to create a GraphQL schema from a Swagger document:
import { createSchema } from '@maka/swagger2gql';
const startServer = async () => {
const { schema } = await createSchema({
swaggerSchema: 'path/to/swagger.json', // Path to your Swagger (OpenAPI) file
// Other options...
});
// Use 'schema' in your GraphQL server setup
};
You can control which queries and mutations are exposed in your GraphQL schema using the includeQueries
, includeMutations
, excludeQueries
, and excludeMutations
options.
To hide all operations by default and only show specific ones:
import { createSchema } from '@maka/swagger2gql';
const startServer = async () => {
const { schema } = await createSchema({
swaggerSchema: 'path/to/swagger.json',
includeQueries: ['getFoo', 'getBar'], // List queries to show
includeMutations: ['createFoo'], // List mutations to show
// Other options...
});
// Use 'schema' in your GraphQL server setup
};
To show all operations by default and hide specific ones:
import { createSchema } from '@maka/swagger2gql';
const startServer = async () => {
const { schema } = await createSchema({
swaggerSchema: 'path/to/swagger.json',
excludeQueries: ['getSecretData'], // List queries to hide
excludeMutations: ['deleteFoo'], // List mutations to hide
// Other options...
});
// Use 'schema' in your GraphQL server setup
};
You can control whether filtering functionality is added to the queries by using the enableFiltering
option.
To enable filtering for each query:
import { createSchema } from '@maka/swagger2gql';
const startServer = async () => {
const { schema } = await createSchema({
swaggerSchema: 'path/to/swagger.json',
enableFiltering: true, // Enable filtering for each query
// Other options...
});
// Use 'schema' in your GraphQL server setup
};
To disable filtering and remove the filter types from the queries:
import { createSchema } from '@maka/swagger2gql';
const startServer = async () => {
const { schema } = await createSchema({
swaggerSchema: 'path/to/swagger.json',
enableFiltering: false, // Disable filtering, no filter types will be added
// Other options...
});
// Use 'schema' in your GraphQL server setup
};
If the response from your query is a simple array (e.g., an array of strings or numbers), you can omit the key
in the filter and apply the regex directly to each item in the array.
If your query looks like this:
query ExampleQuery($filter: FooFilter) {
foo(filter: $filter)
}
And the response is an array of items:
[
"apple",
"banana",
"cherry",
"date"
]
You can use the following filter without specifying a key
:
{
"filter": {
"regex": "cherry" // Matches all items that contain "cherry"
}
}
This will return:
[
"cherry"
]
When dealing with more complex responses that include nested objects and arrays of nested objects, you can use the key
to specify the path to the property you want to filter.
Suppose your query response contains a list of products, where each product has an array of reviews:
{
"products": [
{
"name": "Laptop",
"reviews": [
{
"author": "Alice",
"rating": 5
},
{
"author": "Bob",
"rating": 4
}
]
},
{
"name": "Phone",
"reviews": [
{
"author": "Charlie",
"rating": 3
},
{
"author": "Dave",
"rating": 4
}
]
}
]
}
To filter this response to only include reviews with a rating of 5:
{
"filter": {
"key": "products.$.reviews.$.rating",
"regex": "^5$" // Matches reviews with a rating of 5
}
}
This will return:
{
"products": [
{
"name": "Laptop",
"reviews": [
{
"author": "Alice",
"rating": 5
}
]
}
]
}
In this example, the key
specifies the path through the nested objects and arrays, using the $.
notation to denote elements within arrays.
When working in a federated GraphQL environment, you can specify @key
directives for types by providing a keys
object in the options. Additionally, you can enable federation support to include federation-specific directives like @shareable
.
import { createSchema } from '@maka/swagger2gql';
const startServer = async () => {
const { schema } = await createSchema({
swaggerSchema: 'path/to/swagger.json',
keys: {
User: 'id', // Define the @key directive for the User type
},
enableFederation: true, // Enable federation support
// Other options...
});
// Use 'schema' in your GraphQL server setup
};
In this example, the User
type will have a @key(fields: "id")
directive added to it, and because enableFederation
is set to true
, the @shareable
directive will also be added, allowing it to participate in a federated GraphQL setup.
If you do not require federation support, you can disable it (which is the default behavior):
import { createSchema } from '@maka/swagger2gql';
const startServer = async () => {
const { schema } = await createSchema({
swaggerSchema: 'path/to/swagger.json',
keys: {
User: 'id',
},
enableFederation: false, // Disable federation support (default)
// Other options...
});
// Use 'schema' in your GraphQL server setup
};
In this case, only the @key
directive will be added to the User
type, without any federation-specific directives.
createSchema<TContext>(options: Options<TContext>): Promise<CustomGraphQLSchema>
Parameters:
swaggerSchema
: Path to the Swagger (OpenAPI) JSON file or a JSON schema object.includeQueries
(optional): Array of query operation IDs to include in the schema. If provided, only these queries will be exposed.excludeQueries
(optional): Array of query operation IDs to exclude from the schema. If provided, all other queries will be exposed except these.includeMutations
(optional): Array of mutation operation IDs to include in the schema. If provided, only these mutations will be exposed.excludeMutations
(optional): Array of mutation operation IDs to exclude from the schema. If provided, all other mutations will be exposed except these.enableFiltering
(optional): Boolean flag to enable or disable filtering functionality.keys
(optional): An object where the keys are type names and the values are the fields to be used in the@key
directive for federation.enableFederation
(optional): Boolean flag to enable or disable federation support. Defaults tofalse
.
Returns:
CustomGraphQLSchema
: An object containing the generated GraphQL schema and resolvers.
build
: Compiles the TypeScript files.develop
: Runs the TypeScript compiler in watch mode for development.lint
: Runs ESLint to check code quality.lint:fix
: Runs ESLint and automatically fixes issues.
You can find the source code and contribute at GitHub.
This library is licensed under the ISC License. See the LICENSE file for more details.
Developed by maka@maka-cli.com.