Skip to content

Extending an existing schema

graphql-ts provides a small library to extend an existing GraphQL schema with new query/mutation fields and types.

Installation

Terminal window
npm install @graphql-ts/extend

Usage

g.ts
import {
function extend(extension: Extension | readonly Extension[] | ((base: BaseSchemaMeta) => Extension | readonly Extension[])): (schema: GraphQLSchema) => GraphQLSchema
extend
} from "@graphql-ts/extend";
import {
const schema: GraphQLSchema
schema
} from "./existing-schema";
import {
import g
g
} from "./g";
const
const newSchema: (schema: GraphQLSchema) => GraphQLSchema
newSchema
=
function extend(extension: Extension | readonly Extension[] | ((base: BaseSchemaMeta) => Extension | readonly Extension[])): (schema: GraphQLSchema) => GraphQLSchema
extend
((
base: BaseSchemaMeta
base
) => {
const
const existingType: any
existingType
=
base: BaseSchemaMeta
base
.
enum
inputObject
interface
object
scalar
any
return
{
query: {
hello: any;
field: any;
}
query
: {
hello: any
hello
:
const g: any
g
.
const field: any
field
({
type: any
type
:
const g: any
g
.
any
String
,
resolve: () => string
resolve
: () => "world",
}),
any
users
:
const g: any
g
.
any
field
({
// `base` allows easily retrieving types from the existing schema
type: any
type
:
const g: any
g
.
any
list
(
base: BaseSchemaMeta
base
.
function object(name: string): GObjectType<unknown, unknown>
object
("User")),
function resolve(): never[]
resolve
() {
return [];
},
}),
},
};
})(
const schema: GraphQLSchema
schema
);

Limitations

extend only supports extending the query and mutation types. extend also doesn’t support schemas that use the query or mutation types in any types besides as the root query/mutation types.

Also, since there is no TypeScript type information in the existing schema, all existing types that can be used are typed generically e.g. for object types, the source type is unknown and etc.