Last active
May 14, 2018 21:43
-
-
Save jaroslav-kubicek/a0451d07bd51e820f3fffeca4c768aaa to your computer and use it in GitHub Desktop.
Sample schema for "Implementing GraphQL server" article
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
// @flow | |
import { | |
GraphQLObjectType, | |
GraphQLList, | |
GraphQLString, | |
GraphQLInt, | |
GraphQLNonNull, | |
GraphQLSchema, | |
} from 'graphql'; | |
import fetch from 'node-fetch'; | |
import { DateTime } from 'luxon'; | |
import { globalIdField } from 'graphql-relay'; | |
import { GraphQLDate } from 'graphql-iso-date'; | |
type PriceData = { | |
amount: number, | |
currency: string, | |
}; | |
type FlightData = { | |
id: string, | |
destination: string, | |
price?: PriceData, | |
}; | |
const sanitizeFlight = (flight: Object, currency: string): FlightData => ({ | |
id: flight.id, | |
destination: flight.cityTo, | |
price: { | |
amount: flight.price, | |
currency, | |
}, | |
}); | |
const getFlights = async (departureDate: Date) => { | |
const date = DateTime.fromJSDate(departureDate, { zone: 'utc' }); | |
const departure = date.toFormat('dd/MM/yyyy'); | |
const url = `https://api.skypicker.com/flights?flyFrom=Prague&dateFrom=${departure}&dateTo=${departure}`; | |
const response = await fetch(url, { method: 'GET' }); | |
if (response.status >= 300) { | |
throw new Error(response.statusText); | |
} | |
const payload = await response.json(); | |
if (payload && Array.isArray(payload.data)) { | |
return payload.data.map(flight => sanitizeFlight(flight, payload.currency)); | |
} | |
throw new Error('No data!'); | |
}; | |
const Price = new GraphQLObjectType({ | |
name: 'Price', | |
fields: { | |
amount: { | |
type: GraphQLInt, | |
}, | |
currency: { | |
type: GraphQLString, | |
}, | |
}, | |
}); | |
const Flight = new GraphQLObjectType({ | |
name: 'Flight', | |
fields: { | |
id: globalIdField(), | |
destination: { | |
type: GraphQLString, | |
description: 'Name of the destination city.', | |
resolve: ({ destination }: FlightData) => destination, | |
}, | |
price: { | |
type: Price, | |
resolve: ({ price }: FlightData) => price, | |
}, | |
}, | |
}); | |
const RootQuery = new GraphQLObjectType({ | |
name: 'RootQuery', | |
fields: { | |
findFlights: { | |
type: new GraphQLList(Flight), | |
description: 'Search for some cheap flights on specific date.', | |
args: { | |
departureDate: { | |
type: new GraphQLNonNull(GraphQLDate), | |
}, | |
}, | |
resolve: (_, { departureDate }): Promise<FlightData[]> => getFlights(departureDate), | |
}, | |
}, | |
}); | |
const schema = new GraphQLSchema({ | |
query: RootQuery, | |
}); | |
export default schema; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment