Svelte auth0 example

I’m using Svelte and thought I’d share my approach to getting auth0 working with dgraph based on patterns from the react todo sample provided in the docs. I’m not sure particular code works as I didn’t test it (as I only have one slash instance and didn’t want to change my schema to test it) but conceptually it should.

App.svelte:

<script>
  import LoggedInExperience from "./LoggedInExperience.svelte";
  import { Auth0Context, authError, authToken, isAuthenticated, isLoading,
  	login, logout, userInfo, idToken } from '@dopry/svelte-auth0';
  import { AUTH0_CONFIG } from './config.js';
</script>

<Auth0Context domain = {AUTH0_CONFIG.domain} client_id = {AUTH0_CONFIG.clientId}>
  {#if $isLoading}
    <p>Loading ...</p>
  {:else if $authError}
    <p>Got error: {$authError.message}</p>
  {:else if !$isAuthenticated}
    <button on:click|preventDefault='{login}'>Login</button>
  {:else}
    <LoggedInExperience idToken={$idToken} userInfo={$userInfo} />
  {/if}	
</Auth0Context>

dgraph-apollo.js (this is 100% from the react todo example)

import ApolloClient from 'apollo-client';  
import { createHttpLink } from "apollo-link-http";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";
import { DGRAPH_CONFIG } from './config.js';

export const createApolloClient = token => {
  const httpLink = createHttpLink({
    uri: DGRAPH_CONFIG.uri,
    options: {
      reconnect: true,
    },
  });
  // Add header
  const authLink = setContext((_, { headers }) => {
      // return the headers to the context so httpLink can read them
      return {
        headers: {
          ...headers,
          "X-Auth-Token": token,
        },
      };
  });
  // Include header
  return new ApolloClient({
      link: httpLink,
      link: authLink.concat(httpLink),
      cache: new InMemoryCache()
  });
}

LoggedInExperience.svelte

<script>
  import { createApolloClient } from './dgraph-apollo.js'
  import { setClient } from 'svelte-apollo';
  import { mutate, query } from 'svelte-apollo';
  import { GET_USER, ADD_USER } from './queries.js'
  
  export let idToken;
  export let userInfo;
  const client = createApolloClient(idToken);
  setClient(client);
  
  async function addUser() {
    try{
      await mutate(client, {input: [{
        mutation: ADD_USER,
        variables: { 
          user: {
            username: userInfo.email,
            name: userInfo.nickname
          }
        }
      }]});
    } catch(error) {
      //perhaps already a user
    }
  }

  const userFetch = query(client, {
    query: GET_USER,
    variables: {username: userInfo.email}
  });

  function reload() {
    userFetch.refetch();
  }
</script>

{#await $userFetch}
  <p>Loading...<p>
{:then user}
  <p>{userFetch.data.getUser.user.name}</p>
{/await}

<button on:click={reload}>Reload</button>
8 Likes

Thanks. This is awesome!!!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.