Skip to content

Instantly share code, notes, and snippets.

if (eventType === 'MESSAGE') {
const message = JSON.parse(event.body);
// Handshake with Apollo
if (message.type === 'connection_init') {
// Write connection to persistence
const connection = Object.assign(new Connection(), {
id: connectionId,
requestContext: event.requestContext,
payload: event.body.payload
import { DataMapper } from '@aws/dynamodb-data-mapper';
import { DynamoDB } from 'aws-sdk';
export const mapper = new DataMapper({
client: new DynamoDB({ region: 'us-east-1' })
});
// GET for connection item
mapper.get(Object.assign(new Connection(), {
id: connectionId
}));
const gateway = createGateway(event.requestContext);
// Server sending message to client acknowledging connection_init
gateway.postToConnection({
ConnectionId: event.requestContext.connectionId,
Data: JSON.stringify({ type: 'connection_ack', payload: {} })
});
import { attribute, hashKey, rangeKey } from '@aws/dynamodb-data-mapper-annotations';
import { APIGatewayEventRequestContext } from 'aws-lambda';
@table('SUBSCRIPTION_TABLE')
export class Subscription {
/*
* Combination of connectionId and subscriptionId
* `${connectionId}|${subscriptionId}`
*/
@hashKey({ type: 'String' })
import { attribute, hashKey, table } from '@aws/dynamodb-data-mapper-annotations';
import { APIGatewayEventRequestContext } from 'aws-lambda';
@table('CONNECTION_TABLE')
export class Connection {
/* ConnectionId */
@hashKey()
id: string;
@attribute({defaultProvider: () => new Date()})
functions:
websocket:
name: example-websocket
handler: ws-handler.handler
events:
- websocket:
route: $connect
- websocket:
route: $disconnect
- websocket:
resources:
Resources:
connectionsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: CONNECTION_TABLE
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
import { ApiGatewayManagementApi } from 'aws-sdk';
export const createGateway = (requestContext: any) =>
new ApiGatewayManagementApi({
apiVersion: 'latest',
endpoint: `https://${requestContext.apiId}
.execute-api.us-east-1.amazonaws.com/${requestContext.stage}`
});
import React, { FC } from 'react';
import { ApolloProvider } from '@apollo/react-hooks';
import {
InMemoryCache,
ApolloClient,
HttpLink,
split,
} from 'apollo-boost';
// WS link from example here - https://github.com/enisdenjo/graphql-ws#apollo-client