cheatsheets

GraphQL Cheatsheet

Spis treści


Mutation

Mutacje — createUser

https://graphql.org/graphql-js/mutations-and-input-types/

mutation {
  createUser(data: {
    name: "piecioshka"
  }) {
    id
    name
  }
}
// 5c157dbfa7b11b0007c1767c

Mutation — deleteUser

mutation {
  deleteUser(where: { id: "5c157dbfa7b11b0007c1767c" }) {
    id
    name
  }
}

Spróbuj uruchomić “2x”?

Query

https://graphql.org/learn/queries/

query {
  users {
    id
    name
  }
}

Subscription

https://graphql.org/blog/subscriptions-in-graphql-and-relay/

Apollo

Framework do budowania klientĂłw i serwerĂłw GraphQL.

Apollo Client — instalacja

npm install @apollo/client graphql

Apollo Client — konfiguracja

import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://api.example.com/graphql',
  cache: new InMemoryCache(),
});

Apollo Client — zapytanie (useQuery)

import { useQuery, gql } from '@apollo/client';

const GET_USERS = gql`
  query {
    users {
      id
      name
    }
  }
`;

function Users() {
  const { loading, error, data } = useQuery(GET_USERS);
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  return data.users.map(({ id, name }) => <p key={id}>{name}</p>);
}

Apollo Client — mutacja (useMutation)

import { useMutation, gql } from '@apollo/client';

const CREATE_USER = gql`
  mutation CreateUser($name: String!) {
    createUser(data: { name: $name }) {
      id
      name
    }
  }
`;

function CreateUser() {
  const [createUser] = useMutation(CREATE_USER);
  return (
    <button onClick={() => createUser({ variables: { name: 'piecioshka' } })}>
      Create
    </button>
  );
}

Edytor

https://graphqleditor.com/

Prisma

DEMO: https://github.com/piecioshka/test-nodejs-prisma

Relay