这是indexloc提供的服务,不要输入任何密码
Skip to content

support graphql-ws protocol #67

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
name: Unit tests

on: ["push"]
on:
push:
paths:
- "**.go"
- ".github/workflows/*.yml"
- "example/hasura/docker-compose.yaml"

jobs:
test-go:
Expand All @@ -11,12 +16,46 @@ jobs:
uses: actions/checkout@v2
- uses: actions/setup-go@v2
with:
go-version: '1.16.4'
go-version: "1.16.4"
- uses: actions/cache@v2
with:
path: |
~/go/pkg/mod
~/.cache/go-build
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Install dependencies
run: go get -t -v ./...
- name: Format
run: diff -u <(echo -n) <(gofmt -d -s .)
- name: Vet
run: go vet ./...
- name: Setup integration test infrastructure
run: |
cd ./example/hasura
docker-compose up -d
- name: Run Go unit tests
run: go test -v -race ./...
run: go test -v -race -coverprofile=coverage.out ./...
- name: Go coverage format
run: |
go get github.com/boumenot/gocover-cobertura
gocover-cobertura < coverage.out > coverage.xml
- name: Code Coverage Summary Report
uses: irongut/CodeCoverageSummary@v1.3.0
with:
filename: coverage.xml
badge: true
fail_below_min: true
format: markdown
hide_branch_rate: false
hide_complexity: true
indicators: true
output: both
thresholds: "60 80"
- name: Add Coverage PR Comment
uses: marocchino/sticky-pull-request-comment@v2
if: github.event_name == 'pull_request'
with:
recreate: true
path: code-coverage-results.md
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.idea/
coverage.out
41 changes: 39 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ For more information, see package [`github.com/shurcooL/githubv4`](https://githu
- [Stop the subscription](#stop-the-subscription)
- [Authentication](#authentication-1)
- [Options](#options)
- [Subscription Protocols](#subscription-protocols)
- [Handle connection error](#handle-connection-error)
- [Events](#events)
- [Custom HTTP Client](#custom-http-client)
- [Custom WebSocket client](#custom-websocket-client)
Expand Down Expand Up @@ -531,10 +533,18 @@ client := graphql.NewSubscriptionClient("wss://example.com/graphql").
"headers": map[string]string{
"authentication": "...",
},
}).
// or lazy parameters with function
WithConnectionParamsFn(func () map[string]interface{} {
return map[string]interface{} {
"headers": map[string]string{
"authentication": "...",
},
}
})

```


#### Options

```Go
Expand All @@ -548,8 +558,35 @@ client.
// max size of response message
WithReadLimit(10*1024*1024).
// these operation event logs won't be printed
WithoutLogTypes(graphql.GQL_DATA, graphql.GQL_CONNECTION_KEEP_ALIVE)
WithoutLogTypes(graphql.GQLData, graphql.GQLConnectionKeepAlive)
```

#### Subscription Protocols

The subscription client supports 2 protocols:
- [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md) (default)
- [graphql-ws](https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md)

The protocol can be switchable by the `WithProtocol` function.

```Go
client.WithProtocol(graphql.GraphQLWS)
```

#### Handle connection error

GraphQL servers can define custom WebSocket error codes in the 3000-4999 range. For example, in the `graphql-ws` protocol, the server sends the invalid message error with status [4400](https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md#invalid-message). In this case, the subscription client should let the user handle the error through the `OnError` event.

```go
client := graphql.NewSubscriptionClient(serverEndpoint).
OnError(func(sc *graphql.SubscriptionClient, err error) error {
if strings.Contains(err.Error(), "invalid x-hasura-admin-secret/x-hasura-access-key") {
// exit the subscription client due to unauthorized error
return err
}
// otherwise ignore the error and the client continues to run
return nil
})
```

#### Events
Expand Down
27 changes: 27 additions & 0 deletions example/hasura/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Examples with Hasura graphql server

## How to run

### Server

Requires [Docker](https://www.docker.com/) and [docker-compose](https://docs.docker.com/compose/install/)

```sh
docker-compose up -d
```

Open the console at `http://localhost:8080` with admin secret `hasura`.

### Client

#### Subscription with subscriptions-transport-ws protocol

```sh
go run ./client/subscriptions-transport-ws
```

#### Subscription with graphql-ws protocol

```sh
go run ./client/graphql-ws
```
151 changes: 151 additions & 0 deletions example/hasura/client/graphql-ws/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package main

import (
"context"
"fmt"
"log"
"math/rand"
"net/http"
"strings"
"time"

graphql "github.com/hasura/go-graphql-client"
)

const (
serverEndpoint = "http://localhost:8080/v1/graphql"
adminSecret = "hasura"
xHasuraAdminSecret = "x-hasura-admin-secret"
)

func main() {
go insertUsers()
startSubscription()
}

func startSubscription() error {

client := graphql.NewSubscriptionClient(serverEndpoint).
WithProtocol(graphql.GraphQLWS).
WithConnectionParams(map[string]interface{}{
"headers": map[string]string{
xHasuraAdminSecret: adminSecret,
},
}).WithLog(log.Println).
OnError(func(sc *graphql.SubscriptionClient, err error) error {
if strings.Contains(err.Error(), "invalid x-hasura-admin-secret/x-hasura-access-key") {
return err
}
return nil
})

defer client.Close()

/*
subscription {
user {
id
name
}
}
*/
var sub struct {
Users []struct {
ID int `graphql:"id"`
Name string `graphql:"name"`
} `graphql:"user(order_by: { id: desc }, limit: 5)"`
}

_, err := client.Subscribe(sub, nil, func(data []byte, err error) error {

if err != nil {
log.Println(err)
return nil
}

if data == nil {
return nil
}
log.Println(string(data))
return nil
})

if err != nil {
panic(err)
}

// automatically unsubscribe after 10 seconds
// go func() {
// time.Sleep(10 * time.Second)
// client.Unsubscribe(subId)
// }()

return client.Run()
}

type user_insert_input map[string]interface{}

// insertUsers insert users to the graphql server, so the subscription client can receive messages
func insertUsers() {

client := graphql.NewClient(serverEndpoint, &http.Client{
Transport: headerRoundTripper{
setHeaders: func(req *http.Request) {
req.Header.Set(xHasuraAdminSecret, adminSecret)
},
rt: http.DefaultTransport,
},
})
// stop until the subscription client is connected
time.Sleep(time.Second)
for i := 0; i < 10; i++ {
/*
mutation InsertUser($objects: [user_insert_input!]!) {
insert_user(objects: $objects) {
id
name
}
}
*/
var q struct {
InsertUser struct {
Returning []struct {
ID int `graphql:"id"`
Name string `graphql:"name"`
} `graphql:"returning"`
} `graphql:"insert_user(objects: $objects)"`
}
variables := map[string]interface{}{
"objects": []user_insert_input{
{
"name": randomString(),
},
},
}
err := client.Mutate(context.Background(), &q, variables, graphql.OperationName("InsertUser"))
if err != nil {
fmt.Println(err)
}
time.Sleep(time.Second)
}
}

func randomString() string {
var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

b := make([]rune, 16)
for i := range b {
b[i] = letter[rand.Intn(len(letter))]
}
return string(b)
}

type headerRoundTripper struct {
setHeaders func(req *http.Request)
rt http.RoundTripper
}

func (h headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
h.setHeaders(req)
return h.rt.RoundTrip(req)
}
Loading