/
app-sync.ts
59 lines (51 loc) · 2.02 KB
/
app-sync.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { SubscriptionProvider, SubscriptionProviderExecuteOptions } from '../subscription-provider';
import { Observable, of } from 'rxjs';
import { createAuthLink } from 'aws-appsync-auth-link';
import { createSubscriptionHandshakeLink } from 'aws-appsync-subscription-link';
import { ApolloClient, ApolloLink, InMemoryCache, createHttpLink } from '@apollo/client/core';
import { parse } from 'graphql';
export class AppSyncSubscriptionProvider extends SubscriptionProvider {
subscription?: any;
/**
{
"aws_project_region": "us-west-2",
"aws_appsync_graphqlEndpoint": "https://....appsync-api.us-west-2.amazonaws.com/graphql",
"aws_appsync_region": "us-west-2",
"aws_appsync_authenticationType": "API_KEY",
"aws_appsync_apiKey": "..."
"aws_appsync_jwtToken" "..."
}
*/
execute(options: SubscriptionProviderExecuteOptions) {
const url = this.connectionParams.aws_appsync_graphqlEndpoint;
const region = this.connectionParams.aws_appsync_region;
const auth = {
type: this.connectionParams.aws_appsync_authenticationType,
...this.connectionParams.aws_appsync_apiKey ? {apiKey: this.connectionParams.aws_appsync_apiKey} : {},
...this.connectionParams.aws_appsync_jwtToken ? { jwtToken: this.connectionParams.aws_appsync_jwtToken } : {},
};
const httpLink = createHttpLink({ uri: url });
const link = ApolloLink.from([
createAuthLink({ url, region, auth }),
createSubscriptionHandshakeLink(url, httpLink),
]);
const client = new ApolloClient({
link,
cache: new InMemoryCache()
});
const subscription = client.subscribe({
query: parse(options.query),
variables: options.variables
})
return new Observable((subscriber) => {
this.subscription = subscription.subscribe({
next: (...args: any[]) => subscriber.next(...args),
error: (...args: any[]) => subscriber.error(...args),
complete: () => subscriber.complete(),
});
});
}
close() {
this.subscription?.unsubscribe();
}
}