Skip to content

Instantly share code, notes, and snippets.

@jackie1santana
Last active September 22, 2021 21:58
Show Gist options
  • Save jackie1santana/708c12a2c80a5695c79640068eddda48 to your computer and use it in GitHub Desktop.
Save jackie1santana/708c12a2c80a5695c79640068eddda48 to your computer and use it in GitHub Desktop.
Apollo Client & Server Set up
const resolvers = {
Query: {
getCurrentGlobalCases: () => currentGlobalCases(),
getGlobalCasesByDate(parent, args) {
//id: Cases By Date
return globalCasesByDate(args.id);
},
// id: Cases By Country Name
getCasesByCountryName(parent, args) {
return casesByCountryName(args.id.trim());
},
getCasesByState(parent, args) {
args.id = args.id.toUpperCase().trim() && args.id.toLowerCase().trim();
return casesByState(args.id);
}
},
};
import React from 'react'
import { gql } from 'apollo-boost'
import { useQuery } from '@apollo/react-hooks';
const GET_BOOKS = gql`
query {
books {
title
author,
id
}
}
`
function BookList() {
const { loading, error, data } = useQuery(GET_BOOKS);
const displayBooks = () => {
if(loading){
return(<div>Loading ...</div>)
}else {
return data.books.map(book => {
return <li>{book.title}</li>
})
}
}
return (
<div>
<h2>My first Apollo app 🚀</h2>
<ul>{
displayBooks()
}</ul>
</div>
)
}
export default BookList
import React from 'react';
import './App.css';
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from '@apollo/react-hooks';
import BookList from './components/BookList'
const client = new ApolloClient({
uri: 'http://localhost:4000/',
});
function App() {
return (
<ApolloProvider client={client}>
<div className="App">
<BookList/>
</div>
</ApolloProvider>
);
}
export default App;
const { gql } = require("apollo-server-express");
const books = [
{
title: "Harry Potter and the Chamber of Secrets",
author: "J.K. Rowling",
id: "1"
},
{
title: "Jurassic Park",
author: "Michael Crichton",
id: "2"
}
];
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Book {
title: String
author: String
id: String
}
type Query {
books: [Book]
book(id: ID): Book
}
type Mutation {
addBook(title: String, author: String, id: ID): Book
}
`;
// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
Query: {
books: () => books,
book(parent, args, context, info) {
return books.find(i => i.id === args.id);
}
},
Mutation: {
addBook(_, { title, author, id }){
const storeBook = {
title,
author,
id
}
books.push(storeBook)
return storeBook
}
}
};
// Provide resolver functions for your schema fields
module.exports = {
typeDefs,
resolvers
}
npm i apollo-server-express --save
const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const { ApolloServer } = require("apollo-server-express");
const { typeDefs, resolvers } = require("./model/graphqlSchema/schema");
const path = require('path')
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });
dotenv.config({ path: "./config/.env" });
var PORT = process.env.PORT;
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const publicDirectoryPath = path.join(__dirname, '/server/public')
app.use(express.static(publicDirectoryPath))
app.listen(PORT, () =>
console.log(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`)
);
Date Api format
//put dat as parameter
const MM = "04"
const DD = "02"
const YYYY = "2020"
let date = `${MM}-${DD}-${YYYY}`
globalCasesByDate(date)
},
params: {
//start
country: countryName.trim() === 'us' ? 'United States of America' :
countryName.trim() === 'usa' ? 'United States of America' :
countryName.trim() === 'united states' ? 'United States of America' :
!countryName.trim() ? 'You entered an invalid country' : countryName.trim()
//enf of ternary
},
the only way to get an out put is to do this: const axiosAPIName = () => <axios file>
DO NOT ADD { } to it ... because it will not work in resolvers
const axios = require("axios");
const globalCasesByDate = () =>
axios({
method: "GET",
url: "https://covid-19-data.p.rapidapi.com/report/totals",
headers: {
"content-type": "application/octet-stream",
"x-rapidapi-host": "covid-19-data.p.rapidapi.com",
"x-rapidapi-key": "a8b09fdfc0mshd6f279d5c7cefd6p11f240jsn27ee495e8d1c",
useQueryString: true,
},
params: {
"date-format": "YYYY-MM-DD",
format: "json",
date: "2020-04-02",
},
})
.then((response) => {
return response.data
})
.catch((error) => {
console.log(error);
});
module.exports = { globalCasesByDate }
async getCasesByState(parent, args) {
args.id = args.id.toUpperCase().trim() && args.id.toLowerCase().trim();
db.collection("statesSearched").add({
state: args.id,
});
if (!args.id) {
return "invalid state";
} else {
return await casesByState(args.id);
}
},
},
@jackie1santana
Copy link
Author

Apollo Server Express

If you get data.user.map is not a function? that means your api needs to be in array format not OBJECT ..

your api should return return response.data only

add Array brackets

  type Query {
      user: [User]
    }

schema.js


const { gql } = require("apollo-server-express");
const { users } = require('./users_data')




  
  // Construct a schema, using GraphQL schema language
  const typeDefs = gql`
    type User {
        id: Int
      name: String
      username: String
    }
  
    type Query {
      user: [User]
    }

  `;
  // Resolvers define the technique for fetching the types defined in the
  // schema. This resolver retrieves books from the "books" array above.
  const resolvers = {
    Query: {
      user: () => users()
      
    }
  };
  // Provide resolver functions for your schema fields
  
  module.exports = {
      typeDefs,
      resolvers
  }


server.js


const express = require('express');
const { ApolloServer } = require("apollo-server-express");
const { typeDefs, resolvers } = require("./model/graphqlSchema/schema");

require("./model/graphqlSchema/schema");

const path = require('path') 
const cors = require('cors')


const app = express();
// const myGraphQLSchema = // ... define or import your schema here!
const PORT = 4000;
app.use(cors())
app.use(express.json()) 
app.use(express.urlencoded({ extended: false }));

const server = new ApolloServer({ typeDefs, resolvers });

server.applyMiddleware({ app });


// const publicDirectoryPath = path.join(__dirname, '/server/public')

// app.use(express.static(publicDirectoryPath))


app.listen(PORT, () =>
  console.log(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`)
);

Apollo Client

React
App.js


import Home from './components/Home'
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from '@apollo/react-hooks';


const client = new ApolloClient({
  uri: 'http://localhost:4000/graphql'
});

function App() {
  return (
    <ApolloProvider client={client}>
    <div>
      <Home/>
    </div>
    </ApolloProvider>
  );
}

export default App;





Home.js

import React from 'react'
import './Home.css'
import { gql } from 'apollo-boost'
import { useQuery } from '@apollo/react-hooks';
const USERS = gqlquery getUsers { user { id name, username } }

// const client = ...

export default function Home() {
const { loading, error, data } = useQuery(USERS);
console.log(data)
if (loading) return

Loading...

;
if (error) return

Error :(

;

        return data.user.map(user => (
          <div>
            <p>
              {user.name}
            </p>
          </div>
        ));

}

@jackie1santana
Copy link
Author

if issue with apollo wait.server()
downgrade to apollo-server-express@^2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment