Gathering detailed insights and metrics for @hiveteams/subscriptions-transport-ws
Gathering detailed insights and metrics for @hiveteams/subscriptions-transport-ws
Gathering detailed insights and metrics for @hiveteams/subscriptions-transport-ws
Gathering detailed insights and metrics for @hiveteams/subscriptions-transport-ws
npm install @hiveteams/subscriptions-transport-ws
Typescript
Module System
Node Version
NPM Version
71.7
Supply Chain
99
Quality
82.4
Maintenance
50
Vulnerability
100
License
TypeScript (99.8%)
JavaScript (0.2%)
Total Downloads
35,779
Last Day
1
Last Week
3
Last Month
313
Last Year
10,099
1,517 Stars
900 Commits
341 Forks
70 Watching
6 Branches
107 Contributors
Latest Version
1.3.11
Package Id
@hiveteams/subscriptions-transport-ws@1.3.11
Unpacked Size
267.42 kB
Size
62.71 kB
File Count
46
NPM Version
6.14.18
Node Version
14.21.3
Publised On
22 Sept 2023
Cumulative downloads
Total Downloads
Last day
0%
1
Compared to previous day
Last week
200%
3
Compared to previous week
Last month
-71%
313
Compared to previous month
Last year
-47.1%
10,099
Compared to previous year
5
1
(Work in progress!)
A GraphQL WebSocket server and client to facilitate GraphQL queries, mutations and subscriptions over WebSocket.
subscriptions-transport-ws
is an extension for GraphQL, and you can use it with any GraphQL client and server (not only Apollo).
See GitHunt-API and GitHunt-React for an example server and client integration.
Start by installing the package, using Yarn or NPM.
Using Yarn:
$ yarn add subscriptions-transport-ws
Or, using NPM:
$ npm install --save subscriptions-transport-ws
Note that you need to use this package on both GraphQL client and server.
This command also installs this package's dependencies, including
graphql-subscriptions
.
Starting with the server, create a new simple PubSub
instance. We will later use this PubSub
to publish and subscribe to data changes.
1import { PubSub } from 'graphql-subscriptions'; 2 3export const pubsub = new PubSub();
Now, create SubscriptionServer
instance, with your GraphQL schema
, execute
and subscribe
(from graphql-js
package):
1import { createServer } from 'http'; 2import { SubscriptionServer } from 'subscriptions-transport-ws'; 3import { execute, subscribe } from 'graphql'; 4import { schema } from './my-schema'; 5 6const WS_PORT = 5000; 7 8// Create WebSocket listener server 9const websocketServer = createServer((request, response) => { 10 response.writeHead(404); 11 response.end(); 12}); 13 14// Bind it to port and start listening 15websocketServer.listen(WS_PORT, () => console.log( 16 `Websocket Server is now running on http://localhost:${WS_PORT}` 17)); 18 19const subscriptionServer = SubscriptionServer.create( 20 { 21 schema, 22 execute, 23 subscribe, 24 }, 25 { 26 server: websocketServer, 27 path: '/graphql', 28 }, 29);
Please refer to graphql-subscriptions
documentation for how to create your GraphQL subscriptions, and how to publish data.
When using this package for client side, you can choose either use HTTP request for Queries and Mutation and use the WebSocket for subscriptions only, or create a full transport that handles all type of GraphQL operations over the socket.
To start with a full WebSocket transport, that handles all types of GraphQL operations, import and create an instance of SubscriptionClient
.
Then, create your ApolloClient
instance and use the SubscriptionsClient
instance as network interface:
1import { SubscriptionClient } from 'subscriptions-transport-ws'; 2import ApolloClient from 'apollo-client'; 3 4const GRAPHQL_ENDPOINT = 'ws://localhost:3000/graphql'; 5 6const client = new SubscriptionClient(GRAPHQL_ENDPOINT, { 7 reconnect: true, 8}); 9 10const apolloClient = new ApolloClient({ 11 networkInterface: client, 12}); 13
To start with a hybrid WebSocket transport, that handles only subscription
s over WebSocket, create your SubscriptionClient
and a regular HTTP network interface, then extend your network interface to use the WebSocket client for GraphQL subscriptions:
1import {SubscriptionClient, addGraphQLSubscriptions} from 'subscriptions-transport-ws';
2import ApolloClient, {createNetworkInterface} from 'apollo-client';
3
4// Create regular NetworkInterface by using apollo-client's API:
5const networkInterface = createNetworkInterface({
6 uri: 'http://localhost:3000' // Your GraphQL endpoint
7});
8
9// Create WebSocket client
10const wsClient = new SubscriptionClient(`ws://localhost:5000/`, {
11 reconnect: true,
12 connectionParams: {
13 // Pass any arguments you want for initialization
14 }
15});
16
17// Extend the network interface with the WebSocket
18const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
19 networkInterface,
20 wsClient
21);
22
23// Finally, create your ApolloClient instance with the modified network interface
24const apolloClient = new ApolloClient({
25 networkInterface: networkInterfaceWithSubscriptions
26});
Now, when you want to use subscriptions in client side, use your ApolloClient
instance, with subscribe
or query
subscribeToMore
:
1apolloClient.subscribe({ 2 query: gql` 3 subscription onNewItem { 4 newItemCreated { 5 id 6 } 7 }`, 8 variables: {} 9}).subscribe({ 10 next (data) { 11 // Notify your application with the new arrived data 12 } 13});
1apolloClient.query({ 2 query: ITEM_LIST_QUERY, 3 variables: {} 4}).subscribeToMore({ 5 document: gql` 6 subscription onNewItem { 7 newItemCreated { 8 id 9 } 10 }`, 11 variables: {}, 12 updateQuery: (prev, { subscriptionData, variables }) => { 13 // Perform updates on previousResult with subscriptionData 14 return updatedResult; 15 } 16});
If you don't use any package/modules loader, you can still use this package, by using unpkg
service, and get the client side package from:
https://unpkg.com/subscriptions-transport-ws@VERSION/browser/client.js
Replace VERSION with the latest version of the package.
You can use this package's power with GraphiQL, and subscribe to live-data stream inside GraphiQL.
If you are using the latest version of graphql-server
flavors (graphql-server-express
, graphql-server-koa
, etc...), you already can use it! Make sure to specify subscriptionsEndpoint
in GraphiQL configuration, and that's it!
For example, graphql-server-express
users need to add the following:
1app.use('/graphiql', graphiqlExpress({ 2 endpointURL: '/graphql', 3 subscriptionsEndpoint: `YOUR_SUBSCRIPTION_ENDPOINT_HERE`, 4}));
If you are using older version, or another GraphQL server, start by modifying GraphiQL static HTML, and add this package and it's fetcher from CDN:
1 <script src="//unpkg.com/subscriptions-transport-ws@0.5.4/browser/client.js"></script> 2 <script src="//unpkg.com/graphiql-subscriptions-fetcher@0.0.2/browser/client.js"></script>
Then, create SubscriptionClient
and define the fetcher:
1let subscriptionsClient = new window.SubscriptionsTransportWs.SubscriptionClient('SUBSCRIPTION_WS_URL_HERE', {
2 reconnect: true
3});
4let myCustomFetcher = window.GraphiQLSubscriptionsFetcher.graphQLFetcher(subscriptionsClient, graphQLFetcher);
graphQLFetcher
is the default fetcher, and we use it as fallback for non-subscription GraphQL operations.
And replace your GraphiQL creation logic to use the new fetcher:
1ReactDOM.render(
2 React.createElement(GraphiQL, {
3 fetcher: myCustomFetcher, // <-- here
4 onEditQuery: onEditQuery,
5 onEditVariables: onEditVariables,
6 onEditOperationName: onEditOperationName,
7 query: ${safeSerialize(queryString)},
8 response: ${safeSerialize(resultString)},
9 variables: ${safeSerialize(variablesString)},
10 operationName: ${safeSerialize(operationName)},
11 }),
12 document.body
13);
Constructor(url, options, webSocketImpl)
url: string
: url that the client will connect to, starts with ws://
or wss://
options?: Object
: optional, object to modify default client behavior
timeout?: number
: how long the client should wait in ms for a keep-alive message from the server (default 30000 ms), this parameter is ignored if the server does not send keep-alive messages. This will also be used to calculate the max connection time per connect/reconnectlazy?: boolean
: use to set lazy mode - connects only when first subscription created, and delay the socket initializationconnectionParams?: Object | Function | Promise<Object>
: object that will be available as first argument of onConnect
(in server side), if passed a function - it will call it and send the return value, if function returns as promise - it will wait until it resolves and send the resolved value.reconnect?: boolean
: automatic reconnect in case of connection errorreconnectionAttempts?: number
: how much reconnect attemptsconnectionCallback?: (error) => {}
: optional, callback that called after the first init message, with the error (if there is one)inactivityTimeout?: number
: how long the client should wait in ms, when there are no active subscriptions, before disconnecting from the server. Set to 0 to disable this behavior. (default 0)webSocketImpl?: Object
- optional, constructor for W3C compliant WebSocket implementation. Use this when your environment does not have a built-in native WebSocket (for example, with NodeJS client)request(options) => Observable<ExecutionResult>
: returns observable to execute the operation.options: {OperationOptions}
query: string
: GraphQL subscriptionvariables: Object
: GraphQL subscription variablesoperationName: string
: operation name of the subscriptioncontext: Object
: use to override context for a specific callunsubscribeAll() => void
- unsubscribes from all active subscriptions.on(eventName, callback, thisContext) => Function
eventName: string
: the name of the event, available events are: connecting
, connected
, reconnecting
, reconnected
, disconnected
and error
callback: Function
: function to be called when websocket connects and initialized.thisContext: any
: this
context to use when calling the callback function.off
method to cancel the event subscription.onConnected(callback, thisContext) => Function
- shorthand for .on('connected', ...)
callback: Function
: function to be called when websocket connects and initialized, after ACK message returned from the serverthisContext: any
: this
context to use when calling the callback function.off
method to cancel the event subscription.onReconnected(callback, thisContext) => Function
- shorthand for .on('reconnected', ...)
callback: Function
: function to be called when websocket reconnects and initialized, after ACK message returned from the serverthisContext: any
: this
context to use when calling the callback function.off
method to cancel the event subscription.onConnecting(callback, thisContext) => Function
- shorthand for .on('connecting', ...)
callback: Function
: function to be called when websocket starts it's connectionthisContext: any
: this
context to use when calling the callback function.off
method to cancel the event subscription.onReconnecting(callback, thisContext) => Function
- shorthand for .on('reconnecting', ...)
callback: Function
: function to be called when websocket starts it's reconnectionthisContext: any
: this
context to use when calling the callback function.off
method to cancel the event subscription.onDisconnected(callback, thisContext) => Function
- shorthand for .on('disconnected', ...)
callback: Function
: function to be called when websocket disconnected.thisContext: any
: this
context to use when calling the callback function.off
method to cancel the event subscription.onError(callback, thisContext) => Function
- shorthand for .on('error', ...)
callback: Function
: function to be called when an error occurs.thisContext: any
: this
context to use when calling the callback function.off
method to cancel the event subscription.close() => void
- closes the WebSocket connection manually, and ignores reconnect
logic if it was set to true
.use(middlewares: MiddlewareInterface[]) => SubscriptionClient
- adds middleware to modify OperationOptions
per each requestmiddlewares: MiddlewareInterface[]
- Array contains list of middlewares (implemented applyMiddleware
method) implementation, the SubscriptionClient
will use the middlewares to modify OperationOptions
for every operationstatus: number
: returns the current socket's readyState
Constructor(options, socketOptions | socketServer)
options: {ServerOptions}
rootValue?: any
: Root value to use when executing GraphQL root operationsschema?: GraphQLSchema
: GraphQL schema object. If not provided, you have to return the schema as a property on the object returned from onOperation
.execute?: (schema, document, rootValue, contextValue, variableValues, operationName) => Promise<ExecutionResult> | AsyncIterator<ExecutionResult>
: GraphQL execute
function, provide the default one from graphql
package. Return value of AsyncItrator
is also valid since this package also support reactive execute
methods.subscribe?: (schema, document, rootValue, contextValue, variableValues, operationName) => Promise<ExecutionResult | AsyncIterator<ExecutionResult>>
: GraphQL subscribe
function, provide the default one from graphql
package.onOperation?: (message: SubscribeMessage, params: SubscriptionOptions, webSocket: WebSocket)
: optional method to create custom params that will be used when resolving this operation. It can also be used to dynamically resolve the schema that will be used for the particular operation.onOperationComplete?: (webSocket: WebSocket, opId: string)
: optional method that called when a GraphQL operation is done (for query and mutation it's immediately, and for subscriptions when unsubscribing)onConnect?: (connectionParams: Object, webSocket: WebSocket, context: ConnectionContext)
: optional method that called when a client connects to the socket, called with the connectionParams
from the client, if the return value is an object, its elements will be added to the context. return false
or throw an exception to reject the connection. May return a Promise.onDisconnect?: (webSocket: WebSocket, context: ConnectionContext)
: optional method that called when a client disconnectskeepAlive?: number
: optional interval in ms to send KEEPALIVE
messages to all clientssocketOptions: {WebSocket.IServerOptions}
: options to pass to the WebSocket object (full docs here)
server?: HttpServer
- existing HTTP server to use (use without host
/port
)host?: string
- server hostport?: number
- server portpath?: string
- endpoint pathsocketServer: {WebSocket.Server}
: a configured server if you need more control. Can be used for integration testing with in-memory WebSocket implementation.
AsyncIterator
internally using iterall, for more information click here, or the proposalThe current version of this transport, also support a previous version of the protocol.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 1/29 approved changesets -- score normalized to 0
Reason
project is archived
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
119 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-12-23
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More