Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Data Management with Next.js & GraphQL (Zeit Day Berlin 2017)

Data Management with Next.js & GraphQL (Zeit Day Berlin 2017)

Johannes Schickling

September 23, 2017
Tweet

More Decks by Johannes Schickling

Other Decks in Programming

Transcript

  1. Johannes Schickling • Based in Berlin/San Francisco • @graphcool (GraphQL

    Backend Platform) • Love cutting-edge technology @_schickling @schickling
  2. Use Case: Webshop • An Item has the following fields:

    • id: ID • name: String • price: Float • ratingInfo: Object { "id": "cj1s966c8hudb0139bg5qjmna", "price": 2500, “name": "Macbook Pro 2016", "ratingInfo": null }
  3. Status Quo: RESTful APIs GET https://api.shop.com/items [{ "id": "cj1s966c8hudb0139bg5qjmna", "price":

    2500, "name": "Macbook Pro 2016" }, { "id": "cj1s96cpohufg0139keoewq22", "price": 800, "name": "iPhone" }, { "id": "cj1s97mpwhuo10139salvx5wn", "price": 1700, “name": "Macbook Air 2015" }]
  4. Problem: Related data? • Strategy 1: Flat endpoints N+1 query

    problem • Strategy 2: Nested endpoints
  5. Problem: Related data? • Strategy 1: Flat endpoints N+1 query

    problem • Strategy 2: Nested endpoints GET https://api.shop.com/items-with-ratings
  6. Problem: Related data? • Strategy 1: Flat endpoints N+1 query

    problem • Strategy 2: Nested endpoints Data overfetching
  7. GraphQL Query query { allItems { name ratingInfo { count

    averageRating } } } { "data": { "allItems": [{ "name": "iPhone 6", "ratingInfo": { "count": 115, "averageRating": 4.7 } }, { “name": "Macbook 2016", "ratingInfo": { "count": 29, "averageRating": 4.9 } }] } }
  8. GraphQL Mutation mutation { createItem( name: "iPhone 7" price: 900

    ) { id } } { "data": { "createItem": { "id": "cj1sbo2phrmpq0124t63uyo5f" } } }
  9. GraphQL Subscription subscription { Item { operation node { id

    name } } } [{ "data": { "Item": { “operation": "CREATED”, "node": { "id": 115, "name": "Macbook 2016" } } } }]
  10. GraphQL SDL type Item { id: ID! @isUnique price: Float!

    name: String! ratingInfo: RatingInfo! @relation(name: "ItemRatingInfo") } type RatingInfo { id: ID! @isUnique count: Int! averageRating: Float! item: Item! @relation(name: "ItemRatingInfo") } • Describes data model • Syntax: GraphQL SDL • Typesystem
  11. Data Management • Data Fetching • Direct database access •

    API Layer • Local State Management • Props/State • Redux
  12. Data Fetching: Direct database access • Problems: • Strong coupling

    • Insecure export default class extends React.Component { static async getInitialProps ({ req }) { if (req) { const { db } = req // Note that `db` above comes from express middleware const list = await db.collection(‘Book’).find() .sort({ createdAt: -1 }).toArray() return { list } } return { list: [] } } // … }
  13. Data Fetching: API Layer • Format: REST or GraphQL •

    Mapping needed from API to Database (ORM)
  14. GraphQL Clients • Popular GraphQL clients: Apollo & Relay •

    Features: • Manages caching & network layer (HTTP, real-time, offline) • View-layer integration • Tooling: Build-time query validation & optimization
  15. Apollo Client • Install: `npm install apollo-client react-apollo` • Usage:

    • Configure `ApolloProvider` • Component wrapping • Bonus: SSR via `getInitialProps`
  16. import { ApolloClient, createNetworkInterface } from 'react-apollo'; const client =

    new ApolloClient({ networkInterface: createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/webshop', }), });
  17. import { gql, graphql } from 'react-apollo'; function App({ data:

    { allItems } }) { return ( <ul> {allItems.map(item => <li key={item.id}>{item.name}</li>)} </ul> ); } export default graphql(gql` query AllItems { allItems { id name } } `)(App);
  18. Recap • Data management stack: GraphQL API layer & Apollo

    Client • Problem: Introduces a lot of complexity (code/infrastructure) • Solution: Better abstractions & workflows needed
  19. What is Graphcool? • GraphQL Backend Development Platform • Technology:

    • Creates GraphQL API based on your data model • Framework to implement auth, permissions & business logic • Platform: • Database & API hosting • Collaboration
  20. API • SQL-like flexibility: Querying, filtering, pagination, sorting, … •

    Powerful real-time API • Supports all GraphQL clients (no SDK needed)
  21. Auth & Permissions • Authentication: • Supports every auth provider:

    Facebook, Twitter, Auth0… • Implement your own auth method • Authorization: • Powerful permission system (based on data graph or imperative)
  22. Functions • Used to implement business logic and extend API

    • Supports webhooks or managed function • Enables event-driven architecture
  23. Webshop Demo • List all items & add to shopping

    cart • Checkout process (authentication via Auth0) • Payment via Stripe & send confirmation via Mailgun
  24. What we’ll do 1. Understand app & code base 2.

    Setup Project 1. Create Graphcool project 2. Configure service credentials via env vars 3. Seed initial data 4. Deploy code via now & configure webhooks 3. Run app
  25. Code Base • Frontend: Next.js • pages, components, lib •

    Backend: Graphcool & Node • Config: graphcool.yml & types.graphql • Logic: pay.js & sendConfirmEmail.js
  26. Checkout Process • Authenticate `User` via `authenticateAuth0User` mutation • Add

    `Item`s to `Basket` • Create `Order` • Pay via `pay` mutation - sets `orderedAt` timestamp • Triggers `sendCustomerMail`
  27. Learning GraphQL • How to GraphQL: howtographql.com • Firebase vs

    GraphQL: bit.ly/2xthzjR • GraphQL Newsletter: graphqlweekly.com
  28. Coming soon… • New beta available: • Local development workflow

    • Learn more: graph.cool/forum • Upcoming announcement: • Run Graphcool locally • Deploy on your own servers