0

Execute GraphQL Query

by
Published 4 days ago

Run any Wiz GraphQL query or mutation with optional variables.

Script wiz Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 days ago
1
//native
2

3
/**
4
 * Execute GraphQL Query
5
 * Run any Wiz GraphQL query or mutation with optional variables. The escape hatch for surfaces not covered by a dedicated action.
6
 */
7
export async function main(
8
  auth: RT.Wiz,
9
  query: string,
10
  variables: { [key: string]: any } | undefined,
11
  operation_name: string | undefined
12
) {
13
  const tokenResponse = await fetch(
14
    auth.auth_url || "https://auth.app.wiz.io/oauth/token",
15
    {
16
      method: "POST",
17
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
18
      body: new URLSearchParams({
19
        grant_type: "client_credentials",
20
        audience: auth.audience || "wiz-api",
21
        client_id: auth.client_id,
22
        client_secret: auth.client_secret,
23
      }),
24
    }
25
  )
26
  if (!tokenResponse.ok) {
27
    throw new Error(`${tokenResponse.status} ${await tokenResponse.text()}`)
28
  }
29
  const { access_token } = (await tokenResponse.json()) as {
30
    access_token: string
31
  }
32

33
  const response = await fetch(auth.api_endpoint, {
34
    method: "POST",
35
    headers: {
36
      Authorization: `Bearer ${access_token}`,
37
      "Content-Type": "application/json",
38
      Accept: "application/json",
39
    },
40
    body: JSON.stringify({
41
      query,
42
      variables: variables || {},
43
      operationName: operation_name || null,
44
    }),
45
  })
46

47
  if (!response.ok) {
48
    throw new Error(`${response.status} ${await response.text()}`)
49
  }
50

51
  const result = (await response.json()) as { data?: any; errors?: any }
52
  if (result.errors) {
53
    throw new Error(JSON.stringify(result.errors))
54
  }
55
  return result.data
56
}
57