Skip to content

Instantly share code, notes, and snippets.

@Piefayth
Last active December 2, 2020 06:19
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Piefayth/506d6c2dc375772121d6c6d7d349e918 to your computer and use it in GitHub Desktop.
Save Piefayth/506d6c2dc375772121d6c6d7d349e918 to your computer and use it in GitHub Desktop.
"use strict"
const express = require('express')
const graphqlHTTP = require('express-graphql')
const { parse, print, visit, parseValue, printSchema, buildSchema } = require('graphql')
const app = express()
const util = require('util')
const graphqlTools = require('graphql-tools');
const rawSchema =`
type UserDataA {
woz: String,
foo: String,
userDataC: UserDataC
}
type UserDataB {
woz: String,
bar: String
}
type CompositeUserData {
userDataA: UserDataA,
userDataB: UserDataB,
}
type UserDataC {
baz: String
}
union AorB = UserDataA | UserDataB
type Query {
compositeUserData (username: String!): CompositeUserData,
userDataA (username: String!): UserDataA,
userDataB (username: String!): UserDataB,
userDataC (username: String!, foo: String!): UserDataC
userDataD (username: String!): AorB
}
schema {
query: Query
}
`
const db = {
userone: {
userDataA: { foo: "foo" },
userDataB: { bar: "bar" },
userDataC: {
foo: "goo",
faz: "gaz"
}
},
usertwo: {
userDataA: { foo: "faz" },
userDataB: { bar: "bae" },
userDataC: {
foo: "hoo",
faz: "haz"
}
}
}
const resolvers = {
Query: {
userDataA: (something, args, ctx) => {
return Promise.resolve(db[args.username].userDataA)
.then(uda => {
uda.userDataC = { baz: db[args.username].userDataC[uda.foo] }
return uda
})
},
userDataB: (something, args, ctx) => {
return db[args.username].userDataB
},
userDataC: (something, args, ctx) => {
return { baz: db[args.username].userDataC[args.foo] }
},
userDataD: (something, args, ctx) => {
return db[args.username].userDataB
},
compositeUserData: (something, args, ctx) => {
return {
userDataA: root.userDataA(args),
userDataB: root.userDataB(args)
}
}
},
AorB: {
__resolveType(data, ctx, info) {
if (data.bar) {
return info.schema.getType('UserDataB')
}
if (data.foo) {
return info.schema.getType('UserDataA')
}
return null
}
}
}
app.use('/graphql', graphqlHTTP({
schema: graphqlTools.makeExecutableSchema({
typeDefs: rawSchema,
resolvers: resolvers
}),
graphiql: true,
}))
app.listen(4443)
console.log("Listening on 4443")
@rjkhan
Copy link

rjkhan commented Jan 23, 2020

type CompositeUserData {
        userDataA: UserDataA,
        userDataB: UserDataB,
    }

Does is not necessary to implement Union type like this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment