Today we find ourselves celebrating International Yoga day and Father's day.
I am going to show you how to make a minimal dad joke app using a wonderful API http://dadjokes.online/ that directly gives a JSON response also no CORS issues if GraphQL is used.
So let's apply the knowledge from the previous article and combine it with a powerful framework. I chose Svelte because it has some amazing capabilities. Let's dive into the code.
End result looks like this
Prerequisites:
1/ REST endpoint (http://dadjokes.online/). 2/ NodeJS. (graphql-yoga and good old node-fetch). 3/ Svelte starter template (https://svelte.dev/) 4/ svelte-apollo and apollo-boost
Going to the URL we find a JSON response and we must convert into a schema for our GraphQL.
GraphQL Setup
{ "Joke": { "Opener": "Why did the computer have no money left?", "Punchline": "Someone cleaned out its cache!", "Processing Time": "0.000733" } }
Becomes like this although "ProcessingTime" isn't required I am still adding it.
type Joke { Opener: String Punchline: String ProcessingTime: String }
And firing up GraphQL code should show up on your http://localhost:4000
Svelte code, Imports and Queries
import ApolloClient, {gql} from "apollo-boost" import {query} from "svelte-apollo" const client = new ApolloClient({ uri: "http://localhost:4000" }) let result; let joke = gql ` { getJoke{ Opener Punchline } } `; result = query(client, { query: joke })
This is 90% of the code and it should begin to work. Now let's make the app a little sassy. Svelte supports keyboard events from its svelte:window. Here is a piece of code that listens to the Enter
key and it's key code is 13
. Once it's pressed we refetch() and voila! we have another joke.
let keyCode; function handleKeydown(event) { keyCode = event.keyCode; if (keyCode == 13) { result.refetch() } }
The HTML part of the Svelte app
{#await $result} <p>loading</p> {:then res} <p>{res.data.getJoke.Opener}</p> <p>..</p> <p>....</p> <p>{res.data.getJoke.Punchline}</p> <h1>Press Enter for a new joke!</h1> {/await}
So here is our result.
This post explains JSON <> GraphQL in much better detail.
Happy Father's day and Yoga day!
Link to the repo https://github.com/peopledrivemecrazy/svelte-yoga-dadjoke
Enjoy.
Top comments (0)