DEV Community


Posted on

Svelte + Dad Jokes + GraphQL-yoga

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 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


  1/ REST endpoint (
  2/ NodeJS. (graphql-yoga and good old node-fetch).
  3/ Svelte starter template (
  4/ svelte-apollo and apollo-boost
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Becomes like this although "ProcessingTime" isn't required I am still adding it.

type Joke {
    Opener: String
    Punchline: String
    ProcessingTime: String 

Enter fullscreen mode Exit fullscreen mode

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 `
    result = query(client, {
        query: joke
Enter fullscreen mode Exit fullscreen mode

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) {
Enter fullscreen mode Exit fullscreen mode

The HTML part of the Svelte app

    {#await $result}
        {:then res}
        <h1>Press Enter for a new joke!</h1>
Enter fullscreen mode Exit fullscreen mode

So here is our result.

Dad Joke + GraphQL + Svelte

This post explains JSON <> GraphQL in much better detail.

Happy Father's day and Yoga day!

Link to the repo


Top comments (0)