Last active
September 22, 2018 18:56
-
-
Save atticoos/f3826742e4f44594bc872c86ffddb97a to your computer and use it in GitHub Desktop.
Experimenting with GraphQL for https://docs.robinpowered.com/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const spaceSchema = makeExecutableSchema({ | |
typeDefs: ` | |
type Space { | |
id: Int! | |
name: String | |
location_id: Int! | |
} | |
type Query { | |
spaceById(id: Int!): Space | |
spacesByLocation(locationId: Int!, limit: Int): [Space] | |
} | |
` | |
}) | |
const locationSchema = makeExecutableSchema({ | |
typeDefs: ` | |
type Location { | |
id: Int! | |
name: String | |
address: String | |
} | |
type Query { | |
locationById(id: Int!): Location | |
} | |
` | |
}) | |
const linkTypeDefs = ` | |
extend type Location { | |
spaces(limit: Int): [Space] | |
} | |
extend type Space { | |
location: Location | |
} | |
`; | |
const schema = mergeSchemas({ | |
schemas: [ | |
spaceSchema, | |
locationSchema, | |
linkTypeDefs | |
], | |
resolvers: { | |
Query: { | |
locationById (_, {id}, {http}) { | |
console.log('locationById', id) | |
return http.get(`locations/${id}`).then(({data}) => data.data); | |
}, | |
spaceById (_, {id}, {http}) { | |
console.log('spaceById', id) | |
return http.get(`spaces/${id}`).then(({data}) => data.data).then(space => { | |
delete space.location | |
return space | |
}) | |
}, | |
spacesByLocation(_, {location_id, limit = 10}, {http}) { | |
console.log('spacesByLocation', location_id) | |
return http.get(`locations/${location_id}/spaces?per_page=${args.limit}`).then(({data}) => data.data) | |
} | |
}, | |
Location: { | |
spaces: { | |
fragment: '... on Location { id }', | |
resolve(location, args, context, info) { | |
console.log(`delegating spacesByLocation(locationId: ${location.id})`) | |
// At least this would work.. | |
// return context.http.get(`locations/${location.id}/spaces?per_page=${args.limit}`).then(({data}) => data.data) | |
// But pls, delegate instead! :( | |
return info.mergeInfo.delegateToSchema({ | |
schema: spaceSchema, | |
operation: 'query', | |
fieldName: 'spacesByLocation', | |
args: { | |
limit: args.limit, | |
locationId: location.id | |
}, | |
context, | |
info | |
}) | |
} | |
} | |
}, | |
Space: { | |
location: { | |
fragment: '... on Space { location_id }', | |
resolve(space, args, context, info) { | |
// :( pls run | |
return info.mergeInfo.delegateToSchema({ | |
schema: locationSchema, | |
operation: 'query', | |
fieldName: 'locationById', | |
args: { | |
id: space.location_id | |
}, | |
context, | |
info | |
}) | |
} | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment