Skip to content

Instantly share code, notes, and snippets.

@mattfysh
Created December 17, 2022 04:19
Show Gist options
  • Save mattfysh/2b7c8cbb9642283bc55161b64e81ea8f to your computer and use it in GitHub Desktop.
Save mattfysh/2b7c8cbb9642283bc55161b64e81ea8f to your computer and use it in GitHub Desktop.
Stitch
const { makeExecutableSchema } = require('@graphql-tools/schema')
const { stitchSchemas } = require('@graphql-tools/stitch')
const { RenameObjectFields, FilterRootFields, PruneSchema, wrapSchema } = require('@graphql-tools/wrap')
const { printSchema, parse, execute, print } = require('graphql')
/// SERVICE 1
const source = /* GraphQL */ `
type Query {
foo(key: String!): Foo
}
type Foo {
key: String
name: String
}
`
const inner = makeExecutableSchema({
typeDefs: source,
resolvers: {
Query: {
foo: (_, args) => ({ key: args.key, name: 'dsfjkasd' })
}
}
})
const config = {
schema: inner,
transforms: [
new FilterRootFields(() => false),
new PruneSchema({
skipPruning: type => type.name === 'Foo',
}),
new RenameObjectFields((typeName, fieldName) => {
if (typeName === 'Foo' && fieldName === 'key') {
return '_my_1_key'
}
return fieldName
})
],
merge: {
Foo: {
fieldName: 'foo',
selectionSet: '{ _mapped__s1_key }',
args: (source) => ({ key: source._mapped__s1_key })
}
},
executor: ({ document, variables }) => {
console.log('\n\n:: executing service one\n')
console.log(print(document))
console.log(variables)
return execute({ schema: inner, document, variableValues: variables })
}
}
/// KEY SERVICE
const keySource = /* GraphQL */ `
type Query {
foo(id: ID!): Foo
}
type Foo {
id: ID!
_mapped__s1_key: String
}
`
const keySchema = makeExecutableSchema({
typeDefs: keySource,
resolvers: {
Query: {
foo: (_, args) => ({
id: args.id,
_mapped__s1_key: 'abc',
})
}
}
})
const keyConfig = {
schema: keySchema,
merge: {
Foo: {
entryPoints: []
}
},
executor: ({ document, variables }) => {
console.log('\n\n:: executing key service')
console.log(print(document))
console.log(variables)
return execute({ schema: keySchema, document, variableValues: variables })
}
}
/// STITCH
const outer = stitchSchemas({
subschemas: [config, keyConfig]
})
console.log(printSchema(wrapSchema(config)))
// console.log(printSchema(outer))
const query = /* GraphQL */ `
query {
foo(id:"120") {
id
_mapped__s1_key
_my_1_key
name
}
}
`
const go = async () => {
const result = await execute({
schema: outer,
document: parse(query),
})
console.log('\n\n:: result\n')
console.log(JSON.stringify(result, null, 2))
}
go()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment