0xql 中文文档教程

发布于 5年前 浏览 16 更新于 3年前

0xQL (ZeroEx GraphQL)

轻松将 GraphQL 支持添加到任何遵循 0x 标准中继层 API 规范的 0x 中继层。

Demo

在此处查看 GraphiQL 游乐场。 尝试创建一些查询、变更或订阅。

查看入门指南以获取示例查询和示例订阅以在演示游乐场试用.

Overview

0xQL 使开发人员能够快速构建可自动与现有 0x Relayer 集成的 GraphQL 服务器。 GraphQL 服务器镜像 0x Relayer 的 REST 和 WS API 的功能,但可以通过 GraphQL 的查询访问,突变,以及 订阅

Getting Started

Prerequisite

  • >= Node v10
  • >= Yarn v1.5

Installation

yarn add 0xql

Quick Start Guide

本指南将介绍如何设置与 RadarRelay 配合使用的 0xQL GraphQL 服务器。

安装依赖

$ yarn add 0xql apollo-server

项 创建一个 index.js 文件

$ touch index.js

将以下代码添加到 index.js

// index.js
const { ApolloServer } = require('apollo-server')
const { createReadyToUseResolvers, typeDefs } = require('0xql')

const APP_PORT = 4000
const REST_API_ENDPOINT = 'https://api.radarrelay.com/0x/v2'

const {
  queryResolver,
  mutationResolver,
  jsonResolver,
} = createReadyToUseResolvers(REST_API_ENDPOINT)

const resolvers = {
  Query: queryResolver,
  Mutation: mutationResolver,
  JSON: jsonResolver,
}

const server = new ApolloServer({
  typeDefs,
  resolvers,
})

// Start the GraphQL server
server.listen({ port: APP_PORT }, () =>
  console.log(
    `Server ready at http://localhost:${APP_PORT}${server.graphqlPath}`
  )
)

最后,启动服务器

node index.js

如果一切正常,您应该会在控制台中看到以下内容

Server ready at http://localhost:4000/

恭喜,您有自己的功能 0xQL GraphQL 实例指向 RadarRelay。 让我们试试吧!

导航到 http://localhost:4000 查看 GQL playground

尝试示例查询:

query GetOrders {
  orders {
    records {
      order {
        makerAssetData
        makerAssetAmount
        takerAssetData
        takerAssetAmount
      }
    }
    total
    page
    perPage
  }
}

Adding Subscriptions

除了获取数据使用查询和使用突变修改数据,GraphQL 规范支持第三种操作类型,称为订阅。 GraphQL 订阅是一种将数据从服务器推送到选择收听来自服务器的实时消息的客户端的方法。

如果您要添加订阅,请查看此处 的实施示例,它建立在我们刚刚制作的服务器上。

Subscriptions Demo

查看 [demo site]() 进行现场演示。

这是发送到 GraphQL 服务器的示例订阅:

subscription SubscribeToAllOrders {
  subscribeToOrders(type: subscribe, channel: orders, requestId: "1234") {
    payload {
      order {
        makerAddress
        makerAssetData
        takerAddress
        makerAssetAmount
        takerAssetData
        takerAssetAmount
        signature
        expirationTimeSeconds
      }
    }
  }
}

您将开始获得看起来像您刚刚请求的结构的传入订单流:

{
  "data": {
    "subscribeToOrders": {
      "payload": [
        {
          "order": {
            "makerAddress": "0x50f84bbee6fb250d6f49e854fa280445369d64d9",
            "makerAssetData": "0xf47261b00000000000000000000000000f5d2fb29fb7d3cfee444a200298f468908cc942",
            "takerAddress": "0x0000000000000000000000000000000000000000",
            "makerAssetAmount": "35003789556299530000000",
            "takerAssetData": "0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
            "takerAssetAmount": "6609708813064056613",
            "signature": "0x1b37b290a52a5afccf8c9eb155b37dad510aad8b37a607b939ef6c72b73bc86d956d53dd6bc8c910d8f0d28f6fa94b567151a24dedd3d83404eea67684e348481003",
            "expirationTimeSeconds": "1568183099"
          }
        }
      ]
    }
  }
}

