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
+ }
0 commit comments