Documentation
¶
Overview ¶
Package graphql provides a GraphQL client implementation.
For more information, see package github.com/hasura/go-graphql-client
For now, see README for more details.
Index ¶
- Constants
- Variables
- func ConstructMutation(v interface{}, variables map[string]interface{}, options ...Option) (string, error)
- func ConstructQuery(v interface{}, variables map[string]interface{}, options ...Option) (string, error)
- func ConstructSubscription(v interface{}, variables map[string]interface{}, options ...Option) (string, string, error)
- func ElemSafe(v reflect.Value) reflect.Value
- func FieldSafe(valStruct reflect.Value, i int) reflect.Value
- func IndexSafe(v reflect.Value, i int) reflect.Value
- func UnmarshalGraphQL(data []byte, v any) error
- type Boolean
- type Client
- func (c *Client) Exec(ctx context.Context, query string, v any, variables map[string]any, ...) error
- func (c *Client) ExecRaw(ctx context.Context, query string, variables map[string]any, options ...Option) ([]byte, error)
- func (c *Client) ExecRawWithExtensions(ctx context.Context, query string, variables map[string]any, options ...Option) ([]byte, []byte, error)
- func (c *Client) Mutate(ctx context.Context, m any, variables map[string]any, options ...Option) error
- func (c *Client) MutateRaw(ctx context.Context, m any, variables map[string]any, options ...Option) ([]byte, error)
- func (c *Client) NamedMutate(ctx context.Context, name string, m any, variables map[string]any, ...) errordeprecated
- func (c *Client) NamedMutateRaw(ctx context.Context, name string, m any, variables map[string]any, ...) ([]byte, error)
- func (c *Client) NamedQuery(ctx context.Context, name string, q any, variables map[string]any, ...) errordeprecated
- func (c *Client) NamedQueryRaw(ctx context.Context, name string, q any, variables map[string]any, ...) ([]byte, error)
- func (c *Client) Query(ctx context.Context, q any, variables map[string]any, options ...Option) error
- func (c *Client) QueryRaw(ctx context.Context, q any, variables map[string]any, options ...Option) ([]byte, error)
- func (c *Client) WithDebug(debug bool) *Client
- func (c *Client) WithRequestModifier(f RequestModifier) *Client
- type ClientOption
- type CreateWebSocketConnFunc
- type Doer
- type Error
- type Errors
- type Float
- type GraphQLRequestPayload
- type GraphQLType
- type ID
- type Int
- type NetworkError
- type OperationMessage
- type OperationMessageType
- type Option
- type OptionType
- type RequestModifier
- type String
- type Subscription
- func (s Subscription) Clone() Subscription
- func (s Subscription) GetHandler() func(data []byte, err error)
- func (s Subscription) GetID() string
- func (s Subscription) GetKey() string
- func (s Subscription) GetPayload() GraphQLRequestPayload
- func (s Subscription) GetStatus() SubscriptionStatus
- func (s *Subscription) SetStatus(status SubscriptionStatus)
- type SubscriptionClient
- func (sc *SubscriptionClient) Close() error
- func (sc *SubscriptionClient) Exec(query string, variables map[string]interface{}, ...) (string, error)
- func (sc *SubscriptionClient) GetContext() context.Context
- func (sc *SubscriptionClient) GetReadTimeout() time.Duration
- func (sc *SubscriptionClient) GetSubscription(id string) *Subscription
- func (sc *SubscriptionClient) GetSubscriptions() map[string]Subscription
- func (sc *SubscriptionClient) GetTimeout() time.Duration
- func (sc *SubscriptionClient) GetURL() string
- func (sc *SubscriptionClient) GetWebSocketStatusCode(err error) websocket.StatusCode
- func (sc *SubscriptionClient) GetWriteTimeout() time.Duration
- func (sc *SubscriptionClient) IsConnectionInitialisationTimeout(err error) bool
- func (sc *SubscriptionClient) IsInternalConnectionError(err error) bool
- func (sc *SubscriptionClient) IsInvalidMessageError(err error) bool
- func (sc *SubscriptionClient) IsStatusSubscriberAlreadyExists(err error) bool
- func (sc *SubscriptionClient) IsTooManyInitialisationRequests(err error) bool
- func (sc *SubscriptionClient) IsUnauthorized(err error) bool
- func (sc *SubscriptionClient) IsWebsocketConnectionIdleTimeout(err error) bool
- func (sc *SubscriptionClient) NamedSubscribe(name string, v interface{}, variables map[string]interface{}, ...) (string, error)deprecated
- func (sc *SubscriptionClient) OnConnected(fn func()) *SubscriptionClient
- func (sc *SubscriptionClient) OnConnectionAlive(fn func()) *SubscriptionClient
- func (sc *SubscriptionClient) OnDisconnected(fn func()) *SubscriptionClient
- func (sc *SubscriptionClient) OnError(onError func(sc *SubscriptionClient, err error) error) *SubscriptionClient
- func (sc *SubscriptionClient) OnSubscriptionComplete(fn func(sub Subscription)) *SubscriptionClient
- func (sc *SubscriptionClient) Run() error
- func (sc *SubscriptionClient) RunWithContext(ctx context.Context) error
- func (sc *SubscriptionClient) Subscribe(v interface{}, variables map[string]interface{}, ...) (string, error)
- func (sc *SubscriptionClient) SubscribeRaw(query string, variables map[string]interface{}, ...) (string, error)deprecated
- func (sc *SubscriptionClient) Unsubscribe(id string) error
- func (sc *SubscriptionClient) WithConnectionInitialisationTimeout(timeout time.Duration) *SubscriptionClient
- func (sc *SubscriptionClient) WithConnectionParams(params map[string]interface{}) *SubscriptionClient
- func (sc *SubscriptionClient) WithConnectionParamsFn(fn func() map[string]interface{}) *SubscriptionClient
- func (sc *SubscriptionClient) WithCustomProtocol(protocol SubscriptionProtocol) *SubscriptionClient
- func (sc *SubscriptionClient) WithExitWhenNoSubscription(value bool) *SubscriptionClient
- func (sc *SubscriptionClient) WithKeepAlive(interval time.Duration) *SubscriptionClient
- func (sc *SubscriptionClient) WithLog(logger func(args ...interface{})) *SubscriptionClient
- func (sc *SubscriptionClient) WithProtocol(protocol SubscriptionProtocolType) *SubscriptionClient
- func (sc *SubscriptionClient) WithReadLimit(limit int64) *SubscriptionClient
- func (sc *SubscriptionClient) WithReadTimeout(timeout time.Duration) *SubscriptionClient
- func (sc *SubscriptionClient) WithRetryDelay(delay time.Duration) *SubscriptionClient
- func (sc *SubscriptionClient) WithRetryStatusCodes(codes ...string) *SubscriptionClient
- func (sc *SubscriptionClient) WithRetryTimeout(timeout time.Duration) *SubscriptionClient
- func (sc *SubscriptionClient) WithSyncMode(value bool) *SubscriptionClient
- func (sc *SubscriptionClient) WithTimeout(timeout time.Duration) *SubscriptionClient
- func (sc *SubscriptionClient) WithWebSocket(fn CreateWebSocketConnFunc) *SubscriptionClient
- func (sc *SubscriptionClient) WithWebSocketKeepAlive(interval time.Duration) *SubscriptionClient
- func (sc *SubscriptionClient) WithWebSocketOptions(options WebsocketOptions) *SubscriptionClient
- func (sc *SubscriptionClient) WithWebsocketConnectionIdleTimeout(timeout time.Duration) *SubscriptionClient
- func (sc *SubscriptionClient) WithWriteTimeout(timeout time.Duration) *SubscriptionClient
- func (sc *SubscriptionClient) WithoutLogTypes(types ...OperationMessageType) *SubscriptionClient
- type SubscriptionContext
- func (sc *SubscriptionContext) Cancel()
- func (sc *SubscriptionContext) Close() error
- func (sc *SubscriptionContext) GetAcknowledge() bool
- func (sc *SubscriptionContext) GetSubscription(id string) *Subscription
- func (sc *SubscriptionContext) GetSubscriptions() map[string]Subscription
- func (sc *SubscriptionContext) GetSubscriptionsLength(status []SubscriptionStatus) int
- func (sc *SubscriptionContext) GetWebsocketConn() WebsocketConn
- func (sc *SubscriptionContext) IsClosed() bool
- func (sc *SubscriptionContext) Log(message interface{}, metadata map[string]any, opType OperationMessageType)
- func (sc *SubscriptionContext) OnConnected()
- func (sc *SubscriptionContext) OnConnectionAlive()
- func (sc *SubscriptionContext) OnDisconnected()
- func (sc *SubscriptionContext) OnSubscriptionComplete(subscription Subscription)
- func (sc *SubscriptionContext) Send(message interface{}, opType OperationMessageType) error
- func (sc *SubscriptionContext) SetAcknowledge(value bool)
- func (sc *SubscriptionContext) SetClosed(value bool)
- func (sc *SubscriptionContext) SetSubscription(key string, sub *Subscription)
- func (sc *SubscriptionContext) SetWebsocketConn(conn WebsocketConn)
- type SubscriptionProtocol
- type SubscriptionProtocolType
- type SubscriptionStatus
- type WebSocketStats
- type WebsocketConn
- type WebsocketHandler
- func (wh *WebsocketHandler) Close() error
- func (wh *WebsocketHandler) GetCloseStatus(err error) int32
- func (wh WebsocketHandler) GetID() uuid.UUID
- func (wh *WebsocketHandler) Ping() error
- func (wh *WebsocketHandler) ReadJSON(v interface{}) error
- func (wh *WebsocketHandler) WriteJSON(v interface{}) error
- type WebsocketOptions
Constants ¶
const ( ErrRequestError = "request_error" ErrJsonEncode = "json_encode_error" ErrJsonDecode = "json_decode_error" ErrGraphQLEncode = "graphql_encode_error" ErrGraphQLDecode = "graphql_decode_error" ErrGraphQLExtensionsDecode = "graphql_extensions_decode_error" )
const ( // SubscriptionWaiting the subscription hasn't been registered to the server. SubscriptionWaiting SubscriptionStatus = 0 // SubscriptionRunning the subscription is up and running. SubscriptionRunning SubscriptionStatus = 1 // SubscriptionUnsubscribed the subscription was manually unsubscribed by the user. SubscriptionUnsubscribed SubscriptionStatus = 2 // SubscriptionsTransportWS the enum implements the subscription transport that follows Apollo's subscriptions-transport-ws protocol specification // https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md SubscriptionsTransportWS SubscriptionProtocolType = "subscriptions-transport-ws" // GraphQLWS enum implements GraphQL over WebSocket Protocol (graphql-ws) // https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md GraphQLWS SubscriptionProtocolType = "graphql-ws" // Receiving a message of a type or format which is not specified in this document // The <error-message> can be vaguely descriptive on why the received message is invalid. StatusInvalidMessage websocket.StatusCode = 4400 StatusUnauthorized websocket.StatusCode = 4401 // if the connection is unauthorized and be rejected by the server. StatusForbidden websocket.StatusCode = 4403 // Connection initialisation timeout. StatusConnectionInitialisationTimeout websocket.StatusCode = 4408 // Subscriber for <generated-id> already exists. StatusSubscriberAlreadyExists websocket.StatusCode = 4409 // Too many initialisation requests. StatusTooManyInitialisationRequests websocket.StatusCode = 4429 )
const ( // Unknown operation type, for logging only. GQLUnknown OperationMessageType = "unknown" // Internal status, for logging only. GQLInternal OperationMessageType = "internal" // @deprecated: use GQLUnknown instead. GQL_UNKNOWN = GQLUnknown // @deprecated: use GQLInternal instead. GQL_INTERNAL = GQLInternal )
const ( // The server may responses with this message to the GQL_CONNECTION_INIT from client, indicates the server rejected the connection. GQLConnectionError OperationMessageType = "connection_error" // Client sends this message to execute GraphQL operation. GQLStart OperationMessageType = "start" // Client sends this message in order to stop a running GraphQL operation execution (for example: unsubscribe). GQLStop OperationMessageType = "stop" // Client sends this message in order to stop a running GraphQL operation execution (for example: unsubscribe). GQLData OperationMessageType = "data" // Server message that should be sent right after each GQL_CONNECTION_ACK processed and then periodically to keep the client connection alive. // The client starts to consider the keep alive message only upon the first received keep alive message from the server. GQLConnectionKeepAlive OperationMessageType = "ka" // Client sends this message to terminate the connection. GQLConnectionTerminate OperationMessageType = "connection_terminate" // @deprecated: use GQLConnectionInit instead. GQL_CONNECTION_INIT = GQLConnectionInit // @deprecated: use GQLConnectionError instead. GQL_CONNECTION_ERROR = GQLConnectionError // @deprecated: use GQLStart instead. GQL_START = GQLStart // @deprecated: use GQLStop instead. GQL_STOP = GQLStop // @deprecated: use GQLError instead. GQL_ERROR = GQLError // @deprecated: use GQLData instead. GQL_DATA = GQLData // @deprecated: use GQLComplete instead. GQL_COMPLETE = GQLComplete // @deprecated: use GQLConnectionKeepAlive instead. GQL_CONNECTION_KEEP_ALIVE = GQLConnectionKeepAlive // @deprecated: use GQLConnectionAck instead. GQL_CONNECTION_ACK = GQLConnectionAck // @deprecated: use GQLConnectionTerminate instead. GQL_CONNECTION_TERMINATE = GQLConnectionTerminate )
Variables ¶
var ( // ErrSubscriptionStopped a special error which forces the subscription stop. ErrSubscriptionStopped = errors.New("subscription stopped") // ErrSubscriptionNotExists an error denoting that subscription does not exist. ErrSubscriptionNotExists = errors.New("subscription does not exist") // ErrWebsocketConnectionIdleTimeout indicates that the websocket connection has not received any new messages for a long interval. ErrWebsocketConnectionIdleTimeout = errors.New("websocket connection idle timeout") )
Functions ¶
func ConstructMutation ¶ added in v0.6.4
func ConstructMutation( v interface{}, variables map[string]interface{}, options ...Option, ) (string, error)
ConstructMutation build GraphQL mutation string from struct and variables.
func ConstructQuery ¶ added in v0.6.4
func ConstructQuery( v interface{}, variables map[string]interface{}, options ...Option, ) (string, error)
ConstructQuery build GraphQL query string from struct and variables.
func ConstructSubscription ¶ added in v0.6.4
func ConstructSubscription( v interface{}, variables map[string]interface{}, options ...Option, ) (string, string, error)
ConstructSubscription build GraphQL subscription string from struct and variables.
func UnmarshalGraphQL ¶ added in v0.6.4
This function is re-exported from the internal package.
Types ¶
type Boolean ¶
type Boolean bool
Boolean represents true or false values. Deprecated.
func NewBoolean ¶
NewBoolean is a helper to make a new *Boolean. Deprecated.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a GraphQL client.
func NewClient ¶
func NewClient(url string, httpClient Doer, options ...ClientOption) *Client
NewClient creates a GraphQL client targeting the specified GraphQL server URL. If httpClient is nil, then http.DefaultClient is used.
func (*Client) Exec ¶ added in v0.7.0
func (c *Client) Exec( ctx context.Context, query string, v any, variables map[string]any, options ...Option, ) error
Executes a pre-built query and unmarshals the response into v. Unlike the Query method you have to specify in the query the fields that you want to receive as they are not inferred from v. This method is useful if you need to build the query dynamically.
func (*Client) ExecRaw ¶ added in v0.8.0
func (c *Client) ExecRaw( ctx context.Context, query string, variables map[string]any, options ...Option, ) ([]byte, error)
Executes a pre-built query and returns the raw json message. Unlike the Query method you have to specify in the query the fields that you want to receive as they are not inferred from the interface. This method is useful if you need to build the query dynamically.
func (*Client) ExecRawWithExtensions ¶ added in v0.13.0
func (c *Client) ExecRawWithExtensions( ctx context.Context, query string, variables map[string]any, options ...Option, ) ([]byte, []byte, error)
ExecRawWithExtensions execute a pre-built query and returns the raw json message and a map with extensions (values also as raw json objects). Unlike the Query method you have to specify in the query the fields that you want to receive as they are not inferred from the interface. This method is useful if you need to build the query dynamically.
func (*Client) Mutate ¶
func (c *Client) Mutate( ctx context.Context, m any, variables map[string]any, options ...Option, ) error
Mutate executes a single GraphQL mutation request, with a mutation derived from m, populating the response into it. m should be a pointer to struct that corresponds to the GraphQL schema.
func (*Client) MutateRaw ¶ added in v0.2.0
func (c *Client) MutateRaw( ctx context.Context, m any, variables map[string]any, options ...Option, ) ([]byte, error)
MutateRaw executes a single GraphQL mutation request, with a mutation derived from m, populating the response into it. m should be a pointer to struct that corresponds to the GraphQL schema. return raw bytes message.
func (*Client) NamedMutateRaw ¶ added in v0.2.0
func (c *Client) NamedMutateRaw( ctx context.Context, name string, m any, variables map[string]any, options ...Option, ) ([]byte, error)
NamedMutateRaw executes a single GraphQL mutation request, with operation name return raw bytes message.
func (*Client) NamedQueryRaw ¶ added in v0.2.0
func (c *Client) NamedQueryRaw( ctx context.Context, name string, q any, variables map[string]any, options ...Option, ) ([]byte, error)
NamedQueryRaw executes a single GraphQL query request, with operation name return raw bytes message.
func (*Client) Query ¶
func (c *Client) Query( ctx context.Context, q any, variables map[string]any, options ...Option, ) error
Query executes a single GraphQL query request, with a query derived from q, populating the response into it. q should be a pointer to struct that corresponds to the GraphQL schema.
func (*Client) QueryRaw ¶ added in v0.2.0
func (c *Client) QueryRaw( ctx context.Context, q any, variables map[string]any, options ...Option, ) ([]byte, error)
Query executes a single GraphQL query request, with a query derived from q, populating the response into it. q should be a pointer to struct that corresponds to the GraphQL schema. return raw bytes message.
func (*Client) WithDebug ¶ added in v0.6.4
WithDebug enable debug mode to print internal error detail.
func (*Client) WithRequestModifier ¶ added in v0.6.0
func (c *Client) WithRequestModifier(f RequestModifier) *Client
(i.e. different authentication headers for multitenant applications).
type ClientOption ¶ added in v0.14.0
type ClientOption func(c *Client)
ClientOption is used to configure client with options.
func WithRetry ¶ added in v0.14.0
func WithRetry(maxRetries int) ClientOption
WithRetry creates an option to indicate the number of retries.
func WithRetryBaseDelay ¶ added in v0.14.0
func WithRetryBaseDelay(delay time.Duration) ClientOption
WithRetryBaseDelay creates an option to indicate the base delay factor of retries.
func WithRetryExponentialRate ¶ added in v0.14.0
func WithRetryExponentialRate(rate float64) ClientOption
WithRetryExponentialRate creates an option to indicate the exponential rate of retries.
func WithRetryHTTPStatus ¶ added in v0.14.0
func WithRetryHTTPStatus(status []int) ClientOption
WithRetryHTTPStatus creates an option to retry if the HTTP response status is in the status slice.
func WithRetryOnGraphQLError ¶ added in v0.14.0
func WithRetryOnGraphQLError(callback func(errs Errors) bool) ClientOption
WithRetryOnGraphQLError creates a callback option to check if the graphql error is retryable.
type CreateWebSocketConnFunc ¶ added in v0.14.0
type CreateWebSocketConnFunc func(ctx context.Context, endpoint string, options WebsocketOptions) (WebsocketConn, error)
CreateWebSocketConnFunc represents the function interface to create a WebSocket connection.
type Doer ¶ added in v0.9.0
Doer interface has the method required to use a type as custom http client. The net/*http.Client type satisfies this interface.
type Error ¶ added in v0.6.4
type Error struct { Message string `json:"message"` Extensions map[string]any `json:"extensions"` Locations []struct { Line int `json:"line"` Column int `json:"column"` } `json:"locations"` Path []any `json:"path"` // contains filtered or unexported fields }
type Errors ¶ added in v0.5.2
type Errors []Error
errors represents the "errors" array in a response from a GraphQL server. If returned via error interface, the slice is expected to contain at least 1 element.
Specification: https://facebook.github.io/graphql/#sec-Errors.
type Float ¶
type Float float64
Float represents signed double-precision fractional values as specified by IEEE 754. Deprecated.
type GraphQLRequestPayload ¶ added in v0.9.0
type GraphQLRequestPayload struct { Query string `json:"query"` Variables map[string]interface{} `json:"variables,omitempty"` OperationName string `json:"operationName,omitempty"` }
GraphQLRequestPayload represents the graphql JSON-encoded request body https://graphql.org/learn/serving-over-http/#post-request
type GraphQLType ¶ added in v0.7.0
type GraphQLType interface {
GetGraphQLType() string
}
GraphQLType interface is used to specify the GraphQL type associated with a particular type. If a type implements this interface, the name of the variable used while creating the GraphQL query will be the output of the function defined below.
In the current implementation, the GetGraphQLType function is applied to the zero value of the type to get the GraphQL type. So those who are implementing the function should avoid referencing the value of the type inside the function. Further, by this design, the output of the GetGraphQLType function will be a constant.
type ID ¶
type ID string
ID represents a unique identifier that is Base64 obfuscated. It is often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as "VXNlci0xMA==") or integer (such as 4) input value will be accepted as an ID.
type Int ¶
type Int int32
Int represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. Deprecated.
type NetworkError ¶ added in v0.13.0
type NetworkError struct {
// contains filtered or unexported fields
}
func (NetworkError) Body ¶ added in v0.13.0
func (e NetworkError) Body() string
func (NetworkError) Error ¶ added in v0.13.0
func (e NetworkError) Error() string
func (NetworkError) StatusCode ¶ added in v0.13.0
func (e NetworkError) StatusCode() int
type OperationMessage ¶
type OperationMessage struct { ID string `json:"id,omitempty"` Type OperationMessageType `json:"type"` Payload json.RawMessage `json:"payload,omitempty"` }
OperationMessage represents a subscription operation message.
func (OperationMessage) String ¶
func (om OperationMessage) String() string
String overrides the default Stringer to return json string for debugging.
type OperationMessageType ¶
type OperationMessageType string
OperationMessageType represents a subscription message enum type.
const ( // Indicates that the client wants to establish a connection within the existing socket. // This connection is not the actual WebSocket communication channel, but is rather a frame within it asking the server to allow future operation requests. GQLConnectionInit OperationMessageType = "connection_init" // Expected response to the ConnectionInit message from the client acknowledging a successful connection with the server. GQLConnectionAck OperationMessageType = "connection_ack" // The Ping message can be sent at any time within the established socket. GQLPing OperationMessageType = "ping" // The response to the Ping message. Must be sent as soon as the Ping message is received. GQLPong OperationMessageType = "pong" // Requests an operation specified in the message payload. This message provides a unique ID field to connect published messages to the operation requested by this message. GQLSubscribe OperationMessageType = "subscribe" // Operation execution result(s) from the source stream created by the binding Subscribe message. After all results have been emitted, the Complete message will follow indicating stream completion. GQLNext OperationMessageType = "next" // Operation execution error(s) in response to the Subscribe message. // This can occur before execution starts, usually due to validation errors, or during the execution of the request. GQLError OperationMessageType = "error" // indicates that the requested operation execution has completed. If the server dispatched the Error message relative to the original Subscribe message, no Complete message will be emitted. GQLComplete OperationMessageType = "complete" )
type Option ¶ added in v0.4.0
type Option interface { // Type returns the supported type of the renderer // available types: operation_name and operation_directive Type() OptionType }
They are optional parts. By default GraphQL queries can request data without them.
func BindExtensions ¶ added in v0.13.0
BindExtensions bind the struct pointer to decode extensions from json response.
func BindResponseHeaders ¶ added in v0.14.0
BindExtensionsBindResponseHeaders bind the header response to the pointer.
func OperationName ¶ added in v0.4.0
OperationName creates the operation name option.
type OptionType ¶ added in v0.4.0
type OptionType string
OptionType represents the logic of graphql query construction.
const (
OptionTypeOperationDirective OptionType = "operation_directive"
)
type RequestModifier ¶ added in v0.6.0
headers amongst other things.
type String ¶
type String string
String represents textual data as UTF-8 character sequences. This type is most often used by GraphQL to represent free-form human-readable text. Deprecated.
type Subscription ¶ added in v0.9.0
type Subscription struct {
// contains filtered or unexported fields
}
Subscription stores the subscription declaration and its state.
func (Subscription) Clone ¶ added in v0.14.0
func (s Subscription) Clone() Subscription
The ID is newly generated to avoid subscription id conflict errors from the server.
func (Subscription) GetHandler ¶ added in v0.9.0
func (s Subscription) GetHandler() func(data []byte, err error)
GetHandler a public getter for the subscription handler.
func (Subscription) GetID ¶ added in v0.9.2
func (s Subscription) GetID() string
GetID returns the subscription ID.
func (Subscription) GetKey ¶ added in v0.9.2
func (s Subscription) GetKey() string
It is used for searching because the subscription id is refreshed whenever the client reset.
func (Subscription) GetPayload ¶ added in v0.9.0
func (s Subscription) GetPayload() GraphQLRequestPayload
GetPayload returns the graphql request payload.
func (Subscription) GetStatus ¶ added in v0.9.2
func (s Subscription) GetStatus() SubscriptionStatus
GetStatus a public getter for the subscription status.
func (*Subscription) SetStatus ¶ added in v0.9.2
func (s *Subscription) SetStatus(status SubscriptionStatus)
SetStatus a public getter for the subscription status.
type SubscriptionClient ¶
type SubscriptionClient struct {
// contains filtered or unexported fields
}
SubscriptionClient is a GraphQL subscription client.
func NewSubscriptionClient ¶
func NewSubscriptionClient(url string) *SubscriptionClient
NewSubscriptionClient constructs new subscription client.
func (*SubscriptionClient) Close ¶
func (sc *SubscriptionClient) Close() error
Close closes all subscription channel and websocket as well.
func (*SubscriptionClient) Exec ¶ added in v0.7.1
func (sc *SubscriptionClient) Exec( query string, variables map[string]interface{}, handler func(message []byte, err error) error, ) (string, error)
Exec sends start message to server and open a channel to receive data, with raw query.
func (*SubscriptionClient) GetContext ¶
func (sc *SubscriptionClient) GetContext() context.Context
GetContext returns current context of subscription client.
func (*SubscriptionClient) GetReadTimeout ¶ added in v0.14.0
func (sc *SubscriptionClient) GetReadTimeout() time.Duration
GetReadTimeout returns read timeout of websocket client.
func (*SubscriptionClient) GetSubscription ¶ added in v0.12.0
func (sc *SubscriptionClient) GetSubscription(id string) *Subscription
GetSubscription get the subscription state by id.
func (*SubscriptionClient) GetSubscriptions ¶ added in v0.12.1
func (sc *SubscriptionClient) GetSubscriptions() map[string]Subscription
GetSubscriptions get the list of active subscriptions.
func (*SubscriptionClient) GetTimeout ¶
func (sc *SubscriptionClient) GetTimeout() time.Duration
GetTimeout returns write timeout of websocket client. Deprecated: use GetWriteTimeout instead.
func (*SubscriptionClient) GetURL ¶
func (sc *SubscriptionClient) GetURL() string
GetURL returns GraphQL server's URL.
func (*SubscriptionClient) GetWebSocketStatusCode ¶ added in v0.14.0
func (sc *SubscriptionClient) GetWebSocketStatusCode(err error) websocket.StatusCode
GetWebSocketStatusCode gets the status code of the Websocket error.
func (*SubscriptionClient) GetWriteTimeout ¶ added in v0.14.0
func (sc *SubscriptionClient) GetWriteTimeout() time.Duration
GetWriteTimeout returns write timeout of websocket client.
func (*SubscriptionClient) IsConnectionInitialisationTimeout ¶ added in v0.14.0
func (sc *SubscriptionClient) IsConnectionInitialisationTimeout(err error) bool
IsConnectionInitialisationTimeoutError checks if the input error is ConnectionInitialisationTimeout.
func (*SubscriptionClient) IsInternalConnectionError ¶ added in v0.14.0
func (sc *SubscriptionClient) IsInternalConnectionError(err error) bool
IsInternalConnectionError checks if the input error is an internal error status.
func (*SubscriptionClient) IsInvalidMessageError ¶ added in v0.14.0
func (sc *SubscriptionClient) IsInvalidMessageError(err error) bool
IsInvalidMessageError checks if the input error is an invalid message status.
func (*SubscriptionClient) IsStatusSubscriberAlreadyExists ¶ added in v0.14.0
func (sc *SubscriptionClient) IsStatusSubscriberAlreadyExists(err error) bool
IsStatusSubscriberAlreadyExists checks if the input error has a SubscriberAlreadyExists status.
func (*SubscriptionClient) IsTooManyInitialisationRequests ¶ added in v0.14.0
func (sc *SubscriptionClient) IsTooManyInitialisationRequests(err error) bool
IsTooManyInitialisationRequests checks if the input error has a TooManyInitialisationRequests status.
func (*SubscriptionClient) IsUnauthorized ¶ added in v0.14.0
func (sc *SubscriptionClient) IsUnauthorized(err error) bool
IsUnauthorized checks if the input error is unauthorized.
func (*SubscriptionClient) IsWebsocketConnectionIdleTimeout ¶ added in v0.14.0
func (sc *SubscriptionClient) IsWebsocketConnectionIdleTimeout(err error) bool
IsWebsocketConnectionIdleTimeout checks if the input error is ErrWebsocketConnectionIdleTimeout.
func (*SubscriptionClient) NamedSubscribe
deprecated
func (*SubscriptionClient) OnConnected ¶
func (sc *SubscriptionClient) OnConnected(fn func()) *SubscriptionClient
OnConnected event is triggered when the websocket connected to GraphQL server successfully.
func (*SubscriptionClient) OnConnectionAlive ¶ added in v0.9.2
func (sc *SubscriptionClient) OnConnectionAlive(fn func()) *SubscriptionClient
OnConnectionAlive event is triggered when the websocket receive a connection alive message (differs per protocol).
func (*SubscriptionClient) OnDisconnected ¶
func (sc *SubscriptionClient) OnDisconnected(fn func()) *SubscriptionClient
OnDisconnected event is triggered when the websocket client was disconnected.
func (*SubscriptionClient) OnError ¶
func (sc *SubscriptionClient) OnError( onError func(sc *SubscriptionClient, err error) error, ) *SubscriptionClient
If returns error, the websocket connection will be terminated.
func (*SubscriptionClient) OnSubscriptionComplete ¶ added in v0.9.2
func (sc *SubscriptionClient) OnSubscriptionComplete( fn func(sub Subscription), ) *SubscriptionClient
OnSubscriptionComplete event is triggered when the subscription receives a terminated message from the server.
func (*SubscriptionClient) Run ¶
func (sc *SubscriptionClient) Run() error
Run start the WebSocket client and subscriptions. If the client is running, recalling this function will return errors. If this function is run with goroutine, it can be stopped after closed.
func (*SubscriptionClient) RunWithContext ¶ added in v0.14.0
func (sc *SubscriptionClient) RunWithContext(ctx context.Context) error
RunWithContext start the WebSocket client and subscriptions. If the client is running, recalling this function will return errors. If this function is run with goroutine, it can be stopped after closed.
func (*SubscriptionClient) Subscribe ¶
func (sc *SubscriptionClient) Subscribe( v interface{}, variables map[string]interface{}, handler func(message []byte, err error) error, options ...Option, ) (string, error)
The function returns subscription ID and error. You can use subscription ID to unsubscribe the subscription.
func (*SubscriptionClient) SubscribeRaw
deprecated
added in
v0.3.0
func (*SubscriptionClient) Unsubscribe ¶
func (sc *SubscriptionClient) Unsubscribe(id string) error
The input parameter is subscription ID that is returned from Subscribe function.
func (*SubscriptionClient) WithConnectionInitialisationTimeout ¶ added in v0.14.0
func (sc *SubscriptionClient) WithConnectionInitialisationTimeout( timeout time.Duration, ) *SubscriptionClient
WithConnectionInitialisationTimeout updates timeout for the connection initialisation.
func (*SubscriptionClient) WithConnectionParams ¶
func (sc *SubscriptionClient) WithConnectionParams( params map[string]interface{}, ) *SubscriptionClient
It's usually used for authentication handshake.
func (*SubscriptionClient) WithConnectionParamsFn ¶ added in v0.9.0
func (sc *SubscriptionClient) WithConnectionParamsFn( fn func() map[string]interface{}, ) *SubscriptionClient
It's suitable for short-lived access tokens that need to be refreshed frequently.
func (*SubscriptionClient) WithCustomProtocol ¶ added in v0.14.0
func (sc *SubscriptionClient) WithCustomProtocol( protocol SubscriptionProtocol, ) *SubscriptionClient
WithCustomProtocol changes the subscription protocol that implements the SubscriptionProtocol interface.
func (*SubscriptionClient) WithExitWhenNoSubscription ¶ added in v0.9.2
func (sc *SubscriptionClient) WithExitWhenNoSubscription(value bool) *SubscriptionClient
WithExitWhenNoSubscription the client should exit when all subscriptions were closed.
func (*SubscriptionClient) WithKeepAlive ¶ added in v0.10.1
func (sc *SubscriptionClient) WithKeepAlive(interval time.Duration) *SubscriptionClient
WithKeepAlive programs the websocket to ping on the specified interval. Deprecated: rename to WithWebSocketKeepAlive to avoid confusing with the keep-alive specification of the subscription protocol.
func (*SubscriptionClient) WithLog ¶
func (sc *SubscriptionClient) WithLog(logger func(args ...interface{})) *SubscriptionClient
WithLog sets logging function to print out received messages. By default, nothing is printed.
func (*SubscriptionClient) WithProtocol ¶ added in v0.9.0
func (sc *SubscriptionClient) WithProtocol(protocol SubscriptionProtocolType) *SubscriptionClient
By default the subscription client uses the subscriptions-transport-ws protocol.
func (*SubscriptionClient) WithReadLimit ¶
func (sc *SubscriptionClient) WithReadLimit(limit int64) *SubscriptionClient
WithReadLimit set max size of response message.
func (*SubscriptionClient) WithReadTimeout ¶ added in v0.14.0
func (sc *SubscriptionClient) WithReadTimeout(timeout time.Duration) *SubscriptionClient
WithReadTimeout updates read timeout of websocket client.
func (*SubscriptionClient) WithRetryDelay ¶ added in v0.10.1
func (sc *SubscriptionClient) WithRetryDelay(delay time.Duration) *SubscriptionClient
WithRetryDelay set the delay time before retrying the connection.
func (*SubscriptionClient) WithRetryStatusCodes ¶ added in v0.9.2
func (sc *SubscriptionClient) WithRetryStatusCodes(codes ...string) *SubscriptionClient
the input parameter can be number string or range, e.g 4000-5000.
func (*SubscriptionClient) WithRetryTimeout ¶
func (sc *SubscriptionClient) WithRetryTimeout(timeout time.Duration) *SubscriptionClient
The zero value means unlimited timeout.
func (*SubscriptionClient) WithSyncMode ¶ added in v0.10.1
func (sc *SubscriptionClient) WithSyncMode(value bool) *SubscriptionClient
WithSyncMode subscription messages are executed in sequence (without goroutine).
func (*SubscriptionClient) WithTimeout ¶
func (sc *SubscriptionClient) WithTimeout(timeout time.Duration) *SubscriptionClient
WithTimeout updates read and write timeout of websocket client.
func (*SubscriptionClient) WithWebSocket ¶
func (sc *SubscriptionClient) WithWebSocket(fn CreateWebSocketConnFunc) *SubscriptionClient
WithWebSocket replaces customized websocket client constructor In default, subscription client uses https://github.com/coder/websocket
func (*SubscriptionClient) WithWebSocketKeepAlive ¶ added in v0.14.0
func (sc *SubscriptionClient) WithWebSocketKeepAlive(interval time.Duration) *SubscriptionClient
WithWebSocketKeepAlive programs the websocket to ping on the specified interval.
func (*SubscriptionClient) WithWebSocketOptions ¶ added in v0.6.4
func (sc *SubscriptionClient) WithWebSocketOptions(options WebsocketOptions) *SubscriptionClient
WithWebSocketOptions provides options to the websocket client.
func (*SubscriptionClient) WithWebsocketConnectionIdleTimeout ¶ added in v0.14.0
func (sc *SubscriptionClient) WithWebsocketConnectionIdleTimeout( timeout time.Duration, ) *SubscriptionClient
WithWebsocketConnectionIdleTimeout updates for the websocket connection idle timeout.
func (*SubscriptionClient) WithWriteTimeout ¶ added in v0.14.0
func (sc *SubscriptionClient) WithWriteTimeout(timeout time.Duration) *SubscriptionClient
WithWriteTimeout updates write timeout of websocket client.
func (*SubscriptionClient) WithoutLogTypes ¶
func (sc *SubscriptionClient) WithoutLogTypes(types ...OperationMessageType) *SubscriptionClient
WithoutLogTypes these operation types won't be printed.
type SubscriptionContext ¶ added in v0.9.0
SubscriptionContext represents a shared context for protocol implementations with the websocket connection inside.
func (*SubscriptionContext) Cancel ¶ added in v0.9.1
func (sc *SubscriptionContext) Cancel()
SetCancel set the cancel function of the inner context.
func (*SubscriptionContext) Close ¶ added in v0.9.0
func (sc *SubscriptionContext) Close() error
Close closes the context and the inner websocket connection if exists.
func (*SubscriptionContext) GetAcknowledge ¶ added in v0.9.0
func (sc *SubscriptionContext) GetAcknowledge() bool
GetAcknowledge get the acknowledge status.
func (*SubscriptionContext) GetSubscription ¶ added in v0.9.0
func (sc *SubscriptionContext) GetSubscription(id string) *Subscription
GetSubscription get the subscription state by id.
func (*SubscriptionContext) GetSubscriptions ¶ added in v0.9.0
func (sc *SubscriptionContext) GetSubscriptions() map[string]Subscription
GetSubscription get all available subscriptions in the context.
func (*SubscriptionContext) GetSubscriptionsLength ¶ added in v0.9.1
func (sc *SubscriptionContext) GetSubscriptionsLength(status []SubscriptionStatus) int
GetSubscriptionsLength returns the length of subscriptions by status.
func (*SubscriptionContext) GetWebsocketConn ¶ added in v0.9.0
func (sc *SubscriptionContext) GetWebsocketConn() WebsocketConn
GetWebsocketConn get the current websocket connection.
func (*SubscriptionContext) IsClosed ¶ added in v0.14.0
func (sc *SubscriptionContext) IsClosed() bool
IsClosed get the closed status.
func (*SubscriptionContext) Log ¶ added in v0.9.0
func (sc *SubscriptionContext) Log( message interface{}, metadata map[string]any, opType OperationMessageType, )
Log prints condition logging with message type filters.
func (*SubscriptionContext) OnConnected ¶ added in v0.9.0
func (sc *SubscriptionContext) OnConnected()
OnConnected executes the OnConnected callback if exists.
func (*SubscriptionContext) OnConnectionAlive ¶ added in v0.9.2
func (sc *SubscriptionContext) OnConnectionAlive()
OnConnectionAlive executes the OnConnectionAlive callback if exists.
func (*SubscriptionContext) OnDisconnected ¶ added in v0.9.2
func (sc *SubscriptionContext) OnDisconnected()
OnDisconnected executes the OnDisconnected callback if exists.
func (*SubscriptionContext) OnSubscriptionComplete ¶ added in v0.9.2
func (sc *SubscriptionContext) OnSubscriptionComplete(subscription Subscription)
OnSubscriptionComplete executes the OnSubscriptionComplete callback if exists.
func (*SubscriptionContext) Send ¶ added in v0.9.0
func (sc *SubscriptionContext) Send(message interface{}, opType OperationMessageType) error
Send emits a message to the graphql server.
func (*SubscriptionContext) SetAcknowledge ¶ added in v0.9.0
func (sc *SubscriptionContext) SetAcknowledge(value bool)
SetAcknowledge set the acknowledge status.
func (*SubscriptionContext) SetClosed ¶ added in v0.14.0
func (sc *SubscriptionContext) SetClosed(value bool)
SetAcknowledge set the acknowledge status.
func (*SubscriptionContext) SetSubscription ¶ added in v0.9.0
func (sc *SubscriptionContext) SetSubscription(key string, sub *Subscription)
if subscription is nil, removes the subscription from the map.
func (*SubscriptionContext) SetWebsocketConn ¶ added in v0.9.0
func (sc *SubscriptionContext) SetWebsocketConn(conn WebsocketConn)
SetWebsocketConn set the current websocket connection.
type SubscriptionProtocol ¶ added in v0.9.0
type SubscriptionProtocol interface { // GetSubprotocols returns subprotocol names of the subscription transport // The graphql server depends on the Sec-WebSocket-Protocol header to return the correct message specification GetSubprotocols() []string // ConnectionInit sends a initial request to establish a connection within the existing socket ConnectionInit(ctx *SubscriptionContext, connectionParams map[string]interface{}) error // Subscribe requests an graphql operation specified in the payload message Subscribe(ctx *SubscriptionContext, sub Subscription) error // Unsubscribe sends a request to stop listening and complete the subscription Unsubscribe(ctx *SubscriptionContext, sub Subscription) error // OnMessage listens ongoing messages from server OnMessage(ctx *SubscriptionContext, subscription Subscription, message OperationMessage) error // Close terminates all subscriptions of the current websocket Close(ctx *SubscriptionContext) error }
SubscriptionProtocol abstracts the life-cycle of subscription protocol implementation for a specific transport protocol.
type SubscriptionProtocolType ¶ added in v0.9.0
type SubscriptionProtocolType string
SubscriptionProtocolType represents the protocol specification enum of the subscription.
type SubscriptionStatus ¶ added in v0.9.2
type SubscriptionStatus int32
internal subscription status.
type WebSocketStats ¶ added in v0.14.2
type WebSocketStats struct { TotalActiveConnections int TotalClosedConnections int ActiveConnectionIDs []uuid.UUID }
WebSocketStats hold statistic data of WebSocket connections for subscription.
func GetWebSocketStats ¶ added in v0.14.2
func GetWebSocketStats() WebSocketStats
GetWebSocketStats gets the websocket stats.
type WebsocketConn ¶
type WebsocketConn interface { ReadJSON(v interface{}) error WriteJSON(v interface{}) error Ping() error Close() error // SetReadLimit sets the maximum size in bytes for a message read from the peer. If a // message exceeds the limit, the connection sends a close message to the peer // and returns ErrReadLimit to the application. SetReadLimit(limit int64) // GetCloseStatus tries to get WebSocket close status from error // return -1 if the error is unknown // https://www.iana.org/assignments/websocket/websocket.xhtml GetCloseStatus(err error) int32 }
WebsocketHandler abstracts WebSocket connection functions ReadJSON and WriteJSON data of a frame from the WebSocket connection. Close the WebSocket connection.
type WebsocketHandler ¶ added in v0.3.0
default websocket handler implementation using https://github.com/coder/websocket
func (*WebsocketHandler) Close ¶ added in v0.3.0
func (wh *WebsocketHandler) Close() error
Close implements the function to close the websocket connection.
func (*WebsocketHandler) GetCloseStatus ¶ added in v0.9.2
func (wh *WebsocketHandler) GetCloseStatus(err error) int32
GetCloseStatus tries to get WebSocket close status from error https://www.iana.org/assignments/websocket/websocket.xhtml
func (WebsocketHandler) GetID ¶ added in v0.14.2
func (wh WebsocketHandler) GetID() uuid.UUID
GetID gets the identity of the Websocket connection.
func (*WebsocketHandler) Ping ¶ added in v0.10.1
func (wh *WebsocketHandler) Ping() error
Ping sends a ping to the peer and waits for a pong.
func (*WebsocketHandler) ReadJSON ¶ added in v0.3.0
func (wh *WebsocketHandler) ReadJSON(v interface{}) error
ReadJSON implements the function to decode the json message from the server.
func (*WebsocketHandler) WriteJSON ¶ added in v0.3.0
func (wh *WebsocketHandler) WriteJSON(v interface{}) error
WriteJSON implements the function to encode and send message in json format to the server.
type WebsocketOptions ¶ added in v0.6.4
type WebsocketOptions struct { // HTTPClient is used for the connection. // Its Transport must return writable bodies for WebSocket handshakes. // http.Transport does beginning with Go 1.12. HTTPClient *http.Client // HTTPHeader specifies the HTTP headers included in the handshake request. HTTPHeader http.Header // Host optionally overrides the Host HTTP header to send. If empty, the value // of URL.Host will be used. Host string // CompressionMode controls the compression mode. // Defaults to CompressionDisabled. // // See docs on CompressionMode for details. CompressionMode websocket.CompressionMode // CompressionThreshold controls the minimum size of a message before compression is applied. // // Defaults to 512 bytes for CompressionNoContextTakeover and 128 bytes // for CompressionContextTakeover. CompressionThreshold int // ReadTimeout controls the read timeout of the websocket connection. ReadTimeout time.Duration // WriteTimeout controls the read timeout of the websocket connection. WriteTimeout time.Duration // Subprotocols hold subprotocol names of the subscription transport // The graphql server depends on the Sec-WebSocket-Protocol header to return the correct message specification Subprotocols []string }
WebsocketOptions allows implementation agnostic configuration of the websocket client.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
example
|
|
graphql-ws-bc/client
subscription is a test program currently being used for developing graphql package.
|
subscription is a test program currently being used for developing graphql package. |
graphqldev
Module
|
|
subscription
Module
|
|
Package ident provides functions for parsing and converting identifier names between various naming convention.
|
Package ident provides functions for parsing and converting identifier names between various naming convention. |
pkg
|
|
jsonutil
Package jsonutil provides a function for decoding JSON into a GraphQL query data structure.
|
Package jsonutil provides a function for decoding JSON into a GraphQL query data structure. |