Skip to content

Commit

Permalink
Merge pull request #3 from labd/2-add-retry-policy-to-schema-check
Browse files Browse the repository at this point in the history
Updated repo. Added additional options to override http client, chang…
  • Loading branch information
demeyerthom authored Aug 31, 2023
2 parents fdffddb + 2e71e38 commit 188701a
Show file tree
Hide file tree
Showing 23 changed files with 380 additions and 229 deletions.
6 changes: 6 additions & 0 deletions .changes/header.tpl.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
Empty file added .changes/unreleased/.gitkeep
Empty file.
3 changes: 3 additions & 0 deletions .changes/unreleased/Added-20230830-144259.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
kind: Added
body: Added additional client options to allow overriding of default http client
time: 2023-08-30T14:42:59.707696257+02:00
3 changes: 3 additions & 0 deletions .changes/v1.0.0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## v1.0.0 - 2023-05-04
### Changed
* rename from go-apollostudio-sdk to standard format apollostudio-go-sdk
26 changes: 26 additions & 0 deletions .changie.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
changesDir: .changes
unreleasedDir: unreleased
headerPath: header.tpl.md
changelogPath: CHANGELOG.md
versionExt: md
versionFormat: '## {{.Version}} - {{.Time.Format "2006-01-02"}}'
kindFormat: '### {{.Kind}}'
changeFormat: '* {{.Body}}'
kinds:
- label: Added
auto: minor
- label: Changed
auto: major
- label: Deprecated
auto: minor
- label: Removed
auto: major
- label: Fixed
auto: patch
- label: Security
auto: patch
newlines:
afterChangelogHeader: 1
beforeChangelogVersion: 1
endOfVersion: 1
envPrefix: CHANGIE_
48 changes: 48 additions & 0 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: Run Tests

on: [ push ]

jobs:

test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3

- name: Set up Go 1.20
uses: actions/setup-go@v4
with:
go-version: "1.20"

- name: golangci-lint
continue-on-error: true
uses: golangci/golangci-lint-action@v3
with:
args: --issues-exit-code=0 --timeout=5m

- name: Run tests
run: go test -race -coverprofile=coverage.out -covermode=atomic -coverpkg=./... -v ./...

- name: Upload to codecov
uses: codecov/codecov-action@v3
with:
verbose: true

changie:
runs-on: ubuntu-latest
needs: test
if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
permissions:
contents: write
pull-requests: write
actions: write
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Prepare release
uses: labd/[email protected]
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.env
.idea
.idea
coverage.txt
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).


## 1.0.0 - 2023-05-04
### Changed
* rename from go-apollostudio-sdk to standard format apollostudio-go-sdk
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Lab Digital

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
58 changes: 46 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,56 @@
# Amplience GO SDK
# Apollo Studio Go SDK

