Modesto  Corwin

Modesto Corwin

1597544820

Four GraphQL Clients Compared

Let’s check out fetch, graphql-request, Apollo Client, and Relay, all on the same server so that you can see for yourself which one is the right one for your project.

Code: git remote add origin git@github.com:jherr/gql-clients.git
GraphQL Yoga: https://github.com/prisma-labs/graphql-yoga
GraphQL Request: https://github.com/prisma-labs/graphql-request
Apollo Client: https://www.apollographql.com/
Relay: https://relay.dev/

Thank you for watching this video, click the “SUBSCRIBE” button for stay connected with this channel.

Subscription Link: https://bit.ly/2E7drfJ

#graphql

What is GEEK

Buddha Community

Four GraphQL Clients Compared

How to Create an Image Clip Animation with Slider Controls using Only HTML & CSS

In this blog you’ll learn how to create an Image Clip Animation with Slider Controls using only HTML & CSS.

To create an Image Clip Animation with Slider Controls using only HTML & CSS. First, you need to create two Files one HTML File and another one is CSS File.

1: First, create an HTML file with the name of index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Image Clip Animation | Codequs</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="wrapper">
      <input type="radio" name="slide" id="one" checked>
      <input type="radio" name="slide" id="two">
      <input type="radio" name="slide" id="three">
      <input type="radio" name="slide" id="four">
      <input type="radio" name="slide" id="five">
      <div class="img img-1">
        <!-- <img src="images/img-1.jpg" alt="">
      </div>
      <div class="img img-2">
        <img src="images/img-2.jpg" alt="">
      </div>
      <div class="img img-3">
        <img src="images/img-3.jpg" alt="">
      </div>
      <div class="img img-4">
        <img src="images/img-4.jpg" alt="">
      </div>
      <div class="img img-5">
        <img src="images/img-5.jpg" alt="">
      </div>
      <div class="sliders">
        <label for="one" class="one"></label>
        <label for="two" class="two"></label>
        <label for="three" class="three"></label>
        <label for="four" class="four"></label>
        <label for="five" class="five"></label>
      </div>
    </div>
  </body>
</html>

2: Second, create a CSS file with the name of style.css

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body{
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: -webkit-linear-gradient(136deg, rgb(224,195,252) 0%, rgb(142,197,252) 100%);
}
.wrapper{
  position: relative;
  width: 700px;
  height: 400px;
}
.wrapper .img{
  position: absolute;
  width: 100%;
  height: 100%;
}
.wrapper .img img{
  height: 100%;
  width: 100%;
  object-fit: cover;
  clip-path: circle(0% at 0% 100%);
  transition: all 0.7s;
}
#one:checked ~ .img-1 img{
  clip-path: circle(150% at 0% 100%);
}
#two:checked ~ .img-1 img,
#two:checked ~ .img-2 img{
  clip-path: circle(150% at 0% 100%);
}
#three:checked ~ .img-1 img,
#three:checked ~ .img-2 img,
#three:checked ~ .img-3 img{
  clip-path: circle(150% at 0% 100%);
}
#four:checked ~ .img-1 img,
#four:checked ~ .img-2 img,
#four:checked ~ .img-3 img,
#four:checked ~ .img-4 img{
  clip-path: circle(150% at 0% 100%);
}
#five:checked ~ .img-1 img,
#five:checked ~ .img-2 img,
#five:checked ~ .img-3 img,
#five:checked ~ .img-4 img,
#five:checked ~ .img-5 img{
  clip-path: circle(150% at 0% 100%);
}
.wrapper .sliders{
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 99;
  display: flex;
}
.wrapper .sliders label{
  border: 2px solid rgb(142,197,252);
  width: 13px;
  height: 13px;
  margin: 0 3px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease;
}
#one:checked ~ .sliders label.one,
#two:checked ~ .sliders label.two,
#three:checked ~ .sliders label.three,
#four:checked ~ .sliders label.four,
#five:checked ~ .sliders label.five{
  width: 35px;
  border-radius: 14px;
  background: rgb(142,197,252);
}
.sliders label:hover{
  background: rgb(142,197,252);
}
input[type="radio"]{
  display: none;
}

Now you’ve successfully created an Image Clip Animation with Sliders using only HTML & CSS.

#html #css 

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 

Delbert  Ferry

Delbert Ferry

1621069824

A Swift GraphQL client that lets you forget about GraphQL

SwiftGraphQL is a Swift code generator. It lets you create queries using Swift, and guarantees that every query you create is valid.

The library is centered around three core principles:

  • If your project compiles, your queries work.
  • Use Swift in favour of GraphQL wherever possible.
  • Your application model should be independent of your schema.

#graphql #graphql client #swiftgraphql

Delbert  Ferry

Delbert Ferry

1622279156

Why you might want a GraphQL client

1. Sending correctly formed requests
Say you’re building a web application and you want to interact with a GraphQL backend. At the very basic level, all you have to do is construct POST requests with your query document, send them to the server and get a response back.
2. Keeping your UI consistent across queries
You don’t just want to fetch data; you also want to show this data to your users through a UI component. Let’s say that you have two components within your UI that each display a list of authors.
3. Updating the cache
Of course, in order for the reactive cache to work, we need to be able to update it with information returned from the server. In most cases, this is as easy as fetching a GraphQL query or running a mutation.

#graphql #graphql client

Gordon  Matlala

Gordon Matlala

1679381520

Graphql.js: A Simple & Isomorphic GraphQL Client for JavaScript

Graphql.js: lightweight graphql client

Lightest GraphQL client with intelligent features.


Originally inspired by Robert Mosolgo's blog post

Features

  • Too small, 4k gzipped.
  • No dependencies, plain vanilla JavaScript.
  • Plug & Play.
  • Isomorphic.
  • Runs on most browsers.
  • You don't need to install Node.js ecosystem on your computer.
  • Query merging to reduce request number.

Overview

GraphQL is based on a very simple HTTP transaction, which sends a request to an endpoint with query and variables.

Many libraries require complex stacks to make that simple request. In any project you don't use React, Relay, you'll need a simpler client which manages your query and makes a simple request.

// Connect...
var graph = graphql("/graphql")

// Prepare...
graph.fragment({
  user: `on User {
    id,
    name
  }`
})

const allUsers = graph(`query { allUsers { ...user } }`)

const createUser = graph(`mutation (@autodeclare) {
  createUser($firstName, $lastName) { ...user }
}`)

await createUser({
  firstName: "John",
  lastName: "Doe"
})

const users = await allUsers()

console.log(users)
// {
//   "allUsers": [{ "id": 1, "name": "John Doe" }]
// }

Installation

You can download graphql.js directly, or you can use Bower or NPM.

CDN

<script src="//cdn.jsdelivr.net/npm/graphql.js@0.6.6/graphql.min.js"></script>

Download for Browser

Using NPM

npm install graphql.js --save

# or

yarn add graphql.js

Using with Rails Asset Pipeline

You can use GraphQL.js with Rails Asset Pipeline using graphqljs-rails.

Using

GraphQL.js is isomorphic. You can use it in both browser and Node.js.

Use in Browser

<script src="/path/to/graphql.js"></script>

Use in Node.js

var graphql = require('graphql.js')

Or using import

import graphql from 'graphql.js'

Connection

Create a simple connection to your GraphQL endpoint.

var graph = graphql("http://localhost:3000/graphql", {
  method: "POST", // POST by default.
  headers: {
    // headers
    "Access-Token": "some-access-token"
    // OR "Access-Token": () => "some-access-token"
  },
  fragments: {
    // fragments, you don't need to say `fragment name`.
    auth: "on User { token }",
    error: "on Error { messages }"
  }
})

Executing Queries and Mutations

graph will be a simple function that accepts query and variables as parameters.

graph(`query ($email: String!, $password: String!) {
  auth(email: $email, password: $password) {
    ... auth # if you use any fragment, it will be added to the query.
    ... error
  }
}`, {
  email: "john@doe.com",
  password: "my-super-password"
}).then(function (response) {
  // response is originally response.data of query result
  console.log(response)
}).catch(function (error) {
  // response is originally response.errors of query result
  console.log(error)
})

Prepare Query for Lazy Execution

You can prepare queries for lazy execution. This will allow you to reuse your queries with different variables without any hassle.

var login = graph(`query ($email: String!, $password: String!) {
  auth(email: $email, password: $password) {
    ... on User {
      token
    }
  }
}`)

// Call it later...
login({
  email: "john@doe.com",
  password: "my-super-password"
})

Direct Execution with .run and ES6 Template Tag

If your query doesn't need any variables, it will generate a lazy execution query by default. If you want to run your query immediately, you have three following options:

// 1st option. create and run function.
graph(`...`)()
graph.query(`...`)()
graph.mutate(`...`)()
//...

// 2nd option. create and run function with `run` method.
graph.run(`...`)
graph.query.run(`...`)
graph.mutate.run(`...`)

// 3rd option. create and run function with template tag.
graph`...`
graph.query`...`
graph.mutate`...`

I don't recommend using this. Using it too much may break DRY. Use lazy execution as much as possible.

Prefix Helpers

You can prefix your queries by simply calling helper methods: .query, .mutate or .subscribe

var login = graph.query(`($email: String!, $password: String!) {
  auth(email: $email, password: $password) {
    ... on User {
      token
    }
  }
}`)

var increment = graph.mutate`increment { state }`
var onIncrement = graph.subscribe`onIncrement { state }`

Automatic Declaring with @autodeclare or {declare: true}

Declaring primitive-typed (String, Int, Float, Boolean) variables in query were a little bothering to me. That's why I added an @autodeclare keyword or {declare: true} setting to the processor. It detects types from the variables and declares them in query automatically.

var login = graph.query(`(@autodeclare) {
  auth(email: $email, password: $password) {
    ... on User {
      token
    }
  }
}`)

login({
  email: "john@doe.com", // It's String! obviously.
  password: "my-super-password" // It is, too.
})

This will create following query:

query ($email: String!, $password: String!) {
  auth(email: $email, password: $password) {
    ... on User {
      token
    }
  }
}

You can also pass {declare: true} option to the .query, .mutate and .subscribe helper:

var login = graph.query(`auth(email: $email, password: $password) {
  ... on User {
    token
  }
}`, {declare: true})

This will also create the same query above.

Detecting IDs

Variable names with matching /_id/i pattern will be declared as ID type. Following examples will be declared as IDs:

  • id: 1 will be declared as $id: ID!
  • post_id: "123af" will be declared as $post_id: ID!
  • postID: 3 will be declared as $postID: ID!
  • postId: 4 will be declared as $postId: ID!

You can disable auto ID declaration by adding an ! to the end of the variable name:

  • id!: 1 will be declared as $id: Int!
  • post_id!: "123af" will be declared as $post_id: String!

And, explicitly given types are prioritized.

  • postID!CustomId: 3 will be declared as $postID: CustomId!
  • postId!UUID: 4 will be declared as $postId: UUID!
var userById = graph.query(`(@autodeclare) {
  user(id: $id) {
    email
  }
}`)

userById({
  id: 15
})

The example above will generate following query:

query ($id: ID!) {
  user(id: $id) {
    email
  }
}

Solving Integer and Float Problem

Let's say you have a rating query that accepts an argument with a Float argument named rating. GraphQL.js will declare 10 value as Integer since it casts using value % 1 === 0 ? 'Int' : 'Float' check.

var rate = graph.query(`(@autodeclare) {
  rating(rating: $rating) {
    rating
  }
}`)

rate({
  rating: 10
})

In this case, you must use ! mark to force your type to be Float as below:

rate({
  "rating!Float": 10
})

This will bypass the casting and declare rating as Float.

Advanced Auto Declaring

Beside you can pass {declare: true} to helpers:

graph.query("auth(email: $email, password: $password) { token }", {declare: true})

Also you can enable auto declaration to run by default using alwaysAutodeclare setting.

var graph = graphql("http://localhost:3000/graphql", {
  alwaysAutodeclare: true
})

After you enable alwaysAutodeclare option, your methods will try to detect types of variables and declare them.

// When alwaysAutodeclare is true, you don't have to pass {declare: true} option.

graph.query("auth(email: $email, password: $password) { token }")

Auto Declaring Custom Types

You can define custom types when defining variables by using a simple "variable!Type" notation. It will help you to make more complex variables:

var register = graph.mutate(`(@autodeclare) {
  userRegister(input: $input) { ... }
}`)

register({
  // variable name and type.
  "input!UserRegisterInput": { ... }
})

This will generate following query:

mutation ($input: UserRegisterInput!) {
  userRegister(input: $input) { ... }
}

Fragments

Fragments make your GraphQL more DRY and improves reusability. With .fragment method, you'll manage your fragments easily.

Simple Fragments

While constructing your endpoint, you can predefine all of your fragments.

var graph = graphql("/graphql", {
  fragments: {
    userInfo: `on User { id, name, surname, avatar }`
  }
})

And you can use your fragments in your queries. The query will pick your fragments and will add them to the bottom of your query.

graph.query(`{ allUsers { ...userInfo } }`)

Nested Fragments

You can nest your fragments to keep them organized/namespaced.

var graph = graphql("/graphql", {
  fragments: {
    user: {
      info: `on User { id, name, surname, avatar }`
    }
  }
})

Accessing them is also intuitive:

graph.query(`{ allUsers { ...user.info } }`)

Using Fragments in Fragments

You can reuse fragments in your fragments.

graph.fragment({
  user: "on User {name, surname}",
  login: {
    auth: "on User {token, ...user}"
  }
})

Lazy Fragments

You can also add fragments lazily. So you can use your fragments more modular.

// Adds a profile fragment
graph.fragment({
  profile: `on User {
    id
    name(full: true)
    avatar
  }`
})

var allUsers = graph.query(`{
  allUsers {
    ... profile
  }
}`)

allUsers().then(...)

Also you can add nested fragments lazily, too:

graph.fragment({
  login: {
    error: `on LoginError {
      reason
    }`
  }
})

graph.fragment({
  something: {
    error: `on SomeError {
      messages
    }`
  }
})

graph.query(`{ login {... login.error } }`)
graph.query(`{ something {... something.error } }`)

Getting Fragments by Path

You can call fragment string by using .fragment method. You have to pass path string to get the fragment.

graph.fragment('login.error')

This will give you the matching fragment code:

fragment login_error on LoginError {
  reason
}

Using Fragments in Tag Query

You can use fragments lazily using ES6 template tag queries.

var userProfileToShow = graph.fragment('user.profile')

graph`query { ... ${userProfileToShow} }`

Query Building

You can create queries using .ql ES6 template tag.

// Add some fragments...
graph.fragment({
  username: {
    user: `on User {
      username
    }`,
    admin: `on AdminUser {
      username,
      administrationLevel
    }`
  }
})

// Get any fragment with its path...
var admin = graph.fragment('username.admin')

// Build your query with using fragment paths or dynamic template variables.
var query = graph.ql`query {
  ...username.user
  ...${admin}
}`

// Use query anywhere...
$.post("/graphql", {query: query}, function (response) { ... })

graph.ql will generate this query string:

query {
  ... username_user
  ... username_admin
}

fragment username_user on User {
  username
}

fragment username_admin on AdminUser {
  username,
  administrationLevel
}

Query Merging: Merge Multiple Queries into One Request

merge

This GIF shows a before/after case to make an example how query merging changes the performance.

graphql.js supports query merging that allows you to collect all the requests into one request.

Assume we've these queries on server, define them just like before we do:

var fetchPost = graph.query(`{
  post(id: $id) {
    id
    title
    text
  }
}`)

var fetchComments = graph.query(`{
  commentsOfPost: comments(postId: $postId) {
    comment
    owner {
      name
    }
  }
}`)

Normally, we make requests as following:

var postId = 123

// This will send a request.
fetchPost({ id: postId }).then(function (response) {
  console.log(response.post)
})

// This also will send a request.
fetchComments({ postId: postId }).then(function (response) {
  console.log(response.commentsOfPost)
})

This will make two requests:

ss1

Use .merge(mergeName, variables) command to put them into a merge buffer:

var postId = 123

// This won't send a request.
fetchPost.merge('buildPage', { id: postId }).then(function (response) {
  console.log(response.post)
})

// This also won't send a request.
fetchComments.merge('buildPage', { postId: postId }).then(function (response) {
  console.log(response.commentsOfPost)
})