More examples

  • Basic (without subscriptions)
  • Basic (with subscriptions)
  • Advanced (demos integration with existing express server)

Client Side Integration

这是将 React 和 React Hooks 与 0xQL 服务器集成的示例。 这假设 React 应用程序已经存在(您始终可以使用 create-react-app 来引导您的应用程序)。

我们将使用流行的 GraphQL 库 Apollo,它提供与 React 的平滑集成。 Apollo 提供了一组 React Hooks,我们可以直接在我们的组件中使用它们。

#

首先,设置代码,包括导入所需的代码和设置您的第一个查询。

yarn add apollo-boost @apollo/react-hooks graphql
import gql from 'graphql-tag'
import { useQuery } from '@apollo/react-hooks'

const GET_ORDERS_SUMMARY = gql`
  {
    orders {
      records {
        order {
          makerAssetData
          makerAssetAmount
          takerAssetData
          takerAssetAmount
        }
      }
      total
      page
      perPage
    }
  }
`

现在让我们编写我们的 React 组件

function Orders({ onOrderSelected }) {
  const { loading, error, data } = useQuery(GET_ORDERS_SUMMARY);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return (
    <div>
      {data.orders.records.map(order) => (
        <div onClick={() => onOrderSelected && onOrderSelected(order)}>
          {order.makerAssetData}
        </div>
      )}
    </div>
  );
}

最后,让我们将组件包装在一个 App 和一个 GraphQL 提供程序中:

import React from 'react'
import ApolloClient from 'apollo-boost'
import { render } from 'react-dom'
import { ApolloProvider } from '@apollo/react-hooks'

const client = new ApolloClient({ uri: 'http://localhost:4000' })

const App = () => (
  <ApolloProvider client={client}>
    <Orders onOrderSelected={order => console.log('order selected', order)} />
  </ApolloProvider>
)

render(<App />, document.getElementById('root'))

就是这样!

API

Available Imports

  • typeDefs
  • createReadyToUseResolvers
  • resolvers

typeDefs - 这是 GraphQL 模式的类型定义

createReadyToUseResolvers - 一个工厂函数,用于创建自以为是的、现成可用的解析器,并在需要时自动设置 websockets。

interface SubscriptionConfiguration {
  autoSubscribe?: boolean
  websocketUrl?: string
  ordersTopic?: string
  pubsub?: PubSub
}

const resolvers = createReadyToUseResolvers(
  relayerRestApiUrl: string,
  customSubscriptionConfig: SubscriptionConfiguration
):

返回:包含以下内容的对象:

  • queryResolver
  • mutationResolver
  • subscriptionResolver
  • jsonResolver

请参阅此处有关用法的basic示例。

resolvers:比 createReadyToUseResolvers 提供的解析器更高级、更细粒度、更少固执己见的配置。 请参阅有关用法的高级示例。

FAQ

What's GraphQL?

GraphQL 是一种用于 API 的查询语言,它支持声明式数据获取,以便让客户端能够准确指定 API 所需的数据。

What's 0x?

一个在以太坊区块链上进行去中心化交易的开放协议。

What's 0xQL

一个包,它提供用于将 GraphQL 支持构建到 0x 中继器中的原语和工具。

How does this package apply to GraphQL?

此包 0xQL 提供了必要的 GraphQL 绑定、解析器、架构和类型。 我们还包括一个可选的固执己见的设置,其中大部分内容都已预先配置。

How does this package apply to 0x?

0x Standard Relayer API 为中继器规定了 REST 和 WebSocket 交互的标准接口。 由于此接口是跨中继器标准化的,我们还可以以一致且健壮的方式添加对 GraphQL 的支持。 这个包支持 GraphQL 查询、变更和订阅。

Sounds good, but how do I use this?

此包提供了多种方式来使用 0xQL 包,具体取决于您所需的配置级别。 例如,0xQL 支持:

  • 使用最少的配置创建一个独立的 GraphQL 服务器。 查看此处的基本示例

  • 如果你已经有一个快速服务器并想添加 GraphQL 支持,你可以很容易地在 GraphQL 中分层。 查看此处的高级示例

  • 如果您已经拥有 GraphQL API 并且想要添加 0x 中继器支持,则可以使用 0xQL 架构和类型,并将其与您自己现有的 GraphQL 架构结合在一起。 (有关模式拼接和联合 GraphQL 支持的指南,请参阅 Apollo 文档)

