Skip to content

Commit f4ea104

Browse files
committed
feat: support calling AppSync from Lambda
1 parent 9ad0293 commit f4ea104

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

src/client/appsync.ts

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { parse, UrlWithStringQuery } from 'url';
2+
import * as AWS from 'aws-sdk';
3+
import * as axios from 'axios';
4+
5+
export class AppSyncClient {
6+
7+
protected readonly graphQlServerUri: UrlWithStringQuery;
8+
9+
constructor(protected readonly graphQlServerUrl: string, protected readonly awsRegion: string) {
10+
this.graphQlServerUri = parse(this.graphQlServerUrl);
11+
if (!this.graphQlServerUri.href) {
12+
throw new Error('Invalid GraphQL server URL');
13+
}
14+
}
15+
16+
public async call(operationName: string, query: string, variables: any = {}): Promise<axios.AxiosResponse<any>> {
17+
const post_body = {
18+
operationName,
19+
query,
20+
variables,
21+
};
22+
23+
const httpRequest = new AWS.HttpRequest(new AWS.Endpoint(this.graphQlServerUri.href!), this.awsRegion);
24+
httpRequest.headers.host = this.graphQlServerUri.host!;
25+
httpRequest.headers['Content-Type'] = 'application/json';
26+
httpRequest.method = 'POST';
27+
httpRequest.body = JSON.stringify(post_body);
28+
29+
await ((AWS.config.credentials as AWS.Credentials)?.getPromise());
30+
31+
// Signers is an internal API
32+
const signer = new (AWS as any).Signers.V4(httpRequest, 'appsync', true);
33+
signer.addAuthorization(AWS.config.credentials, (AWS as any).util.date.getDate());
34+
35+
const res = await axios.default.post(this.graphQlServerUri.href!, httpRequest.body, {
36+
headers: httpRequest.headers,
37+
});
38+
return res;
39+
}
40+
41+
}

src/client/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './appsync';

src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * as errors from './types/errors';
22
export * as dynamodb from './dynamodb';
33
export * as http from './http';
4+
export * as client from './client';

0 commit comments

Comments
 (0)