Go SDK for [Apollo Studio](https://studio.apollographql.com/).

## Development
## Installation

To test the API, run `cmd/debug/main.go` file with your own Apollo studio graph credentials.
```bash
go get github.com/labd/apollostudio-go-sdk
```

## Usage

```go
package main

import (
"context"
"github.com/labd/apollostudio-go-sdk/apollostudio"
)

func main() {
key := "your-api-key"
ref := "your-schema-reference"

client, err := apollostudio.NewClient(key, ref)
if err != nil {
panic(err)
}

_, _ := client.SubmitSubGraph(
context.Background(),
&apollostudio.SubmitOptions{
SubGraphSchema: []byte("schema { query: Query } type Query { hello: String }"),
SubGraphName: "my-subgraph",
SubGraphURL: "https://my-subgraph.com/graphql",
},
)
}
```
export APOLLO_API_KEY=your_api_key
export APOLLO_GRAPH_REF=your_graph_ref
export APOLLO_SUB_GRAPH_SCHEMA=your_sub_graph_schema
export APOLLO_SUB_GRAPH_NAME=your_sub_graph_name
export APOLLO_SUB_GRAPH_URL=your_sub_graph_url
go build ./cmd/debug
./debug -h

The client allows for several additional options to be set, which can extend its functionality.

```go
var clientOpts = []apollostudio.ClientOpt{
apollostudio.WithHttpClient(http.DefaultClient),
apollostudio.WithDebug(true),
apollostudio.WithUrl("https://studio.apollographql.com/api/graphql"),
}

client, err := apollostudio.NewClient(key, ref, clientOpts...)

```

## Contributing

Apollo Studio GraphQL explorer can be found [here](https://studio.apollographql.com/public/apollo-platform/variant/main/explorer).
Apollo Studio GraphQL explorer can be found [here](https://studio.apollographql.com/public/apollo-platform/variant/main/explorer).
116 changes: 116 additions & 0 deletions apollostudio/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package apollostudio

import (
"errors"
"fmt"
"net/http"
"strings"

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

var defaultUrl = "https://graphql.api.apollographql.com/api/graphql"

type clientSettings struct {
httpClient *http.Client
debug bool
url string
requestModifier graphql.RequestModifier
}

type Client struct {
gqlClient *graphql.Client
GraphRef GraphRef
}

type ClientOpt func(client *clientSettings)

// WithHttpClient allows you to set a custom http client for fine-grained control of traffic
func WithHttpClient(httpClient *http.Client) ClientOpt {
return func(settings *clientSettings) {
settings.httpClient = httpClient
}
}

// WithDebug allows you to run the client in debug mode, which will return internal error details
func WithDebug(debug bool) ClientOpt {
return func(settings *clientSettings) {
settings.debug = debug
}
}

// WithUrl allows you to overrule the default url
func WithUrl(url string) ClientOpt {
return func(settings *clientSettings) {
settings.url = url
}
}

// WithRequestModifier allows you to modify the request. Note that the API key is also set by ApiKeyRequestModifier,
// so make sure to also call this method if you want to further modify the request
func WithRequestModifier(modifier graphql.RequestModifier) ClientOpt {
return func(settings *clientSettings) {
settings.requestModifier = modifier
}
}

type GraphRef string

func isValidGraphRef(graphRef string) bool {
if graphRef == "" {
return false
}

p := strings.Split(graphRef, "@")

if len(p) != 2 {

Check failure on line 66 in apollostudio/client.go

View workflow job for this annotation

GitHub Actions / test

S1008: should use 'return len(p) == 2' instead of 'if len(p) != 2 { return false }; return true' (gosimple)
return false
}

return true
}

func (g *GraphRef) getGraphId() string {
p := strings.Split(string(*g), "@")

return p[0]
}

func (g *GraphRef) getVariant() string {

p := strings.Split(string(*g), "@")

return p[1]
}

func NewClient(apiKey string, graphRef string, opts ...ClientOpt) (*Client, error) {
settings := &clientSettings{
httpClient: http.DefaultClient,
debug: false,
url: defaultUrl,
requestModifier: ApiKeyRequestModifier(apiKey),
}

for _, opt := range opts {
opt(settings)
}

if !isValidGraphRef(graphRef) {
return nil, errors.New(fmt.Sprintf("Provided invalid graph ref. Expected ref in format *@*, received %s", graphRef))

Check failure on line 99 in apollostudio/client.go

View workflow job for this annotation

GitHub Actions / test

S1028: should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (gosimple)
}

gqlClient := graphql.NewClient(settings.url, settings.httpClient)
gqlClient = gqlClient.WithDebug(settings.debug)
gqlClient = gqlClient.WithRequestModifier(settings.requestModifier)

return &Client{
gqlClient: gqlClient,
GraphRef: GraphRef(graphRef),
}, nil
}

func ApiKeyRequestModifier(apiKey string) graphql.RequestModifier {
return func(req *http.Request) {
req.Header.Add("x-api-key", apiKey)
}
}
33 changes: 33 additions & 0 deletions apollostudio/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package apollostudio

import (
"github.com/stretchr/testify/assert"
"testing"
)

func TestValidateGraphRef(t *testing.T) {
tests := []struct {
ref string
valid bool
}{
{ref: "foo@bar", valid: true},
{ref: "foobar", valid: false},
}

for _, test := range tests {
valid := isValidGraphRef(test.ref)
assert.Equal(t, test.valid, valid)
}
}

func TestGraphRefGetGraphId(t *testing.T) {
graphRef := GraphRef("foo@bar")

assert.Equal(t, "foo", graphRef.getGraphId())
}

func TestGraphRefGetVariant(t *testing.T) {
graphRef := GraphRef("foo@bar")

assert.Equal(t, "bar", graphRef.getVariant())
}
4 changes: 3 additions & 1 deletion pkg/apollostudio/errors.go → apollostudio/errors.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package apollostudio

import (
"errors"
"fmt"
"strings"
)
Expand Down Expand Up @@ -30,6 +31,7 @@ func (e *OperationError) Error() string {
// an error, but the subgraph will still be created. As a result, the
// federation schema remains unaffected, while the subgraph coexists with errors.
func IsOperationError(err error) bool {
_, ok := err.(*OperationError)
var operationError *OperationError
ok := errors.As(err, &operationError)
return ok
}
4 changes: 2 additions & 2 deletions pkg/apollostudio/get.go → apollostudio/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ func (c *Client) GetSubGraph(ctx context.Context, name string) (*SubGraphResult,
var query Query

vars := map[string]interface{}{
"graph_id": graphql.ID(c.GraphID),
"graph_id": graphql.ID(c.GraphRef.getGraphId()),
"subgraph": graphql.ID(name),
"variant": graphql.String(c.Variant),
"variant": c.GraphRef.getVariant(),
}

err := c.gqlClient.Query(ctx, &query, vars)
Expand Down
File renamed without changes.
6 changes: 3 additions & 3 deletions pkg/apollostudio/remove.go → apollostudio/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ func (c *Client) RemoveSubGraph(ctx context.Context, name string) error {
var mutation Mutation

vars := map[string]interface{}{
"graph_id": graphql.ID(c.GraphID),
"subgraph": graphql.String(name),
"variant": graphql.String(c.Variant),
"graph_id": graphql.ID(c.GraphRef.getGraphId()),
"subgraph": name,
"variant": c.GraphRef.getVariant(),
}

err := c.gqlClient.Mutate(ctx, &mutation, vars)
Expand Down
Loading

0 comments on commit 188701a

Please sign in to comment.