Коммуникация клиента и сервера

Занятие 12

Профессия
Node.js & React.js developer
продвинутый курс

1

  • Коммуникация и проблемы связанные с ней
  • Решения для коммуникация
  • GraphQL
  • Пару слов

План

1

Комуникация

и проблемы связанные с ней

2

Решения

для хорошей коммуникации

Amelisa

Amelisa

let app = express()

app.use(store.modelMiddleware())

app.use((req, res, next) => {
  let model = req.getModel()
})

//////

let model = store.createModel()

let $user = model.doc('user', '1')
let $items = model.query('items', {})

await model.subscribe($user, 'users.2', ['users', '3'], $items, 'todos', ['products', {}])

let user1 = model.get('users.1')
let user2 = model.get('users.2')
let todos = model.query('todos', {}).get()

Swarm.js

Swarm.js

Swarm.js

var sync = require('swarm-syncable');
var Model = sync.Model;
var Host = sync.Host;

// var replica = new Replica({upstream: 'ws://localhost:8000'});
// a replica manages logs and synchronizes to the upstream replica
// in this example, we'll create a replica implicitly through Host

// manages objects
new Host({
    replica: true,
    upstream: 'ws://localhost:8000'
});
var mouse = new swarm.Model({x:1, y:2});
mouse.on('change', function() {
    console.log('mouse x:', mouse.x, 'y:', mouse.y);
});
mouse.set({x:3, y:4});

Logux

Replace AJAX-REST by Redux actions synchronization between client and server

GraphQL

Relay

Apollo

Apollo Client

Vulcan.js

3

GraphQL

Restful

JSON API

{
  "links": {
    "self": "http://example.com/articles",
    "next": "http://example.com/articles?page[offset]=2",
    "last": "http://example.com/articles?page[offset]=10"
  },
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!"
    },
    "relationships": {
      "author": {
        "links": {
          "self": "http://example.com/articles/1/relationships/author",
          "related": "http://example.com/articles/1/author"
        },
        "data": { "type": "people", "id": "9" }
      },
      "comments": {
        "links": {
          "self": "http://example.com/articles/1/relationships/comments",
          "related": "http://example.com/articles/1/comments"
        },
        "data": [
          { "type": "comments", "id": "5" },
          { "type": "comments", "id": "12" }
        ]
      }
    },
    "links": {
      "self": "http://example.com/articles/1"
    }
  }],
  "included": [{
    "type": "people",
    "id": "9",
    "attributes": {
      "first-name": "Dan",
      "last-name": "Gebhardt",
      "twitter": "dgeb"
    },
    "links": {
      "self": "http://example.com/people/9"
    }
  }, {
    "type": "comments",
    "id": "5",
    "attributes": {
      "body": "First!"
    },
    "relationships": {
      "author": {
        "data": { "type": "people", "id": "2" }
      }
    },
    "links": {
      "self": "http://example.com/comments/5"
    }
  }, {
    "type": "comments",
    "id": "12",
    "attributes": {
      "body": "I like XML better"
    },
    "relationships": {
      "author": {
        "data": { "type": "people", "id": "9" }
      }
    },
    "links": {
      "self": "http://example.com/comments/12"
    }
  }]
}

GraphQL

Основные части

  1. GraphQL - спецификация
  2. GraphQL server - для обработки запросов к API
  3. GraphQL client - то что будет подключаться к endpoint.
  4. Tools

GraphQL

GraphQL

GraphQL

Запросы

query {
  stuff
}
query {
  stuff {
    eggs
    shirt
    pizza
  }
}
query {
  posts { # это массив
    title
    body
    author { # мы может пойти глубже
      name
      avatarUrl
      profileUrl
    }
  }
}
query {
  post(id: "123foo"){
    title
    body
    author{
      name
      avatarUrl
      profileUrl
    }
  }
}
query getMyPost($id: String) {
  post(id: $id){
    title
    body
    author{
      name
      avatarUrl
      profileUrl
    }
  }
}
query getMyPost($id: String) {
  post(id: $id){
    title
    body
    author{
      name
      avatarUrl
      profileUrl
    }
  }
}

GraphQL

Запросы

GitHub GraphQL API

GraphQL

Схемы

type Author {
  id: ID! # the ! means that every author object _must_ have an id
  firstName: String
  lastName: String
  posts: [Post] # the list of Posts by this author
}

type Post {
  id: ID!
  title: String
  author: Author
  votes: Int
}

# the schema allows the following query:
type Query {
  posts: [Post]
}

# we need to tell the server which types represent the root query
# and root mutation types. We call them RootQuery and RootMutation by convention.
schema {
  query: Query
}

GraphQL

Схемы, arguments

type Starship {
  id: ID!
  name: String!
  length(unit: LengthUnit = METER): Float
}

GraphQL

scalar types

  • Int: A signed 32‐bit integer.
  • Float: A signed double-precision floating-point value.
  • String: A UTF‐8 character sequence.
  • Boolean: true or false.
  • ID: The ID scalar type represents a unique identifier
  • Date *??
enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}
#Lists and Non-Null 

type Character {
  name: String!
  appearsIn: [Episode]!
  myField: [String!]
}

GraphQL

interfaces

interface Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
}
type Human implements Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
  starships: [Starship]
  totalCredits: Int
}

type Droid implements Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
  primaryFunction: String
}
union SearchResult = Human | Droid | Starship

GraphQL

review types

GraphQL

Resolvers (распознаватели)

Query: {
  post(root, args) {
    return Posts.find({ id: args.id });
  }
},
Post: {
  author(post) {
    return Users.find({ id: post.authorId})
  },
  commentsCount(post) {
    return Comments.find({ postId: post.id}).count()
  }
}

GraphQL

variables

GraphQL

Mutations (изменения)

mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) {
  createReview(episode: $ep, review: $review) {
    stars
    commentary
  }
}

{
  "ep": "JEDI",
  "review": {
    "stars": 5,
    "commentary": "This is a great movie!"
  }
}

GraphQL

fragments

GraphQL server

  1. Парсер запросов QL
  2. GraphQL
  3. Адаптер для БД
    1. PostgreSQL
    2. MongoDB
    3. ...
  4. Реализации под:
    1. Node.js
    2. PHP
    3. Python
    4. ... Java, C, C++, Go, .Net

GraphQL client

  1. Relay
  2. Apollo
    1. Apollo Client
    2. Apollo Client Dev Tools
    3. Коннектор: React-Apollo, Angular-Apollo
    4. По умолчанию Apollo-client сохраняет данных используя Redux
  3. Lokka
  1. Apollo - Andoid
  2. Apollo - iOS
  3. .Net

Apollo Client - Dev Tools

Graffiti

GraphiQL

4

Пару слов

Что почитать

Игорь Суворов

Thanks!

any questions?

программист-предприниматель

Коммуникация клиента и сервера

By Igor Suvorov

Коммуникация клиента и сервера

  • 1,058