So... what is GraphQL..?
High-level definition
- query language for APIs
- alternative to REST
- customizable requests
Why Graphql?
- One centralized endpoint
- Client gets exactly what it needs
- less overhead
- faster
- Typed!
Set up a mock server
- You can mock the data that is returned from your API to get a quicker start
- As easy as setting mocks to true when you start your Apollo Server
- Or you can customize your mocks
const { ApolloServer, gql } = require("apollo-server");
const faker = require("faker");
const typeDefs = gql`
type Dog {
id: ID!
name: String!
age: Int
}
type Query {
allDog: [Dog!]!
}
`;
const mocks = {
ID: () => faker.random.uuid(),
Int: () => faker.random.number({ min: 1, max: 25 }),
String: () => faker.name.firstName(),
};
const resolvers = {
Query: {
allDogs: () => [{id: 1, name: "Meatball"}]
}
};
const server = new ApolloServer({typeDefs, resolvers, mocks, mockEntireSchema: false});
server
.listen()
.then(({ port }) => console.log(`Server running on port ${port}`));
import React, { Fragment } from 'react';
import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';
import { LaunchTile, Header, Button, Loading } from '../components';
import { RouteComponentProps } from '@reach/router';
import * as GetLaunchListTypes from './__generated__/GetLaunchList';
const GET_LAUNCHES = gql`
query launchList($after: String) {
launches(after: $after) {
cursor
hasMore
launches {
id
isBooked
rocket {
id
name
}
mission {
name
missionPatch
}
}
}
}
`;
interface LaunchesProps extends RouteComponentProps {}
const Launches: React.FC<LaunchesProps> = () => {
const {
data,
loading,
error
} = useQuery<
GetLaunchListTypes.GetLaunchList,
GetLaunchListTypes.GetLaunchListVariables
>(GET_LAUNCHES);
if (loading) return <Loading />;
if (error) return <p>ERROR</p>;
if (!data) return <p>Not found</p>;
return (
<Fragment>
<Header />
{data.launches &&
data.launches.launches &&
data.launches.launches.map((launch: any) => (
<LaunchTile key={launch.id} launch={launch} />
))}
</Fragment>
);
}
export default Launches;
Check out Static-Sites
- Uses Contentful GraphQL API
- No mutations, just queries
- run it locally and check out http://localhost:8000/___graphql
Further reading
GraphQL 101
By borisonr
GraphQL 101
- 377