Skip to content

Instantly share code, notes, and snippets.

@craicoverflow
Created March 4, 2020 08:35
Show Gist options
  • Save craicoverflow/61469b104513ea4e7a0e6fb452e38658 to your computer and use it in GitHub Desktop.
Save craicoverflow/61469b104513ea4e7a0e6fb452e38658 to your computer and use it in GitHub Desktop.
Transform GraphQL Schema
import { GraphQLSchema, GraphQLObjectType, GraphQLField, buildSchema, GraphQLScalarType, GraphQLString, printSchema, GraphQLNamedType } from 'graphql';
const schema = buildSchema(`
type User {
id: ID!
name: String
}
`)
const userType = schema.getType('User') as GraphQLObjectType;
const newField: GraphQLField<any, any> = {
name: 'test',
type: GraphQLString,
description: 'asdekfwkdfYes boi',
args: [],
extensions: []
}
const x = mutateObject(userType, newField)
const y = mutateSchema(schema, x);
console.log(printSchema(y));
export function mutateSchema(schema: GraphQLSchema, gqlType: GraphQLObjectType) {
// TODO
const config = schema.toConfig();
return new GraphQLSchema({
...config,
types: [
...config.types.filter((v: GraphQLNamedType) => v.name !== gqlType.name),
gqlType
]
})
}
export function mutateObject(schemaObject: GraphQLObjectType, field: GraphQLField<any, any>) {
const config = schemaObject.toConfig();
return new GraphQLObjectType({
...config,
fields: {
...config.fields,
[field.name]: { type: field.type, description: field.description }
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment