0%

17. GraphQL

GraphQL

  • more efficient
  • alternative to REST API
  • Not a Framework!
  • similar to router

REST

  • pattern, standard for APIs
  • interface that tells the external how to get the datas
  • have endpoints (e.g. ‘/messages’)
/teams/CH
send all the info

–> moduler
/teams/CH/info
/teams/CH/players
/teams/CH/matches

  • Query Language (Standard)

order also matches!

Implementation

  1. Schema
    • Types

id => unique
[]! => need [] type, you need to pass [] thing
team: Team! => team is related to type Team (Team: object)

  1. Resolvers
  • Scalar Types
    (Built-In)
  • Int
  • Float
  • String
  • Boolean
  • ID
    (Custom Scalar)
  • Date, Url, EmailAddress …
    id, name, age: primitive type
    team: object -> sub-doc. type => repeat the same process to find the type
  1. Queries & Mutations
    one single endpoint

-> perform queries

  • Sub-Selection
    pass the object to the type -> give the right interface of information of that object
  • have to ask the property of the object
  • Arguments

  • Variables

put “DEF” into $position var

      • fetching data - - -
        👇
      • change (mutate) data - - -
  • Mutations

  • another type of action like query that performs changes on the resources
  • diff is like GET - POST: doesn’t change anything in the server - change something in the server
    -> do st that doesn’t suppose to do, run semantic, perform changes by manipulating inside my DB
  1. create new data POST
  2. update existing data PUT
  3. delete existing data DELETE

name, position: response
1st: input type checking -> 2nd: actually executing the mutation

  • ID: created internally by the program
  • send the request to the root (4000-graphQL as the endpoint)
  • reliable, flexible
  • Execution
    search for syntax error

undefined height -> null, name ~ pass height ~ go inside team obj

  • Resolvers
    Schema: define, Resolver: interact => interplay to call server flexibly

get id:42 from upper example

  • obj : the previous resolved obj, parent element that has been previously resolved
  • args : the arguments object for the field in the query, include id .. all the args that we want to pass
  • context : shared object provided to every resolver, communicate and share information, later function can access to it (i.e. ctx in Koa)
  • info : extra information about the current query to mutate, etc.

Implementation

typeDefs: routers
resolvers: controllers

  • index.js

  • typeDefs.js

  • resolvers.js

not using obj => replace it with _
👇

  • resolvers.js

※ express / koa : REST API = apollo-server : gql