In the last last post on apollo-graphql I guide you to setup Apollo server and in this going to fetch live data from API using Apollo’s in build REST feature.
In this project we are using Todos API, so schema and structure may vary from the first project.
What we need ?
- A minimal Apollographql project
- RESTDataSource package
- Resolvers
RESTDatasource
Install the RESTDataSource from npm and create database/todos-api.js file.
npm install apollo-datasource-rest
Let’s extend a new class from apollo-datasource-rest package and implement our logic.
const {RESTDataSource} = require('apollo-datasource-rest');
class TodoAPI extends RESTDataSource
{
constructor(){
super();
this.baseURL='https://jsonplaceholder.typicode.com/';
}
getAllTodos(){
return this.get("todos");
}
}
module.exports=TodoAPI;
In this file we simply define baseURL and a getAllTodos method which return the API end point response.
Why I need the REST (apollo), still I have the async fetch ?. Good thought :).
Apollo REST also use the cached data and it is smarter than the async fetch, and fast.
Schema and Resolver
This is our schema and query definitions.
const { gql } = require('apollo-server')
const typeDefs = gql`
type Query{
"Query to get all todos"
todos:[Todo!]
}
type Todo{
userId:ID!
id:Int
title:String!
completed:Boolean
}
`;
module.exports = typeDefs;
Resolvers
Resolver function handles the response / data, which should have same name as Query type / schema. We are going to use the REST API within the resolvers
Save the resolvers file in resolvers/todos.js
const resolvers = {
Query: {
todos: (_, __, { dataSources }) => {
return dataSources.todoAPI.getAllTodos();
},
}
}
module.exports = resolvers;
Resolver Query function should match the type Query (in typeDef) . Every resolver function can have three arguments , namely parent, args, context and info.
Here we skip the first two and the last (Info) ,using _ for skipping first and __ for second.
Our context here is the dataSources and using it we can access the API REST methods.
In the entry point(index.js) we configure the server with following properties
const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers/todos');
const TodoAPI =require('./datasources/todos-api')
const server = new ApolloServer({ typeDefs, resolvers,dataSources:()=>{
return{
todoAPI:new TodoAPI()
}
}});
server.listen(4001).then(({ url }) => {
console.log(`
Server is running!
Listening on port ${url}
Query @ http://studio.apollographql.com/dev
`);
})
We also need to specify the dataSources as function, along with resolvers.
Let’s run the server and goto the studio.
npm start
[display-posts tag=apollo-server,graphql