9. Code-Along: Use RESTDataSource instead of mocks
2m

The plan

Goal: Replace the mock data in our GraphQL server with a RESTDataSource that talks to the Catstronauts REST API.

Note: This RESTDataSource has already been created for you! It lives in the server/src/datasources/cats-api.js file.

Code-Along

  1. In the server/src/index.js file, start by removing the code for passing mock data into our ApolloServer instance. (Notice that you'll need to pass in typeDefs to the ApolloServer configuration object.)
src/index.js
// ... other imports
- import { addMocksToSchema } from "@graphql-tools/mock";
- import { makeExecutableSchema } from "@graphql-tools/schema";
- import { mocks } from "./mocks.js";
const typeDefs = gql(
readFileSync("./src/schema.graphql", { encoding: "utf-8" })
);
const server = new ApolloServer({
- schema: addMocksToSchema({
- schema: makeExecutableSchema({ typeDefs }),
- mocks,
+ typeDefs
}),
});
const { url } = await startStandaloneServer(server, {
listen: { port: process.env.PORT || 4000 },
});
console.log(`🚀 Server ready at ${url}`);
  1. Import the CatsAPI RESTDataSource class.
src/index.js
// ... other imports
import {CatsAPI} from './datasources/cats-api.js';
const typeDefs = gql(readFileSync('./src/schema.graphql', {encoding: 'utf-8'}));
const server = new ApolloServer({
typeDefs
});
const {url} = await startStandaloneServer(server, {
listen: {port: process.env.PORT || 4000}
});
console.log(`🚀 Server ready at ${url}`);
  1. Update your startStandaloneServer options to match the code below. This adds a new property called context, which is an async function that returns an object to be shared between all resolvers for an operation. (We'll talk more about context later.)
src/index.js
const {url} = await startStandaloneServer(server, {
listen: {port: process.env.PORT || 4000},
context: async () => {
return {
dataSources: {
catsAPI: new CatsAPI()
}
};
}
});
  1. Check that your server code recompiles without any errors.

Task!

Previous
Next