These will create a buffer with buildPage name, and append the queries to that buffer. You need to use commit(mergeName) to merge the buffer and send to the server, the response will be consolidated:

// This will send a merged request:
graph.commit('buildPage').then(function (response) {
  // All base fields will be in response return.
  console.log(response.post)
  console.log(response.commentsOfPost)
})

And this will create only one request:

ss2

This will create the following merged query generated by graphql.js:

query ($merge024533__id: ID!, $merge141499__postId: ID!) {
  merge024533_post: {
    post(id: $merge024533__id) {
      id
      title
      text
    }
  }
  merge141499_commentsOfPost: {
    comments(postId: $merge141499__postId) {
      comment
      owner {
        name
      }
    }
  }
}

And variables will be generated, too:

{
  "merge024533__id": 123,
  "merge141499__postId": 123
}

The merge{number} aliases won't be passed into your responses, since they will be used for initial seperation.

⚠️ Important Restriction: You cannot use multiple root fields using query merging. ⚠️ Important Restriction: Autodeclaration is on by default, do not use alwaysAutodeclare: true.

Debugging

You can pass debug: true to options parameter to get a console output looks like following:

[graphql]: POST http://localhost:3000/graphql
  QUERY: query ($email: String!, $password: String!) {
    auth(email: $email, password: $password) {
      .. login_auth
    }
  }

  fragment info on User { hasPin }
  fragment login_auth on User { token, ...info }

  VARIABLES: {
    "email": "john@doe.com",
    "password": "123123"
  }

  sending as form url-data

Advanced

Using with Vue.js

Create a GraphQLProvider.js.

import graphql from 'graphql.js';

/* eslint-disable no-underscore-dangle */
export default {
  install(Vue, url, options) {
    Vue.mixin({
      created() {
        this._graph = graphql(url, options);
      },
    });
    Object.defineProperty(Vue.prototype, '$graph', {
      get() {
        return this._graph;
      },
    });
  },
};

And then you can use this with your Vue app:

import Vue from 'vue';
import GraphQLProvider from './GraphQLProvider';

Vue.use(GraphQLProvider, 'http://localhost:3000/graphql', {
  headers: {
    // headers...
  },
});

// ... in your Vue VM
data() {
  return {
    hello: '',
  };
},
methods: {
  makeSomeQuery() {
    this.$graph.query(`{hello}`).then(response => {
      this.hello = response.hello;
    });
  },
}

Change POST Method

As default, GraphQL.js makes a POST request. But you can change the behavior by setting asJSON.

var graph = graphql("http://localhost:3000/graphql", {
  asJSON: true
});

Using with graphql-tag

graphql-tag converts GraphQL query strings to AST. You can use graphql-tag with GraphQL.js

graph.query(gql`query { name }`)

Using graphql-tag will not allow you to use auto declaration and nested fragments syntaxes since these are not valid query syntax for GraphQL but only for this library.

Change Url Anywhere

You can change url anywhere with setUrl method.

var graph = graphql("http://localhost:3000/graphql", {
  asJSON: true
});

// Change url
graph.setUrl('http://www.example.com')

// Run query
graph.query(`{ name }`)

Todo App Example

A CRUD ToDo app example code to show how to use GraphQL.js. An implementation can be found at f/graphql.js-demo

var graph = graphql("/graphql", {
  alwaysAutodeclare: true,
  fragments: {
    todo: `on Todo {
      id
      text
      isCompleted
    }`
  }
})

function getTodos() {
  return graph.query.run(`allTodos {
    ...todo
  }`)
}

function addTodo(text) {
  return graph.mutate(`todoAdd(text: $text) {
    ...todo
  }`, {
    text: text
  })
}

function setTodo(id, isCompleted) {
  return graph.mutate(`todoComplete(
    id: $id,
    status: $isCompleted
  ) {
    ...todo
  }`, {
    id: id,
    isCompleted: isCompleted
  })
}

function removeTodo(id) {
  return graph.mutate(`todoRemove(
    id: $id
  ) {
    ...todo
  }`, {
    id: id
  })
}

Download Details:

Author: F
Source Code: https://github.com/f/graphql.js 
License: MIT license

#javascript #graphql #client #relay