Franz  Bosco

Franz Bosco

1602734400

Maxime Lambotin : Svelte + Sapper + GraphQL = ❤️

Svelte + Sapper + GraphQL = ❤️

J’ai testé Svelte et Sapper pour la première fois lors d’un projet libre pour mon école (Epitech). Il s’agit d’une application web permettant d’agréger des événements (concerts, meetups, etc…) de différentes plateformes en ligne (EventBrite, Meetup, Facebook Events). J’ai également utilisé un client GraphQL avec Svelte via Svelte-Apollo.

#svelte #sapper #graphql #javascript #developer

What is GEEK

Buddha Community

Maxime Lambotin : Svelte + Sapper + GraphQL = ❤️
Franz  Bosco

Franz Bosco

1602734400

Maxime Lambotin : Svelte + Sapper + GraphQL = ❤️

Svelte + Sapper + GraphQL = ❤️

J’ai testé Svelte et Sapper pour la première fois lors d’un projet libre pour mon école (Epitech). Il s’agit d’une application web permettant d’agréger des événements (concerts, meetups, etc…) de différentes plateformes en ligne (EventBrite, Meetup, Facebook Events). J’ai également utilisé un client GraphQL avec Svelte via Svelte-Apollo.

#svelte #sapper #graphql #javascript #developer

Elm Graphql: Autogenerate Type-safe GraphQL Queries in Elm

dillonkearns/elm-graphql  

