GraphQL

GraphQL je query (query=upit, google translate) jezik. Query znači u istom smislu kao i query za bazu podataka. Dakle, daj mi određenu tablicu, stupac i redove. Cilj i svrha ovoga je pojednostavniti rad sa REST API-jima. Sa GraphQL API-jem dolazi i vizualno sučelje gdje se može vidjeti schema odnosno arhitektura cijelog API-ja.

Primjer

Za primjer ćemo koristiti http://api.spacex.land/graphql/

Ako napišemo:

{capsules {
  id
}}

Dobivamo listu svih “kapsula”.

{
  "data": {
    "capsules": [
      {
        "id": "C105"
      },
      {
        "id": "C101"
      },
...

Jednostavno! Hajdemo složiti malo kompliciraniji upit:

{
  capsules {
    id
    landings
    status
    missions {
      name
    }
  }
}

Rezultat:

{
  "data": {
    "capsules": [
      {
        "id": "C105",
        "landings": 1,
        "status": "unknown",
        "missions": [
          {
            "name": "CRS-3"
          }
        ]
      },
      {
        "id": "C101",
        "landings": 1,
        "status": "retired",
        "missions": [
          {
            "name": "COTS 1"
          }
        ]
      },
...

Kako koristiti u projektu?

React

npx create-react-app my-app
cd my-app
npm install @apollo/client graphql
npm start

index.js

import React from "react";
import ReactDOM from "react-dom";
import { ApolloProvider, ApolloClient, InMemoryCache } from "@apollo/client";

import App from "./App";

const client = new ApolloClient({
  uri: "https://api.spacex.land/graphql/",
  cache: new InMemoryCache()
});

const rootElement = document.getElementById("root");
ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  rootElement
);

App.js

import React from "react";
import { useQuery, gql } from "@apollo/client";

const query = gql`
{
  capsules {
    id
    landings
    status
    missions {
      name
    }
  }
}
`;

export default function App() {
  const { data, loading, error } = useQuery(query);

  if (loading) return "Loading...";
  if (error) return <pre>{error.message}</pre>

  console.log(data);

  return (
  
    <div>
      <h1>SpaceX Capsules</h1>
      <ul>
        {data.capsules.map((capsule) => (
          <li key={capsule.id}>{capsule.id} => {capsule.status}</li>
        ))}
      </ul>
    </div>
  );
    
}

Vanilla JS

Za obični JS koristimo lib:

https://github.com/f/graphql.js

Iz tog paketića potrebna nam je datoteka “graphql.min.js” i “index.html” ovog sadržaja:

<!doctype html>
<head>
   <meta charset="utf-8">
   <title></title>
   <meta name="description" content="">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <script src="graphql.min.js"></script>
</head>
<body onload="main()">
   <h1>Hello World</h1>
   <main></main>
</body>
</html>
<script>
   const main = async () => {
         var graph = graphql("https://api.spacex.land/graphql/", {
           alwaysAutodeclare: true,
           asJSON: true,
           debug: true
         })
   
   
   	    var capsulesData = graph(` query      
   			{
   			  capsules {
   				id
   				landings
   				status
   				missions {
   				  name
   				}
   			  }
   			}       
         `);
         
         const capsulesGql = await capsulesData();
   	  const capsules = capsulesGql.capsules;		
         let mainElement = document.getElementsByTagName('main')[0];	
   	
   	  for (let i=0; i<capsules.length; i++){
   		  let key = capsules[i].id;
   		  let status = capsules[i].status;
   		  let landings = capsules[i].landings;
   		  
   		  mainElement.innerHTML += `
   		    <div key="${key}"> ${key} ${status} ${landings}</div>
   		  `;
   	  }
   }
   	
</script>

Odgovori

Vaša adresa e-pošte neće biti objavljena.

Previous post I took your sun with hands and put it on my head
Next post Amiga

🗣 You can translate this site using Chrome built-in translator.