Graphql Schema

Graphql Schema

GraphQL the holy contract between client and server @nodkz Pavel Chertorogov with GraphQL since 2015 3 Client-server intro 4 Intro Client-server apps Redis HTML XML PostgreSQL REST HTTP ES URL JSON MongoDB form-data WS etc… MySQL url-encoded etc… etc… SERVER CLIENTS Java Python iOS .NET NodeJS Go Browsers Android etc… C# Ruby etc… 5 Intro Backend capabilities Invoice Customer id id 1 customer_id * name amount date Simple DB Schema Diagram 6 Intro Wordpress 4.4.2 Schema (12 tables) Drupal8 Schema (60 tables) SalesLogix Schema (168 tables) 7 Intro … and even more Monster with 333 tables Order table (138 fields) Hi-Res: http://anna.voelkl.at/wp-content/uploads/2016/12/ce2.1.3.png Magento: Commerce Solutions for Selling Online (333 tables) 8 Intro How to create API for this db-schema HELL? 9 Intro Wait! I have a better plan! 10 GraphQL Basics This is GraphQL Schema Wikipedia MBT-70 schema 11 GraphQL basics 12 GraphQL Basics GraphQL – is a … query query language executor + C# for APIs on Schema .NET Python NodeJS for Frontenders for Backenders Ruby Go etc… 13 GraphQL Basics GraphQL Query Language GraphQL query Response in JSON 14 GraphQL Basics GraphQL Query Language GraphQL query Response in JSON 15 GraphQL Basics GraphQL Schema GraphQL Schema Single entrypoint Query Mutation Subscription Type Type Type READ (stateless) WRITE (stateless) EVENTS (stateful) 16 GraphQL Basics ObjectType Type Type Invoice Name Name id Field Field 1 customerId Field amount Field Field N date Field 17 GraphQL Basics Field Config Type Field 1 Field N Type Scalar or Object Type which returns resolve Resolve Function with fetch logic from any data source Args Set of input args for resolve function Description Documentation DeprecationReason Field hiding 18 GraphQL Basics Relations between types Type Type Invoice Customer Field id Int * 1 id id Field Int customerId Field Field String Int name Field amount Decimal date Field Date 19 GraphQL Basics One does not simply draw a relation line in GraphQL! Invoice * 1 Customer 20 GraphQL Basics Relation is a new field in your Type Type Type Invoice Customer id Field Field select * from invoice where id customerId Field customer_id = {customer.id} name Field Field amount Resolve invoices Field Array<Invoice> date Field customer Field Resolve Customer select * from customer where id = {invoice.customerId} 21 GraphQL Basics — Limit? Offset? Sort? Additional filtering? — No problem, add them to args and process in resolve function! Type Type Invoice Customer select * from invoice where id Field Field customer_id = {customer.id} id customerId Field limit {args.limit} name Field Field amount Resolve invoices Field Args Array<Invoice> date Field Limit: 3 22 GraphQL Basics Resolve function function (source, args, context, info ) { // access logic (check permissions) // fetch data logic (from any mix of DBs) // processing logic (operations, calcs) return data; } ANY PRIVATE BUSINESS LOGIC… 23 GraphQL Basics Schema Introspection printSchema(schema); // txt output (SDL format) graphql(schema, introspectionQuery); // json output (AST) Just remove Resolve functions (private business logic) and you get PUBLIC schema 24 GraphQL Basics Schema Introspection example SDL format types type Customer { • id: Int (txt) • fields name: String args # List of Invoices for current Customer • invoices(limit: Int): [Invoice] • docs } resolve • # Show me the money • directives type Invoice { input types id: Int • customerId: Int • enums amount: Decimal # Customer data for current Invoice • interfaces customer: Customer • unions oldField: Int @deprecated(reason: "will be removed") } 25 GraphQL Basics Schema Introspection provides an ability for awesome tooling: • Autocompletion • Query validation • Documentation • Visualization • TypeDefs generation for static analysis (Flow, TypeScript) GraphiQL — graphical interactive in-browser GraphQL IDE Eslint-plugin-graphql — check queries in your editor, CI Relay-compiler — generates type definitions from queries 26 GraphQL Basics Type definition example const QueryType = new GraphQLObjectType({ name: 'Query', fields: () => ({ films: { type: new GraphQLList(FilmType), args: { limit: { type: GraphQLInt, defaultValue: 5 }, }, resolve: async (source, args) => { const data = await loadData(`https://swapi.co/api/films/`); return data.slice(0, args.limit); }, }, ...otherFields, }), }); 27 GraphQL Basics Type definition example const QueryTypeQuery = new GraphQLObjectType({ Type Type name: 'Query', fields: () => ({ Field 1 filmsfield : { typetype : new GraphQLList(FilmType), Field N argsargs : { limit: { type: GraphQLInt, defaultValue: 5 }, Type }, Args resolveresolve : async (source, args) => { const data = await loadData(`...`); Resolve return data.slice(0, args.limit); }, Description }, FieldConfig ...otherFields, DeprecationReason }), }); 28 GraphQL Basics Don’t forget to read about • input types • directives • enums • interfaces • unions • fragments http://graphql.org/learn/ 29 Backend capabilities Client requirements https://graphql-compose.herokuapp.com/ GraphQL Demo 30 Fetch Network sub-fetch 1 Network RESULT Delay Delay sub-fetch 2 REST API sub-fetch N - Sub-fetch logic on client side (increase bundle size) - Over-fetching (redundant data transfer/parsing) Query Network RESULT Delay GraphQL + No additional network round-trip (speed) + Exactly requested fields (speed) + Sub-fetch logic implemented on server side 31 Intro A copy from one of the previous slides… Client-server apps Redis HTML XML PostgreSQL REST HTTP ES URL JSON MongoDB form-data WS etc… MySQL url-encoded etc… etc… SERVER CLIENTS Java Python iOS .NET NodeJS Go Browsers Android etc… C# Ruby etc… 32 GraphQL – is a query language for APIs Specification for describing the capabilities and requirements of data models Redis PostgreSQL for client‐server apps ES HTTP MongoDB WS MySQL SCHEMA Pretty QUERY INTROSPECTION etc… etc… Language SERVER CLIENTS NodeJS Go .NET Browsers iOS Java Ruby C# Python etc… etc… Android 33 For frontend developers Static Analysis 34 Static Analysis Static type checks � PRODUCTIVITY • Types checks • Functions call checks • Auto-suggestion • Holy refactoring Static program analysis is the analysis of computer software that is performed without actually executing programs 35 Static Analysis SERVER JS CLIENT GraphQL File with GraphQL Query Schema and Response processing Let’s turbo-charge our client apps static analysis with GraphQL queries 36 Static Analysis SERVER JS CLIENT GraphQL File with GraphQL Query Schema and Response processing 1 Schema Introspection 37 Static Analysis SERVER JS CLIENT GraphQL File with GraphQL Query Schema and Response processing 1 Schema 2 Introspection Relay-compiler Watcher Apollo-codegen 38 Static Analysis SERVER JS CLIENT GraphQL File with GraphQL Query Schema and Response processing 1 File with Response Type Defs Schema 2 3 Introspection Watcher Hey, you have a wrong Query 39 Static Analysis SERVER JS CLIENT GraphQL File with GraphQL Query Schema and Response processing 4 1 File with Response Type Defs Schema 2 3 Introspection Watcher 40 Static Analysis SERVER JS CLIENT GraphQL File with GraphQL Query Schema and Response processing 4 1 File with Response Type Defs Schema 2 3 5 Introspection Watcher Flowtype or TypeScript 41 Static Analysis SERVER JS CLIENT GraphQL File with GraphQL Query Schema and Response processing 4 1 File with Response Type Defs Schema 2 3 5 Introspection Watcher Flowtype Houston, we have a Type Check problem 6 at line 19287 col 5: possible undefined value 42 Static Analysis DEMO GraphQL Query Generated Response Type Def Crappy Code Flow typed Code Flow error 43 Balance.js Static Analysis GraphQL Query import { graphql } from 'react-relay'; const query = graphql` query BalanceQuery { viewer { JS CLIENT cabinet { File with GraphQL Query accountBalance and Response processing 4 } File with Response Type Defs } 3 5 }`; Watcher Flowtype 44 __generated__/BalanceQuery.graphql.js Static Analysis Generated Response Type Def JS CLIENT File with GraphQL Query and Response processing /* @flow */ 4 File with /*:: Response Type Defs export type BalanceQueryResponse = {| 3 5 +viewer: ?{| Watcher Flowtype +cabinet: ?{| +accountBalance: ?number; |}; Writer time: 0.53s [0.37s compiling, …] |}; Created: - BalanceQuery.graphql.js |}; Unchanged: 291 files */ Written default in 0.61s 45 Balance.js Static Analysis import { graphql } from 'react-relay'; Crappy Code import * as React from 'react'; export default class Balance extends React.Component { render() { const { viewer } = this.props; return <div> Balance {viewer.cabinet.accountBalance} JS CLIENT File with </div>; GraphQL Query and Response processing } 4 } File with Response Type Defs const query = graphql`query BalanceQuery { 3 5 viewer { cabinet { accountBalance } } Watcher Flowtype }`; 46 Balance.js Static Analysis Flow typed Code import { graphql } from 'react-relay'; import * as React from 'react'; import type { BalanceQueryResponse } from './__generated__/BalanceQuery.graphql'; type Props = BalanceQueryResponse; export default class Balance extends React.Component<Props> { render() { JS CLIENT const { viewer } = this.props; File with GraphQL Query return <div>Balance {viewer.cabinet.accountBalance}</div>; and Response processing } 4 } File with const query = graphql`query BalanceQuery { Response Type Defs viewer { cabinet { accountBalance } } 3 5 }`; Watcher Flowtype 47 Balance.js Static Analysis /* @flow */ Flow typed Code import { graphql } from 'react-relay'; import * as React from 'react'; import type { BalanceQueryResponse } from './__generated__/BalanceQuery.graphql';

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    95 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us