Skip to content

Instantly share code, notes, and snippets.

View clarencenpy's full-sized avatar

Clarence Ngoh clarencenpy

View GitHub Profile
import { UserInputError } from 'apollo-server';
const resolvers = {
Query: {
events(root, { zipCode }) {
// do custom validation for user inputs
const validationErrors = {};
if (!isValidZipCode(zipCode)) {
validationErrors.zipCode = 'This is not a valid zipcode';
{
"message": "Failed to get events due to validation errors",
"extensions": {
"code": "BAD_USER_INPUT",
"exception": {
"validationErrors": {
"zipCode": "This is not a valid zipcode"
}
}
}
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: '<your graphql endpoint>',
// Apollo Boost allows you to specify a custom error link for your client
onError: ({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
// handle errors differently based on its error code
switch (err.extensions.code) {
const typeDefs = gql`
type Event {
name: String!
date: Date!
capacity: Int!
zipCode: String!
}
`;
const typeDefs = gql`
# define wrapper result type that could return either
# the added Event on success, or an array of Errors
# on error. Notice both fields are nullable.
type AddEventResult {
event: Event
validationErrors: [FieldValidationError!]
}
# define how you want errors to be represented. This
{
"data": {
"searchMovies": {
"movies": [
{
"name": "Avengers Infinity War",
}
],
"recommendedForYou": null,
}
const typeDefs = gql`
type MovieSearchResult {
movies: [Movie!]!
recommendedForYou: [Movie!]
}
...
`
// Note: since it makes no sense that we have a null
// Movie returned in the list, we should mark each Movie
// as non-nullable too.
import React from 'react';
import { Query } from 'react-apollo';
const MovieSearchResults = ({ keyword }) => (
<Query query={SEARCH_MOVIES} variables={{ keyword }}>
{(data, loading, error) => {
if (loading) return <LoadingIndicator />;
// if networkError is present, we can be sure that no data
// was returned. We can simply display an error component.
if (error && error.networkError) return <ErrorDisplay />;
const typeDefs = gql`
type MovieSearchResult {
movies: [Movie]
recommendedForYou: [Movie]
}
type Query {
searchMovies(keyword: String!): MovieSearchResult!
}
`
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
const client = new ApolloClient({
link: ApolloLink.from([
// other links go here
ReauthenticatonLink,
new HttpLink({
uri: 'http://graphql-endpoint:4000',
}),