Why write this package?

为什么不呢?

拥有更多方式并与 0x 中继器交互和集成是生态系统的胜利。

0xQL (ZeroEx GraphQL)

Easily add GraphQL support to any 0x Relayer that follows the 0x Standard Relayer API spec.

Demo

Check out the GraphiQL playground here. Try creating some queries, mutations, or subscriptions.

Check out the getting started guide for a sample query and sample subscription to try out on the demo playground.

Overview

0xQL enables developers to quickly build a GraphQL server that can automatically integrate with an existing 0x Relayer. The GraphQL server mirrors functionality of the 0x Relayer's REST and WS API, but instead can be accessed via GraphQL's Queries, Mutations, and Subscriptions.

Getting Started

Prerequisite

  • >= Node v10
  • >= Yarn v1.5

Installation

yarn add 0xql

Quick Start Guide

This guide will walk through setting up a 0xQL GraphQL server that works with RadarRelay.

Install the dependencies

$ yarn add 0xql apollo-server

Create an index.js file

$ touch index.js

Add the following code to index.js

// index.js
const { ApolloServer } = require('apollo-server')
const { createReadyToUseResolvers, typeDefs } = require('0xql')

const APP_PORT = 4000
const REST_API_ENDPOINT = 'https://api.radarrelay.com/0x/v2'

const {
  queryResolver,
  mutationResolver,
  jsonResolver,
} = createReadyToUseResolvers(REST_API_ENDPOINT)

const resolvers = {
  Query: queryResolver,
  Mutation: mutationResolver,
  JSON: jsonResolver,
}

const server = new ApolloServer({
  typeDefs,
  resolvers,
})

// Start the GraphQL server
server.listen({ port: APP_PORT }, () =>
  console.log(
    `???? Server ready at http://localhost:${APP_PORT}${server.graphqlPath}`
  )
)

Finally, start the server

node index.js

If everything worked, you should see the following printed in the console

???? Server ready at http://localhost:4000/

Congrats, you have your own functional 0xQL GraphQL instance pointed at RadarRelay. Let's try it out!

Navigate to http://localhost:4000 to check out the GQL playground

Try a sample query:

query GetOrders {
  orders {
    records {
      order {
        makerAssetData
        makerAssetAmount
        takerAssetData
        takerAssetAmount
      }
    }
    total
    page
    perPage
  }
}

Adding Subscriptions

In addition to fetching data using queries and modifying data using mutations, the GraphQL spec supports a third operation type, called subscription. GraphQL subscriptions are a way to push data from the server to the clients that choose to listen to real time messages from the server.

If you're looking to add subscriptions, check out the implementation example here which builds on the server we just made.

Subscriptions Demo

Check out the [demo site]() for a live demo.

Here's a sample subscription to send to the GraphQL server:

subscription SubscribeToAllOrders {
  subscribeToOrders(type: subscribe, channel: orders, requestId: "1234") {
    payload {
      order {
        makerAddress
        makerAssetData
        takerAddress
        makerAssetAmount
        takerAssetData
        takerAssetAmount
        signature
        expirationTimeSeconds
      }
    }
  }
}

You'll start to get a stream of incoming orders that look like the structure you just requested:

{
  "data": {
    "subscribeToOrders": {
      "payload": [
        {
          "order": {
            "makerAddress": "0x50f84bbee6fb250d6f49e854fa280445369d64d9",
            "makerAssetData": "0xf47261b00000000000000000000000000f5d2fb29fb7d3cfee444a200298f468908cc942",
            "takerAddress": "0x0000000000000000000000000000000000000000",
            "makerAssetAmount": "35003789556299530000000",
            "takerAssetData": "0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
            "takerAssetAmount": "6609708813064056613",
            "signature": "0x1b37b290a52a5afccf8c9eb155b37dad510aad8b37a607b939ef6c72b73bc86d956d53dd6bc8c910d8f0d28f6fa94b567151a24dedd3d83404eea67684e348481003",
            "expirationTimeSeconds": "1568183099"
          }
        }
      ]
    }
  }
}

