-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Server-Sent Events transport (#2498)
* Add new transport via server-sent events * Add graphql-sse option to chat example * Add SSE transport to documentation * Reorder imports and handle test err to fix golangci-lint remarks
- Loading branch information
Showing
10 changed files
with
369 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { | ||
ApolloLink, | ||
Operation, | ||
FetchResult, | ||
Observable, | ||
} from '@apollo/client/core'; | ||
import { print } from 'graphql'; | ||
import { createClient, ClientOptions, Client } from 'graphql-sse'; | ||
|
||
export class SSELink extends ApolloLink { | ||
private client: Client; | ||
|
||
constructor(options: ClientOptions) { | ||
super(); | ||
this.client = createClient(options); | ||
} | ||
|
||
public request(operation: Operation): Observable<FetchResult> { | ||
return new Observable((sink) => { | ||
return this.client.subscribe<FetchResult>( | ||
{ ...operation, query: print(operation.query) }, | ||
{ | ||
next: sink.next.bind(sink), | ||
complete: sink.complete.bind(sink), | ||
error: sink.error.bind(sink), | ||
}, | ||
); | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
{ | ||
"compilerOptions": { | ||
"target": "es5", | ||
"lib": [ | ||
"dom", | ||
"dom.iterable", | ||
"esnext" | ||
], | ||
"allowJs": true, | ||
"skipLibCheck": true, | ||
"esModuleInterop": true, | ||
"allowSyntheticDefaultImports": true, | ||
"strict": true, | ||
"forceConsistentCasingInFileNames": true, | ||
"module": "esnext", | ||
"moduleResolution": "node", | ||
"resolveJsonModule": true, | ||
"isolatedModules": true, | ||
"noEmit": true, | ||
"jsx": "preserve" | ||
}, | ||
"include": [ | ||
"src" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
package transport | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"log" | ||
"mime" | ||
"net/http" | ||
"strings" | ||
|
||
"github.com/vektah/gqlparser/v2/gqlerror" | ||
|
||
"github.com/99designs/gqlgen/graphql" | ||
) | ||
|
||
type SSE struct{} | ||
|
||
var _ graphql.Transport = SSE{} | ||
|
||
func (t SSE) Supports(r *http.Request) bool { | ||
if !strings.Contains(r.Header.Get("Accept"), "text/event-stream") { | ||
return false | ||
} | ||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) | ||
if err != nil { | ||
return false | ||
} | ||
return r.Method == http.MethodPost && mediaType == "application/json" | ||
} | ||
|
||
func (t SSE) Do(w http.ResponseWriter, r *http.Request, exec graphql.GraphExecutor) { | ||
ctx := r.Context() | ||
flusher, ok := w.(http.Flusher) | ||
if !ok { | ||
SendErrorf(w, http.StatusInternalServerError, "streaming unsupported") | ||
return | ||
} | ||
defer flusher.Flush() | ||
|
||
w.Header().Set("Cache-Control", "no-cache") | ||
w.Header().Set("Connection", "keep-alive") | ||
w.Header().Set("Content-Type", "application/json") | ||
|
||
params := &graphql.RawParams{} | ||
start := graphql.Now() | ||
params.Headers = r.Header | ||
params.ReadTime = graphql.TraceTiming{ | ||
Start: start, | ||
End: graphql.Now(), | ||
} | ||
|
||
bodyString, err := getRequestBody(r) | ||
if err != nil { | ||
gqlErr := gqlerror.Errorf("could not get json request body: %+v", err) | ||
resp := exec.DispatchError(ctx, gqlerror.List{gqlErr}) | ||
log.Printf("could not get json request body: %+v", err.Error()) | ||
writeJson(w, resp) | ||
return | ||
} | ||
|
||
bodyReader := io.NopCloser(strings.NewReader(bodyString)) | ||
if err = jsonDecode(bodyReader, ¶ms); err != nil { | ||
w.WriteHeader(http.StatusBadRequest) | ||
gqlErr := gqlerror.Errorf( | ||
"json request body could not be decoded: %+v body:%s", | ||
err, | ||
bodyString, | ||
) | ||
resp := exec.DispatchError(ctx, gqlerror.List{gqlErr}) | ||
log.Printf("decoding error: %+v body:%s", err.Error(), bodyString) | ||
writeJson(w, resp) | ||
return | ||
} | ||
|
||
rc, OpErr := exec.CreateOperationContext(ctx, params) | ||
if OpErr != nil { | ||
w.WriteHeader(statusFor(OpErr)) | ||
resp := exec.DispatchError(graphql.WithOperationContext(ctx, rc), OpErr) | ||
writeJson(w, resp) | ||
return | ||
} | ||
|
||
ctx = graphql.WithOperationContext(ctx, rc) | ||
|
||
w.Header().Set("Content-Type", "text/event-stream") | ||
fmt.Fprint(w, ":\n\n") | ||
flusher.Flush() | ||
|
||
responses, ctx := exec.DispatchOperation(ctx, rc) | ||
|
||
for { | ||
response := responses(ctx) | ||
if response == nil { | ||
break | ||
} | ||
writeJsonWithSSE(w, response) | ||
flusher.Flush() | ||
} | ||
|
||
fmt.Fprint(w, "event: complete\n\n") | ||
} | ||
|
||
func writeJsonWithSSE(w io.Writer, response *graphql.Response) { | ||
b, err := json.Marshal(response) | ||
if err != nil { | ||
panic(err) | ||
} | ||
fmt.Fprintf(w, "event: next\ndata: %s\n\n", b) | ||
} |
Oops, something went wrong.