Why use this package over the other available Elm GraphQL packages? This is the only one that generates type-safe code for your entire schema. Check out this blog post, Type-Safe & Composable GraphQL in Elm, to learn more about the motivation for this library. (It's also the only type-safe library with Elm 0.18 or 0.19 support, see this discourse thread).

I built this package because I wanted to have something that:

  1. Gives you type-safe GraphQL queries (if it compiles, it's valid according to the schema),
  2. Creates decoders for you in a seamless and failsafe way, and
  3. Eliminates GraphQL features in favor of Elm language constructs where possible for a simpler UX (for example, GraphQL variables & fragments should just be Elm functions, constants, lets).

See an example in action on Ellie. See more end-to-end example code in the examples/ folder.

Overview

dillonkearns/elm-graphql is an Elm package and accompanying command-line code generator that creates type-safe Elm code for your GraphQL endpoint. You don't write any decoders for your API with dillonkearns/elm-graphql, instead you simply select which fields you would like, similar to a standard GraphQL query but in Elm. For example, this GraphQL query

query {
  human(id: "1001") {
    name
    homePlanet
  }
}

would look like this in dillonkearns/elm-graphql (the code in this example that is prefixed with StarWars is auto-generated)

import Graphql.Operation exposing (RootQuery)
import Graphql.SelectionSet as SelectionSet exposing (SelectionSet)
import StarWars.Object
import StarWars.Object.Human as Human
import StarWars.Query as Query
import StarWars.Scalar exposing (Id(..))


query : SelectionSet (Maybe HumanData) RootQuery
query =
    Query.human { id = Id "1001" } humanSelection


type alias HumanData =
    { name : String
    , homePlanet : Maybe String
    }


humanSelection : SelectionSet HumanData StarWars.Object.Human
humanSelection =
    SelectionSet.map2 HumanData
        Human.name
        Human.homePlanet

GraphQL and Elm are a perfect match because GraphQL is used to enforce the types that your API takes as inputs and outputs, much like Elm's type system does within Elm. elm-graphql simply bridges this gap by making your Elm code aware of your GraphQL server's schema. If you are new to GraphQL, graphql.org/learn/ is an excellent way to learn the basics.

After following the installation instructions to install the @dillonkearns/elm-graphql NPM package and the proper Elm packages (see the Setup section for details). Once you've installed everything, running the elm-graphql code generation tool is as simple as this:

npx elm-graphql https://elm-graphql.herokuapp.com --base StarWars --output examples/src

If headers are required, such as a Bearer Token, the --header flag can be supplied.

npx elm-graphql https://elm-graphql.herokuapp.com --base StarWars --output examples/src --header 'headerKey: header value'

Learning Resources

There is a thorough tutorial in the SelectionSet docs. SelectionSets are the core concept in this library, so I recommend reading through the whole page (it's not very long!).

The examples/ folder is another great place to start.

If you want to learn more GraphQL basics, this is a great tutorial, and a short read: graphql.org/learn/

My Elm Conf 2018 talk goes into the philosophy behind dillonkearns/elm-graphql

Types Without Borders Elm Conf Talk

(Skip to 13:06 to go straight to the dillonkearns/elm-graphql demo).

If you're wondering why code is generated a certain way, you're likely to find an answer in the Frequently Asked Questions (FAQ).

There's a very helpful group of people in the #graphql channel in the Elm Slack. Don't hesitate to ask any questions about getting started, best practices, or just general GraphQL in there!

Setup

dillonkearns/elm-graphql generates Elm code that allows you to build up type-safe GraphQL requests. Here are the steps to setup dillonkearns/elm-graphql.

Add the dillonkearns/elm-graphql elm package as a dependency in your elm.json. You will also need to make sure that elm/json is a dependency of your project since the generated code has lots of JSON decoders in it.

elm install dillonkearns/elm-graphql
elm install elm/json

Install the @dillonkearns/elm-graphql command line tool through npm. This is what you will use to generate Elm code for your API. It is recommended that you save the @dillonkearns/elm-graphql command line tool as a dev dependency so that everyone on your project is using the same version.

npm install --save-dev @dillonkearns/elm-graphql
# you can now run it locally using `npx elm-graphql`,
# or by calling it through an npm script as in this project's package.json

Run the @dillonkearns/elm-graphql command line tool installed above to generate your code. If you used the --save-dev method above, you can simply create a script in your package.json like the following:

{
  "name": "star-wars-elm-graphql-project",
  "version": "1.0.0",
  "scripts": {
    "api": "elm-graphql https://elm-graphql.herokuapp.com/api --base StarWars"
  }

With the above in your package.json, running npm run api will generate dillonkearns/elm-graphql code for you to call in ./src/StarWars/. You can now use the generated code as in this Ellie example or in the examples folder.

Subscriptions Support

You can do real-time APIs using GraphQL Subscriptions and dillonkearns/elm-graphql. Just wire in the framework-specific JavaScript code for opening the WebSocket connection through a port. Here's a live demo and its source code. The demo server is running Elixir/Absinthe.

Contributors

Thank you Mario Martinez (martimatix) for all your feedback, the elm-format PR, and for the incredible logo design!

Thank you Mike Stock (mikeastock) for setting up Travis CI!

Thanks for the reserved words pull request @madsflensted!

A huge thanks to @xtian for doing the vast majority of the 0.19 upgrade work! :tada:

Thank you Josh Adams (@knewter) for the code example for Subscriptions with Elixir/Absinthe wired up through Elm ports!

Thank you Romario for adding OptionalArgument.map!

Thank you Aaron White for your pull request to improve the performance and stability of the elm-format step! 🎉

Roadmap

All core features are supported. That is, you can build any query or mutation with your dillonkearns/elm-graphql-generated code, and it is guaranteed to be valid according to your server's schema.

dillonkearns/elm-graphql will generate code for you to generate subscriptions and decode the responses, but it doesn't deal with the low-level details for how to send them over web sockets. To do that, you will need to use custom code or a package that knows how to communicate over websockets (or whichever protocol) to setup a subscription with your particular framework. See this discussion for why those details are not handled by this library directly.

I would love to hear feedback if you are using GraphQL Subscriptions. In particular, I'd love to see live code examples to drive any improvements to the Subscriptions design. Please ping me on Slack, drop a message in the #graphql channel, or open up a Github issue to discuss!

I would like to investigate generating helpers to make pagination simpler for Connections (based on the Relay Cursor Connections Specification). If you have ideas on this chime in on this thread.

See the full roadmap on Trello.


Author: dillonkearns
Source Code: https://github.com/dillonkearns/elm-graphql
License: View license

#graphql 

Layne  Fadel

Layne Fadel

1648555200

Svelte Apollo: Svelte Integration For Apollo GraphQL

svelte-apollo

Svelte integration for Apollo GraphQL.

Example

The following simple example shows how to run a simple query with svelte-apollo.

<!-- App.svelte -->
<Books />

<script>
  import { ApolloClient } from "@apollo/client";
  import { setClient } from "svelte-apollo";
  import Books from "./Books.svelte";

  // 1. Create an Apollo client and pass it to all child components
  //    (uses svelte's built-in context)
  const client = new ApolloClient({
    /* ... */
  });
  setClient(client);
</script>
<!-- Books.svelte -->
<script>
  import { query } from "svelte-apollo";
  import { GET_BOOKS } from "./queries";

  // 2. Execute the GET_BOOKS GraphQL query using the Apollo client
  //    -> Returns a svelte store of promises that resolve as values come in
  const books = query(GET_BOOKS);
</script>

<!-- 3. Use $books (note the "$"), to subscribe to query values -->
{#if $books.loading}
  Loading...
{:else if $books.error}
  Error: {$books.error.message}
{:else}
  {#each $books.data.books as book}
    {book.title} by {book.author.name}
  {/each}
{/if}

API

# query(document[, options])

Query an Apollo client, returning a readable store of result values. Uses Apollo's watchQuery, for fetching from the network and watching the local cache for changes. If the client is hydrating after SSR, it attempts a readQuery to synchronously check the cache for values.

<script>
  import { query } from "svelte-apollo";
  import { GET_BOOKS } from "./queries";

  const books = query(GET_BOOKS, {
    // variables, fetchPolicy, errorPolicy, and others
  });

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

<ul>
  {#if $books.loading}
    <li>Loading...</li>
  {:else if $books.error}
    <li>ERROR: {$books.error.message}</li>
  {:else}
    {#each $books.data.books as book (book.id)}
      <li>{book.title} by {book.author.name}</li>
    {/each}
  {/if}
</ul>

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

Reactive variables are supported with refetch:

<script>
  import { query } from "svelte-apollo";
  import { SEARCH_BY_AUTHOR } from "./queries";

  export let author;
  let search = "";

  const books = query(SEARCH_BY_AUTHOR, {
    variables: { author, search },
  });

  // `books` is refetched when author or search change
  $: books.refetch({ author, search });
</script>

Author: {author}
<label>Search <input type="text" bind:value="{search}" /></label>

<ul>
  {#if $books.loading}
    <li>Loading...</li>
  {:else if $books.error}
    <li>ERROR: {$books.error.message}</li>
  {:else if $books.data}
    {#each $books.data.books as book (book.id)}
      <li>{book.title}</li>
    {/each}
  {:else}
    <li>No books found</li>
  {/if}
</ul>

# mutation(document[, options])

Prepare a GraphQL mutation with the Apollo client, using Apollo's mutate.

<script>
  import { mutation } from "svelte-apollo";
  import { ADD_BOOK } from "./queries";

  const addBook = mutation(ADD_BOOK);
  let title = "";
  let author = "";

  async function handleSubmit() {
    try {
      await addBook({ variables: { title, author } });
    } catch (error) {
      // TODO
    }
  }
</script>

<form on:submit|preventDefault="{handleSubmit}">
  <label for="book-author">Author</label>
  <input type="text" id="book-author" bind:value="{author}" />

  <label for="book-title">Title</label>
  <input type="text" id="book-title" bind:value="{title}" />

  <button type="submit">Add Book</button>
</form>

# subscribe(document[, options])

Subscribe using an Apollo client, returning a store that is compatible with {#await $...}. Uses Apollo's subscribe.

<script>
  import { subscribe } from "svelte-apollo";
  import { NEW_BOOKS } from "./queries";

  const newBooks = subscribe(NEW_BOOKS);
</script>

{#if $newBooks.loading}
  Waiting for new books...
{:else if $newBooks.data}
  New Book: {$newBooks.data.book}
{/if}

# restore(document, options)

Restore a previously executed query (e.g. via preload) into the Apollo cache.

<script context="module">
  import client from "./client";
  import { GET_BOOKS } from "./queries";

  export async function preload() {
    return {
      preloaded: await client.query({ query: GET_BOOKS }),
    };
  }
</script>

<script>
  import { restore } from "svelte-apollo";

  export let preloaded;

  // Load preloaded values into client's cache
  restore(GET_BOOKS, preloaded);
</script>

# setClient(client)

Set an Apollo client for the current component's and all child components' contexts.

<!-- Parent.svelte -->
<script>
  import { setClient } from "svelte-apollo";
  import client from "./client";

  setClient(client);
</script>

# getClient()

Get an Apollo client from the current component's context.

<!-- Child.svelte -->
<script>
  import { getClient } from "svelte-apollo";

  const client = getClient();
</script>

Author: timhall
Source Code: https://github.com/timhall/svelte-apollo
License: MIT License

#graphql #apollo #svelte 

Delbert  Ferry

Delbert Ferry

1622105190

How to use GraphQL with Javascript – GraphQL.js tutorial

One of the fastest ways to get up and running with GraphQL is to install Apollo Server as middleware on your new or existing HTTP server.

In this short post, we demonstrate how to use Apollo Server to create a GraphQL server with Express.js using the [apollo-server-express] package. At the end, we’ll discuss the tradeoffs of this approach.

#graphql #javascript #graphql.js #graphql.js tutorial

Sean Wade

Sean Wade

1595899390

Hosting your own Svelte / Sapper App

You’ve built an amazing app using Sapper and Svelte, but now what? Where do we host it to make it available to the world? This article will set out the steps involved in one possible approach, self-hosting your own Sapper application using DigitalOcean.

I recently went through this process having built an application and hosting it using Vercel. They have a slick deployment process, but as they better suit serverless applications I quickly realized I needed more than what they offered. So I rented a virtual server and moved the app there.

If you like you can see my Shop Ireland Sapper / Svelte project in action. It’s running on a DigitalOcean droplet as a Node app, with an Nginx reverse proxy. I also have a second app running alongside that acts as an API layer to get product information from Amazon.

What we cover in this article

In this article, I’ll walk through the steps I took to set up a server to run Node projects such as Sapper applications. I hope this can act as a good starting point for you if you’re interested in running your own Svelte / Sapper app.

Note: this is written based on Ubuntu version 18.04. Some specifics might have changed with newer versions.

Topics:

  • Setting up your Digital Ocean droplet
  • Node and Nginx proxy server
  • Pushing your app code using Git
  • Running your app using PM2
  • Setting up Nginx server block with caching
  • Adding a domain name
  • Testing your site

#svelte #sapper #digitalocean #database #developer