More examples

  • Basic (without subscriptions)
  • Basic (with subscriptions)
  • Advanced (demos integration with existing express server)

Client Side Integration

Here's an example of integrating React and React Hooks with the 0xQL server. This assumes a React app already exists (you can always use create-react-app to bootstrap your app).

We're going to use the popular GraphQL library Apollo which offers smooth integration with React. Apollo offers a set of React Hooks which we can consume directly inside our components.

#

First, set up the code, which includes importing the required code and setting up your first query.

yarn add apollo-boost @apollo/react-hooks graphql
import gql from 'graphql-tag'
import { useQuery } from '@apollo/react-hooks'

const GET_ORDERS_SUMMARY = gql`
  {
    orders {
      records {
        order {
          makerAssetData
          makerAssetAmount
          takerAssetData
          takerAssetAmount
        }
      }
      total
      page
      perPage
    }
  }
`

Now let's write our React component

function Orders({ onOrderSelected }) {
  const { loading, error, data } = useQuery(GET_ORDERS_SUMMARY);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return (
    <div>
      {data.orders.records.map(order) => (
        <div onClick={() => onOrderSelected && onOrderSelected(order)}>
          {order.makerAssetData}
        </div>
      )}
    </div>
  );
}

Then finally, let's wrap the component in an App and a GraphQL provider:

import React from 'react'
import ApolloClient from 'apollo-boost'
import { render } from 'react-dom'
import { ApolloProvider } from '@apollo/react-hooks'

const client = new ApolloClient({ uri: 'http://localhost:4000' })

const App = () => (
  <ApolloProvider client={client}>
    <Orders onOrderSelected={order => console.log('order selected', order)} />
  </ApolloProvider>
)

render(<App />, document.getElementById('root'))

That's it!

API

Available Imports

  • typeDefs
  • createReadyToUseResolvers
  • resolvers

typeDefs - This is the Type Definitions for the GraphQL schema

createReadyToUseResolvers - A factory function to create opinionated, ready-to-use resolvers, and if requested, sets up websockets automatically.

interface SubscriptionConfiguration {
  autoSubscribe?: boolean
  websocketUrl?: string
  ordersTopic?: string
  pubsub?: PubSub
}

const resolvers = createReadyToUseResolvers(
  relayerRestApiUrl: string,
  customSubscriptionConfig: SubscriptionConfiguration
):

Returns: Object that contains the following:

  • queryResolver
  • mutationResolver
  • subscriptionResolver
  • jsonResolver

See the basic example on the usage here.

resolvers: More advanced fine-grained, less opinionated configuration over resolvers than createReadyToUseResolvers provides. See the advanced example on usage.

FAQ

What's GraphQL?

GraphQL is a query language for APIs that enables declarative data fetching in order to give the client the power to specify exactly the data that is needed from the API.

What's 0x?

An open protocol for decentralized exchange on the Ethereum blockchain.

What's 0xQL

A package that provides primitives and tooling for building GraphQL support into your 0x Relayer.

How does this package apply to GraphQL?

This package, 0xQL, provides the necessary GraphQL bindings, resolvers, schema, and types. We also include an optional opinionated setup with most things preconfigured.

How does this package apply to 0x?

The 0x Standard Relayer API dictates a standard interface for both REST and WebSocket interaction for a relayer. Since this interface is standardized across relayers, we can also add support for GraphQL in a consistent and robust way. This package supports GraphQL queries, mutations, and subscriptions.

Sounds good, but how do I use this?

This package provides various ways to consume the 0xQL package, depending on your level of configuration required. For example, 0xQL supports:

  • Creating a standalone GraphQL server with minimal configuration. Check out the basic example here.

  • If you already have an express server and want to add GraphQL support, you can layer in GraphQL quite easily. Check out the advanced example here

  • If you already have a GraphQL API and you want to add 0x relayer support, you can take the 0xQL schema and types and stich it together with your own existing GraphQL schema. (See Apollo docs for guides on schema stiching and federated GraphQL support)

Why write this package?

Why not?

Having more ways and to interact and integrate with 0x relayers is a win for the ecosystem.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文