之前闲着无聊写的一个 Redux 项目,今天突然想把它做成动态数据源,很早之前使用 Gatsby 的时候尝试过 GraphQL 觉得不错,所以就试着集成了一下。

Server

轮子: express-graphql

安装一下然后用下面的代码搭出 Skeleton Framework

  var express = require('express');
  var graphqlHTTP = require('express-graphql');
  var { buildSchema } = require('graphql');

  // Construct a schema, using GraphQL schema language
  var schema = buildSchema(`
    type Query {
      hello: String
    }
  `);

  // The root provides a resolver function for each API endpoint
  var root = {
    hello: () => {
      return 'Hello world!';
    },
  };

  var app = express();
  app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
  }));
  app.listen(4000);
  console.log('Running a GraphQL API server at localhost:4000/graphql');

放到 index.js 然后 node 跑起来即可

浏览器直接打开 localhost:4000/graphql 就是 graphiql 的界面,这玩意算是半个 IDE 吧

Client

轮子:react-apollo

因为之前用了 Redux,只需要修改一些地方就行。核心就是用一个 Provider 包裹之前的内容。

 src/index.js | 34 +++++++++++++++++++++++++++++-----
 1 file changed, 29 insertions(+), 5 deletions(-)

diff --git a/src/index.js b/src/index.js
index aabf911..12227bd 100644
--- a/src/index.js
+++ b/src/index.js
@@ -6,16 +6,40 @@ import registerServiceWorker from './registerServiceWorker';
 import { createStore } from 'redux'
 import { Provider } from 'react-redux';
 import Reducer from './reducers'
+import gql from "graphql-tag";
+import { ApolloProvider } from "react-apollo";
+import ApolloClient from "apollo-boost";
 
 
 const store = createStore(
-    Reducer, /* preloadedState, */
-    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
+  Reducer, /* preloadedState, */
+  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
 );
 
+const client = new ApolloClient({
+  uri: "https://w5xlvm3vzz.lp.gql.zone/graphql"
+});
+
+
+client
+  .query({
+    query: gql`
+      {
+        rates(currency: "USD") {
+          currency
+        }
+      }
+    `
+  })
+  .then(result => console.log(result));
+
+
+
 ReactDOM.render(
-    <Provider store={store}>
+    <ApolloProvider client={client}>
+  <Provider store={store}>
       
-    </Provider>,
-    document.getElementById('root'));
+  </Provider>
+    </ApolloProvider>,
+  document.getElementById('root'));
 registerServiceWorker();
  • 文章标题: 《React + Redux + GraphQL 环境搭建》
  • 发布日期: 2018-08-05
  • 文章分类: Tech
  • 相关标签: JS NodeJS Redux