iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 21
0
Modern Web

線上讀書會-2016 年學 JavaScript 是一種什麼樣的體驗系列 第 21

reactjs + graphQL 另外12/27 還有一場相關 Functional Programming 歐

  • 分享至 

  • xImage
  •  

polo 不專業分享 graphQL 心得分享篇
https://www.youtube.com/watch?v=oi2hfP5WmV8

關於要如何學習GrapHQL polo 這邊提供一個網站
https://learngraphql.com/basics/introduction

  1. Introduction to GraphQL
    這邊主要說明GraphQL的功能
    目前以自己的學習經驗來說,整理幾個好處GraphQL 他的restful 開口只有一個,相對的在大幅修改中比較不會犯錯,透過簡單格式可以做到複雜的關聯語法,因為開口只有一個所以對開口 做好一次性的保護即可

  2. Let’s Learn GraphQL

這邊有提供沙箱連結,然後跟你說要有Es6的一些知識

  1. Querying GraphQL

透過沙箱開始玩 簡單query語法


{
  latestPost {
    title,
    summary
  }
}

然後回傳,前端就是這樣簡單

{
  "data": {
    "latestPost": {
      "title": "New Feature: Tracking Error Status with Kadira",
      "summary": "Lot of users asked us to add a feature to set status for errors in the Kadira Error Manager. Now, we've that functionality."
    }
  }
}

也可以透過參數的方法

{
  recentPosts(count: 5) {
    title
  }
}

  1. Invoking Mutations

這邊新增刪除修改都叫做Mutations,前端調用發法如下

mutation {
  createAuthor(
    _id: "john",
    name: "John Carter",
    twitterHandle: "@john"
  ) {
    _id
    name
  }
}
  1. Fragments
    把重複的片段抽離出來
{
  arunoda: author(_id: "arunoda") {
    _id,
    name,
    twitterHandle
  },
  pahan: author(_id: "pahan") {
    _id,
    name,
    twitterHandle
  },
  indi: author(_id: "indi") {
    _id,
    name,
    twitterHandle
  }
}

抽離後

{
  arunoda: author(_id: "arunoda") {
    ...authorInfo
  },
  pahan: author(_id: "pahan") {
    ...authorInfo
  },
  indi: author(_id: "indi") {
    ...authorInfo,
    memo  <----額外還可以擴充
  }
}

fragment authorInfo on Author {
  _id,
  name,
  twitterHandle
}
  1. Query Variables

參數變數可以這樣設定然後裡面的Code都吃得到

query getFewPosts($postCount: Int!, $commentCount: Int) {
  recentPosts(count: $postCount) {
    title,
    ...comments
  }
}

fragment comments on Post {
  comments(limit: $commentCount) {
    content
  }
}
  1. Defining Queries
    開始後端設定 Queeries 要這樣定義
    要先訂一個Type
const Post = new GraphQLObjectType({
  name: "Post",
  description: "This represent a Post",
  fields: () => ({
    _id: {type: new GraphQLNonNull(GraphQLString)},
    title: {type: new GraphQLNonNull(GraphQLString)},
    content: {type: GraphQLString}
  })
});

實際上在對應前端要長這樣

const Query = new GraphQLObjectType({
  name: 'BlogSchema',
  description: "Root of the Blog Schema",
  fields: () => ({
    posts: {
      type: new GraphQLList(Post),  <---這個Type是上面的
      resolve: function() {
        return PostsList;   
      }
    }
  })
});

  1. Defining Mutations
    前端調用要加上Mutations
 mutation insertFirstPost {
  post: createPost(
    title: "GraphQL is Awesome",
    content: "Yep, it's purely awesome."
  ) {
    _id,
    title
  }
}

實際上後端是這樣
GraphQLNonNull 必填
GraphQLObjectType 必要型態

const Mutation = new GraphQLObjectType({
  name: "BlogMutations",  <--前端沙箱會看到的名稱
  description: "Mutations of our blog",  <--前端沙箱會看到的敘述
  fields: () => ({
    createPost: {
      type: Post, <-- 這邊使用上面定義好的post即可
      args: {  <--傳入參數
        title: {type: new GraphQLNonNull(GraphQLString)},  
        content: {type: new GraphQLNonNull(GraphQLString)}
      },
      resolve: function(source, args) {

//這邊可以接資料庫 如果是用react 可以用 async await ,以下是用immutable方式

        let post = Object.assign({}, args);
        // Generate the _id
        post._id = `${Date.now()}::${Math.ceil(Math.random() * 9999999)}`;
        // Assign a user
        post.author = "arunoda";

        // Add the Post to the data store
        PostsList.push(post);

        // return the new post.
        return post;
      }
    }
  })
});
  1. Executing GraphQL Queries
    匯入所有型態
import {
  // These are the basic GraphQL types
  GraphQLInt,
  GraphQLFloat,
  GraphQLString,
  GraphQLList,
  GraphQLObjectType,
  GraphQLEnumType,

  // This is used to create required fields and arguments
  GraphQLNonNull,

  // This is the class we need to create the schema
  GraphQLSchema,

  // This function is used execute GraphQL queries
  graphql
} from 'graphql';
const Query = new GraphQLObjectType({
  name: 'RootQueries',
  fields: () => ({
    echo: {
      type: GraphQLString,
      args: {
        message: {type: GraphQLString}
      },
      resolve(rootValue, args) {  <--多參數也可以這樣寫
        return `received: ${args.message}`;
      }
    }
  })
});

const Schema = new GraphQLSchema({  <-- 一定要加入
  query: Query
});

透過 babel 可以使用es6語法

babel-node index.js --presets "es2015"
  1. Using A Real Data Source
    使用mongoDB 來做CRUD
const mongo = require('promised-mongo');
// You can use any MONGO_URL here, whether it's locally or on cloud.
const db = mongo('mongodb://localhost/mydb');
const authorsCollection = db.collection('authors');

resolve 之後 authorsCollection 就是mongoDB的部分 其他都一樣歐

const Mutation = new GraphQLObjectType({
  name: "Mutations",
  fields: {
    createAuthor: {
      type: Author,
      args: {
        _id: {type: new GraphQLNonNull(GraphQLString)},
        name: {type: new GraphQLNonNull(GraphQLString)},
        twitterHandle: {type: GraphQLString}
      },
      resolve: function(rootValue, args) {
        let author = Object.assign({}, args);
        return authorsCollection.insert(author)
          .then(_ => author);
      }
    }
  }
});

  1. More on GraphQL

GraphQL website
http://graphql.org/
GraphQL spec
http://facebook.github.io/graphql/

另外更專業的在這邊
[線上讀書會] 承澤 主講 React graphQL + Relay 入門
https://www.youtube.com/watch?v=K0WEazN9Nf4

Relay 利用了 optimistic ui 增加了使用者體驗 加快速度流程,詳細用法請參考承澤大大的影片

繼上次Andy大大 的 Reactjs workshop 已經很多人 一天入魂 Reactjs了,
12/27 還有一場相關 Functional Programming 主題 由 孟偉大大 來 主講


上一篇
reactnative 實戰
下一篇
reactjs 配rx.js 也不錯,入門推薦影片與文章推薦
系列文
線上讀書會-2016 年學 JavaScript 是一種什麼樣的體驗30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言