/
appsyncAuthUtil.ts
71 lines (61 loc) · 1.67 KB
/
appsyncAuthUtil.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
60
61
62
63
64
65
66
67
68
69
70
71
import { SignatureV4 } from '@aws-sdk/signature-v4'
import { Sha256 } from '@aws-crypto/sha256-js'
import { defaultProvider } from '@aws-sdk/credential-provider-node'
import { HttpRequest } from '@aws-sdk/protocol-http'
import { default as fetch, Request } from 'node-fetch'
export type Operation = {
query: string
operationName: string
variables: object
}
export type Config = {
url: string
region: string
}
export type RequestParams = {
config: Config
operation: Operation
}
export type GraphQLResult<T = object> = {
data?: T
errors?: any[]
extensions?: { [key: string]: any }
}
export const AppSyncRequestIAM = async (params: RequestParams) => {
// deconstruct the url and create a URL object
const endpoint = new URL(params.config.url)
// create something that knows how to let Lambda sign AppSync requests
const signer = new SignatureV4({
credentials: defaultProvider(),
region: params.config.region,
service: 'appsync',
sha256: Sha256,
})
// Setup the request that we are wanting to sign with our URL and signer
const requestToBeSigned = new HttpRequest({
hostname: endpoint.host,
port: 443,
path: endpoint.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/json',
host: endpoint.host,
},
body: JSON.stringify(params.operation),
})
// Actually sign the request
const signedRequest = await signer.sign(requestToBeSigned)
// Create an authenticated request for fetch
const request = new Request(endpoint, signedRequest)
let body
try {
// Make the fetch request
const response = await fetch(request)
body = await response.json()
} catch (e) {
console.log('error', e)
}
return {
body: JSON.stringify(body),
}
}