Hi @ptpaterson @alexnitta . Below is the API for the /api/graphql
route:
import Cors from 'micro-cors'
import { gql, ApolloServer } from 'apollo-server-micro'
import { Client, Map, Paginate, Documents, Collection, Lambda, Get } from 'faunadb'
const client = new Client({
secret: process.env.FAUNA_SECRET,
domain: "db.fauna.com",
})
export const config = {
api: {
bodyParser: false
}
}
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`
const resolvers = {
Query: {
books: async () => {
const response = await client.query(
Map(
Paginate(Documents(Collection('Book'))),
Lambda((x) => Get(x))
)
)
const books = response.data.map(item => item.data)
return [...books]
},
},
}
const cors = Cors()
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
},
introspection: true,
playground: true,
})
const serversStart = apolloServer.start()
export default cors(async (req, res) => {
if (req.method === "OPTIONS") {
res.end();
return false;
}
await serversStart;
await apolloServer.createHandler({ path: '/api/graphql' })(req, res)
})
Through a Chrome browser, I can view the data it calls through the Apollo GraphQL Studio and it successfully responds:
Following your suggesting @alexnitta, I added the following code to the _app.js
file:
import '../styles/globals.css'
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { ApolloProvider } from "@apollo/client";
const client = new ApolloClient({
uri: "https://graphql.fauna.com/graphql",
headers: {
authorization: `Bearer ${process.env.FAUNA_SECRET}`,
},
cache: new InMemoryCache(),
});
function MyApp({ Component, pageProps }) {
console.log(client)
return (
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
)
}
export default MyApp
Although, I’m not sure if the uri
parameter should be set to /api/graphql
instead.
An alternate page which should call the data is the test.js
page:
import gql from "graphql-tag";
import { useQuery } from "@apollo/react-hooks";
const Query = gql`
query Query {
books {
title
}
}
`
export default function Test() {
const { data, loading } = useQuery(Query);
if (loading) {
return "Loading...";
}
return (
<div>
<div>
TEST
</div>
{data.books.title}
</div>
);
}
As you can probably tell, I’m quite green to Apollo and also fauna development.
The page localhost:3000/test
simply returns the TypeError: Cannot read properties of undefined (reading 'books')
.
I’m not sure how to render the data