Commit 9854f583 authored by alexlbr's avatar alexlbr

adds solution

parent 6fe392ae
...@@ -32,9 +32,26 @@ We are going to create our own GraphQL API on top of this [Rick and Morty API](h ...@@ -32,9 +32,26 @@ We are going to create our own GraphQL API on top of this [Rick and Morty API](h
- [ ] 1. Create a Character type in your schema. Here is the [documentation of the character endpont](https://rickandmortyapi.com/documentation/#character-schema). - [ ] 1. Create a Character type in your schema. Here is the [documentation of the character endpont](https://rickandmortyapi.com/documentation/#character-schema).
- [ ] 2. Create as Episode type in your schema. Here is the [documentation of the episode endpont](https://rickandmortyapi.com/documentation/#episode-schema). - [ ] 2. Create an Episode type in your schema. Here is the [documentation of the episode endpont](https://rickandmortyapi.com/documentation/#episode-schema).
### Bonus exercise - [ ] 3. Create a relationship between Episode type in your schema. Here is the [documentation of the episode endpont](https://rickandmortyapi.com/documentation/#episode-schema). Hints
- You need to add a Character type in the resolvers object and an episodes field to it. Similar to the Author type and books field in the example [https://www.apollographql.com/docs/apollo-server/essentials/data#resolver-map](map) the episodes
- You can filter the episodes in our case using the `mapEpisodeUrlToEpisode` defined at the bottom of this file `src/index.js` of this project.
- [ ] 4. Replace the mock data using https://rickandmortyapi.com/documentation/#rest.
- You can use the `fetchEpisodes` and `fetchCharacters` defined at the bottom of this file `src/index.js`
- You'll need to replace mock data in 3 different places:
- Query characters
- Query episodes
- Field episodes in the Character type
- [ ] 5. Create a query that returns a single Character given an id. You need to fetch the character using `https://rickandmortyapi.com/documentation/#get-a-single-character`
### Bonus
Create a field in Episode that returns a list the Character types in that episode using the [REST API](https://rickandmortyapi.com/documentation/#rest)
## Articles and links ## Articles and links
......
...@@ -19,7 +19,8 @@ ...@@ -19,7 +19,8 @@
"homepage": "https://github.com/reactgraphqlacademy/rest-to-graphql-workshop#readme", "homepage": "https://github.com/reactgraphqlacademy/rest-to-graphql-workshop#readme",
"dependencies": { "dependencies": {
"apollo-server": "^2.5.0", "apollo-server": "^2.5.0",
"graphql": "^14.3.1" "graphql": "^14.3.1",
"node-fetch": "^2.6.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.4.5", "@babel/core": "^7.4.5",
......
const fetch = require("node-fetch");
const { ApolloServer, gql } = require("apollo-server"); const { ApolloServer, gql } = require("apollo-server");
// import { ApolloServer, gql } from "apollo-server";
// This is a (sample) collection of books we'll be able to query
// the GraphQL server for. A more complete example might fetch
// from an existing data source like a REST API or database.
const characters = [
{
name: "Rick Sanchez",
id: 1,
status: "Alive"
},
{
name: "Morty Smith",
id: 2,
status: "Alive"
}
];
// Type definitions define the "shape" of your data and specify // Type definitions define the "shape" of your data and specify
// which ways the data can be fetched from the GraphQL server. // which ways the data can be fetched from the GraphQL server.
const typeDefs = gql` const typeDefs = gql`
# Comments in GraphQL are defined with the hash (#) symbol. # Comments in GraphQL are defined with the hash (#) symbol.
# This "Characher" type can be used in other type declarations. # This "Character" type can be used in other type declarations.
type Characher { type Character {
id: Int id: Int
name: String name: String
status: String status: String
episodes: [Episode]
} }
type Episode { type Episode {
id: Int id: Int
name: String name: String
episode: String
} }
# The "Query" type is the root of all GraphQL queries. # The "Query" type is the root of all GraphQL queries.
# (A "Mutation" type will be covered later on.) # (A "Mutation" type will be covered later on.)
type Query { type Query {
characters: [Characher] characters: [Character]
episodes: [Episodes] character(id: Int): Character
episodes: [Episode]
} }
`; `;
// Resolvers define the technique for fetching the types in the
// schema. We'll retrieve books from the "books" array above.
const resolvers = { const resolvers = {
Query: { Query: {
characters: () => characters characters: () => fetchCharacters(),
character: (_, args) => fetchCharacter(args.id),
episodes: () => fetchEpisodes()
},
Character: {
episodes: async obj => {
const characterEpisodes = obj.episode || [];
const episodes = await fetchEpisodes();
if (characterEpisodes.length === 0) {
return [];
}
return characterEpisodes.map(episodeUrl => {
return mapEpisodeUrlToEpisode(episodes, episodeUrl);
});
}
} }
}; };
...@@ -61,3 +60,67 @@ const server = new ApolloServer({ typeDefs, resolvers }); ...@@ -61,3 +60,67 @@ const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => { server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`); console.log(`🚀 Server ready at ${url}`);
}); });
// This is a (sample) collection of books we'll be able to query
// the GraphQL server for. A more complete example might fetch
// from an existing data source like a REST API or database.
const characters = [
{
name: "Rick Sanchez",
id: 1,
status: "Alive",
episodes: [
"https://rickandmortyapi.com/api/episode/1",
"https://rickandmortyapi.com/api/episode/2"
]
},
{
name: "Morty Smith",
id: 2,
status: "Alive",
episodes: [
"https://rickandmortyapi.com/api/episode/1",
"https://rickandmortyapi.com/api/episode/3"
]
}
];
const episodes = [
{
name: "Pilot",
id: 1
},
{
name: "Lawnmower Dog",
id: 2
}
];
function getEpisodeIdFromUrl(url) {
return url && url.split("/").pop();
}
function mapEpisodeUrlToEpisode(episodes, episodeUrl) {
return episodes.find(e => e.id == getEpisodeIdFromUrl(episodeUrl));
}
function fetchEpisodes() {
// More info about the fetch function? https://github.com/bitinn/node-fetch#json
return fetch("https://rickandmortyapi.com/api/character/")
.then(res => res.json())
.then(json => json.results);
}
function fetchCharacters() {
// More info about the fetch function? https://github.com/bitinn/node-fetch#json
return fetch("https://rickandmortyapi.com/api/character/")
.then(res => res.json())
.then(json => json.results);
}
function fetchCharacter(id) {
// More info about the fetch function? https://github.com/bitinn/node-fetch#json
return fetch("https://rickandmortyapi.com/api/character/" + id)
.then(res => res.json())
.then(json => json);
}
...@@ -1990,7 +1990,7 @@ node-environment-flags@^1.0.5: ...@@ -1990,7 +1990,7 @@ node-environment-flags@^1.0.5:
object.getownpropertydescriptors "^2.0.3" object.getownpropertydescriptors "^2.0.3"
semver "^5.7.0" semver "^5.7.0"
node-fetch@^2.1.2, node-fetch@^2.2.0: node-fetch@^2.1.2, node-fetch@^2.2.0, node-fetch@^2.6.0:
version "2.6.0" version "2.6.0"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.0.tgz#e633456386d4aa55863f676a7ab0daa8fdecb0fd" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.0.tgz#e633456386d4aa55863f676a7ab0daa8fdecb0fd"
integrity sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA== integrity sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment