`<a href="https://www.useanvil.com"><img src="/static/anvil.png" width="50">
# Microfiber - A.K.A. GraphQL Introspection Tools
<a href="https://www.useanvil.com/docs"><img src="/static/microfiber.png" width="500">
A library to query and manipulate GraphQL Introspection Query results in some useful ways. What ways you ask?
How about:
- Digging through your Introspection Query Results for a specific Query, Mutation, Type, Field, Argument or Subscription.
- Removing a specific Query, Mutation, Type, Field/InputField, Argument or Subscription from your Introspection Query Results.
- Removing Queries, Mutations, Fields/InputFields or Arguments that refer to Type that does not exist in - or has been removed from - your Introspection Query Results.
Yay!
It's called microfiber
because it is heavily used to do the cleaning and manipulation in SpectaQL...it cleans the spectacles, get it?!
But, we also wanted to have a more intuitive, literal name so that people could find it. Hence it's also known as @anvilco/graphql-introspection-tools
.
Repository sponsored by Anvil
Anvil provides easy APIs for all things paperwork.
1. PDF filling API - fill out a PDF template with a web request and structured JSON data.
2. PDF generation API - send markdown or HTML and Anvil will render it to a PDF.
3. Etch e-sign with API - customizable, embeddable, e-signature platform with an API to control the signing process end-to-end.
4. Anvil Workflows (w/ API) - Webforms + PDF + e-sign with a powerful no-code builder. Easily collect structured data, generate PDFs, and request signatures.
Learn more on our Anvil developer page.
## Getting Started
1. Install microfiber
npm install microfiber
# OR
yarn add microfiber
2. Clean your GraphQL Introspection Query Results
import { Microfiber } from 'microfiber'
const introspectionQueryResults = {...}
const microfiber = new Microfiber(introspectionQueryResults)
// ...do some things to your schema with `microfiber`
const cleanedIntrospectonQueryResults = microfiber.getResponse()
// ...do something with your cleaned Introspection Query Results.
## Usage
### class Microfiber
Most of the useful stuff in this library is done through creating a new Microfiber class instance with your Introspection Query Results, and querying or manipulating it via that instance. Here are most of the interesting bits to know about class behavior.
#### constructor
const introspectionQueryResponse = {...}
// Here are the publicly supported options and their sane defaults:
const options = {
// Some GraphQL implementations have non-standard Query, Mutation and/or Subscription
// type names. This option will fix them if they're messed up in the Introspection Query
// Results
fixQueryAndMutationAndSubscriptionTypes: true,
// Remove Types that are not referenced anywhere by anything
removeUnusedTypes: true,
// Remove things whose Types are not found due to being removed
removeFieldsWithMissingTypes: true,
removeArgsWithMissingTypes: true,
removeInputFieldsWithMissingTypes: true,
removePossibleTypesOfMissingTypes: true,
// Remove all the types and things that are unreferenced immediately?
cleanupSchemaImmediately: true,
}
const microfiber = new Microfiber(introspectionQueryResponse, options)
#### cleanSchema
Clean up the schema by removing:
- Fields or Input Fields whose Type does not exist in the schema.
- Args whose Type does not exist in the schema.
- Possible Types in a Union that do not exist in the schema.
- Queries or Mutations whose return Type does not exist in the schema.
This method is usually called after altering the schema in any way so as to not leave any dangling/orphaned things around the schema.
microfiber.cleanSchema()
#### getResponse
Get out the Introspection Query Result that you have manipulated with Microfiber as an Object.
const cleanedResponse = microfiber.getResponse()
#### getAllTypes
Get all the Types from your schema as an Array of Objects. Supported options and their sane defaults are shown.
const allTypes = microfiber.getAllTypes({
// Include reserved GraphQL types?
includeReserved: false,
// Include the Query type?
includeQuery: false,
// Include the Mutation type?
includeMutation: false,
// Include the Subscription type?
includeSubscription: false,
} = {})
#### getType
Get a specific Type from yoyur schema. Supported params and their sane defaults are shown.
const type = microfiber.getType({ kind: 'OBJECT', name })
#### getQueryType
Get the Query Type from your schema.
const queryType = microfiber.getQueryType()
#### getQuery
Get a specific Query from your schema.
const query = microfiber.getQuery({ name })
#### getMutationType
Get the Mutation Type from your schema.
const mutationType = microfiber.getMutationType()
#### getMutation
Get a specific Mutation from your schema.
const mutation = microfiber.getMutation({ name })
#### getSubscriptionType
Get the Subscription Type from your schema.
const subscriptionType = microfiber.getSubscription()
#### getSubscription
Get a specific Subscription from your schema.
const subscription = microfiber.getSubscription({ name })
#### getField
Get a specific Field from your schema. Supported params and their sane defaults are shown.
const field = microfiber.getField({ typeKind: 'OBJECT', typeName, fieldName })
#### getInputField
Get a specific InputField from your schema.
const inputField = microfiber.getInputField({ typeName, fieldName })
#### getArg
Get a specific Arg from your schema. Supported params and their sane defaults are shown.
const arg = microfiber.getArg({ typeKind: 'OBJECT', typeName, fieldName, argName })
#### removeType
Remove a Type from your schema, and optionally the references to that Type elsewhere in your schema. Supported params and their sane defaults are shown.
microfiber.removeType({
kind: 'OBJECT',
name,
// Clean up the schema afterwards?
cleanup: true,
// Remove occurances of this Type from other places?
removeFieldsOfType: constructorOptions.removeFieldsWithMissingTypes,
removeInputFieldsOfType: constructorOptions.removeInputFieldsWithMissingTypes,
removePossibleTypesOfType: constructorOptions.removePossibleTypesOfMissingTypes,
removeArgsOfType: constructorOptions.removeArgsWithMissingTypes,
})
#### removeField
Remove a specific Field from a specific Type in your schema. Supported params and their sane defaults are shown.
microfiber.removeField({
typeKind: 'OBJECT',
typeName,
fieldName,
// Clean up the schema afterwards?
cleanup: true,
})
#### removeInputField
Remove a specific Input Field from a specific Input Object in your schema. Supported params and their sane defaults are shown.
microfiber.removeInputField({
typeName,
fieldName,
// Clean up the schema afterwards?
cleanup: true,
})
#### removeArg
Remove a specific Arg from a specific Field or Input Field in your schema. Supported params and their sane defaults are shown.
microfiber.removeArg({
typeKind,
typeName,
fieldName,
argName,
// Clean up the schema afterwards?
cleanup: true,
})
#### removeEnumValue
Remove a specifc Enum value from an Enum Type in your schema. Supported params are shown.
microfiber.removeEnumValue({
// The name of the Enum Type
name,
// The Enum value you want to remove
value,
})
#### removePossibleType
Remove a Possible Type from a specific Union Type in your schema. Supported params and sane defaults are shown.
microfiber.removePossibleType({
// The name of the Union Type
typeName,
// The Kind of the possible Type you want to remove
possibleTypeKind,
// The name of the possible Type you want to remove
possibleTypeName,
// Clean up the schema afterwards?
cleanup: true,
})
#### removeQuery
Remove a specific Query from your schema. Supported params and their sane defaults are shown.
microfiber.removeQuery({
name,
// Clean up the schema afterwards?
cleanup: true,
})
#### removeMutation
Remove a specific Mutation from your schema. Supported params and their sane defaults are shown.
microfiber.removeMutation({
name,
// Clean up the schema afterwards?
cleanup: true,
})
#### removeSubscription
Remove a specific Subscription from your schema. Supported params and their sane defaults are shown.
microfiber.removeSubscription({
name,
// Clean up the schema afterwards?
cleanup: true,
})
### Other exports from this library
There are some other exports from this library, not just the Microfiber
class.
#### KINDS
An Object containing all the GraphQL Kind values you may encounter.
import { KINDS } from 'microfiber'
console.log(KINDS)
// {
// SCALAR: 'SCALAR',
// OBJECT: 'OBJECT',
// INTERFACE: 'INTERFACE',
// UNION: 'UNION',
// ENUM: 'ENUM',
// INPUT_OBJECT: 'INPUT_OBJECT',
// LIST: 'LIST',
// NON_NULL: 'NON_NULL'
// }
#### typesAreSame
A function that compares 2 types and determines if they have the same Kind and Name.
import { typesAreSame } from 'microfiber'
const typeA = { kind: 'OBJECT', name: 'Foo' }
const typeB = { kind: 'OBJECT', name: 'Bar' }
typesAreSame(typeA, typeB) // false
typesAreSame(typeA, typeA) // true
#### digUnderlyingType
A function that digs through any Non-Null and List nesting and returns the underlying Type.
import { digUnderlyingType } from 'microfiber'
const nonNullableString = {
name: null,
kind: 'NON_NULL',
ofType: {
name: null,
kind: 'LIST',
ofType: {
name: 'String',
kind: 'SCALAR',
}
}
}
digUnderlyingType(nonNullableString) // { name: 'String', kind: 'SCALAR' }
#### isReservedType
A function that returns a Boolean indicating whether a Type is special GraphQL reserved Type.
import { isReservedType } from 'microfiber'
const myType = { name: 'Foo', ... }
const reservedType = { name: '__Foo', ... }
isReservedType(myType) // false
isReservedType(reservedType) // true
nate
## What is gqlgen?
gqlgen is a Go library for building GraphQL servers without any fuss.
- gqlgen is based on a Schema first approach — You get to Define your API using the GraphQL Schema Definition Language.
- gqlgen prioritizes Type safety — You should never see map[string]interface{}
here.
- gqlgen enables Codegen — We generate the boring bits, so you can focus on building your app quickly.
Still not convinced enough to use gqlgen? Compare gqlgen with other Go graphql implementations
## Quick start
1. Initialise a new go module
mkdir example
cd example
go mod init example
2. Add github.com/99designs/gqlgen
to your project's tools.go
printf '// +build tools\npackage tools\nimport _ "github.com/99designs/gqlgen"' | gofmt > tools.go
go mod tidy
3. Initialise gqlgen config and generate models
go run github.com/99designs/gqlgen init
4. Start the graphql server
go run server.go
More help to get started:
- Getting started tutorial - a comprehensive guide to help you get started
- Real-world examples show how to create GraphQL applications
- Reference docs for the APIs
## Reporting Issues
If you think you've found a bug, or something isn't behaving the way you think it should, please raise an issue on GitHub.
## Contributing
We welcome contributions, Read our Contribution Guidelines to learn more about contributing to gqlgen
## Frequently asked questions
### How do I prevent fetching child objects that might not be used?
When you have nested or recursive schema like this:
type User {
id: ID!
name: String!
friends: [User!]!
}
You need to tell gqlgen that it should only fetch friends if the user requested it. There are two ways to do this;
- #### Using Custom Models
Write a custom model that omits the friends field:
type User struct {
ID int
Name string
}
And reference the model in gqlgen.yml
:
# gqlgen.yml
models:
User:
model: github.com/you/pkg/model.User # go import path to the User struct above
- #### Using Explicit Resolvers
If you want to Keep using the generated model, mark the field as requiring a resolver explicitly in gqlgen.yml
like this:
# gqlgen.yml
models:
User:
fields:
friends:
resolver: true # force a resolver to be generated
After doing either of the above and running generate we will need to provide a resolver for friends:
func (r *userResolver) Friends(ctx context.Context, obj *User) ([]*User, error) {
// select * from user where friendid = obj.ID
return friends, nil
}
You can also use inline config with directives to achieve the same result
directive @goModel(model: String, models: [String!]) on OBJECT
| INPUT_OBJECT
| SCALAR
| ENUM
| INTERFACE
| UNION
directive @goField(forceResolver: Boolean, name: String) on INPUT_FIELD_DEFINITION
| FIELD_DEFINITION
type User @goModel(model: "github.com/you/pkg/model.User") {
id: ID! @goField(name: "todoId")
friends: [User!]! @goField(forceResolver: true)
}
### Can I change the type of the ID from type String to Type Int?
Yes! You can by remapping it in config as seen below:
models:
ID: # The GraphQL type ID is backed by
model:
- github.com/99designs/gqlgen/graphql.IntID # a go integer
- github.com/99designs/gqlgen/graphql.ID # or a go string
This means gqlgen will be able to automatically bind to strings or ints for models you have written yourself, but the
first model in this list is used as the default type and it will always be used when:
- Generating models based on schema
- As arguments in resolvers
There isn't any way around this, gqlgen has no way to know what you want in a given context.
## Other Resources
- Christopher Biscardi @ Gophercon UK 2018
- Introducing gqlgen: a GraphQL Server Generator for Go
- Dive into GraphQL by Iván Corrales Solera
- Sample Project built on gqlgen with Postgres by Oleg Shalygin