@mstuercke/api-utils 6.0.1 → 6.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mstuercke/api-utils",
3
- "version": "6.0.1",
3
+ "version": "6.0.2",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "files": [
@@ -1,4 +1,4 @@
1
- import {GoneException, PostToConnectionCommand} from '@aws-sdk/client-apigatewaymanagementapi'
1
+ import {GetConnectionCommand, GoneException, PostToConnectionCommand} from '@aws-sdk/client-apigatewaymanagementapi'
2
2
  import {type AnyTRPCRouter, callTRPCProcedure, type inferRouterContext} from '@trpc/server'
3
3
  import type {APIGatewayProxyEvent, APIGatewayProxyResult, Context} from 'aws-lambda'
4
4
  import {getApiGatewayManagementApiClient} from '../getApiGatewayManagementApiClient'
@@ -29,6 +29,12 @@ export const awsLambdaTrpcSubscriptionRequestHandler = <Router extends AnyTRPCRo
29
29
  }),
30
30
  )
31
31
  }
32
+ const isConnected = async (): Promise<boolean> => {
33
+ return getApiGatewayManagementApiClient(connection.endpoint)
34
+ .send(new GetConnectionCommand({ConnectionId: connection.connectionId}))
35
+ .then(() => true)
36
+ .catch(() => false)
37
+ }
32
38
  const stopConnection = async (): Promise<void> => {
33
39
  await sendMessage({
34
40
  id: request.id,
@@ -87,6 +93,8 @@ export const awsLambdaTrpcSubscriptionRequestHandler = <Router extends AnyTRPCRo
87
93
  },
88
94
  })
89
95
 
96
+ const pingIntervalMs = 5_000
97
+ let lastPing = Date.now()
90
98
  let stopped = false
91
99
  while (!stopped) {
92
100
  if (messageQueue.length === 0) await new Promise((resolve) => setTimeout(resolve, 10))
@@ -96,6 +104,14 @@ export const awsLambdaTrpcSubscriptionRequestHandler = <Router extends AnyTRPCRo
96
104
  await sendMessage(message)
97
105
 
98
106
  stopped = message.result.type === 'stopped'
107
+
108
+ if (Date.now() > lastPing + pingIntervalMs) {
109
+ if (!(await isConnected())) {
110
+ console.info('Connection closed by client')
111
+ stopped = true
112
+ }
113
+ lastPing = Date.now()
114
+ }
99
115
  }
100
116
  }
101
117
  } catch (err) {