feat(api): add AppSync GraphQL APIs to the cloud explorer
CI / checks (pull_request) Successful in 28m38s

Create GraphQL APIs with API-key (the first key is made for you), IAM or
Cognito user pool authorization, then edit the schema (a starter schema is
offered, and a rejected one is explained), create and delete API keys, create
data sources for a DynamoDB table, a Lambda function or none, and attach
JavaScript resolvers to fields of the schema from a template for the data
source.

TheCloud's endpoint checks queries against the schema and the API key but does
not run resolvers yet, so the page says so and offers no query runner.
This commit is contained in:
Zakaria
2026-10-25 18:21:46 -04:00
parent 5eee0b7e9b
commit ca3e67a803
23 changed files with 1509 additions and 1 deletions
+58
View File
@@ -155,6 +155,15 @@ export const apiEndpointKeys = {
export: "clouds.services.certificates.export",
revoke: "clouds.services.certificates.revoke",
},
graphql: {
schema: "clouds.services.graphql.schema",
apiKeys: "clouds.services.graphql.apiKeys",
apiKey: "clouds.services.graphql.apiKey",
dataSources: "clouds.services.graphql.dataSources",
dataSource: "clouds.services.graphql.dataSource",
resolvers: "clouds.services.graphql.resolvers",
resolver: "clouds.services.graphql.resolver",
},
query: {
catalog: "clouds.services.query.catalog",
queries: "clouds.services.query.queries",
@@ -975,6 +984,55 @@ export const endpointRegistry: EndpointRegistry = new Map([
method: "POST",
},
],
[
apiEndpointKeys.clouds.graphql.schema,
{
path: "/clouds/:cloud/services/graphql/resources/:id/schema",
method: "PUT",
},
],
[
apiEndpointKeys.clouds.graphql.apiKeys,
{
path: "/clouds/:cloud/services/graphql/resources/:id/api-keys",
method: "POST",
},
],
[
apiEndpointKeys.clouds.graphql.apiKey,
{
path: "/clouds/:cloud/services/graphql/resources/:id/api-keys/:keyId",
method: "DELETE",
},
],
[
apiEndpointKeys.clouds.graphql.dataSources,
{
path: "/clouds/:cloud/services/graphql/resources/:id/data-sources",
method: "POST",
},
],
[
apiEndpointKeys.clouds.graphql.dataSource,
{
path: "/clouds/:cloud/services/graphql/resources/:id/data-sources/:name",
method: "DELETE",
},
],
[
apiEndpointKeys.clouds.graphql.resolvers,
{
path: "/clouds/:cloud/services/graphql/resources/:id/resolvers",
method: "POST",
},
],
[
apiEndpointKeys.clouds.graphql.resolver,
{
path: "/clouds/:cloud/services/graphql/resources/:id/resolvers/:typeName/:fieldName",
method: "DELETE",
},
],
[
apiEndpointKeys.clouds.query.catalog,
{
@@ -37,6 +37,9 @@ import type {
AccessPointInput,
CatalogTableInput,
QueryCatalog,
GraphqlApiKeyInput,
GraphqlDataSourceInput,
GraphqlResolverInput,
QueryExecutionSummary,
QueryInput,
QueryResult,
@@ -1728,6 +1731,98 @@ export async function revokeCertificate(
return res.data;
}
export async function updateGraphqlSchema(
cloud: CloudProvider,
apiId: string,
definition: string,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource, { definition: string }>(
apiEndpointKeys.clouds.graphql.schema,
requestOptions(cloud, "graphql", { body: { definition } }),
{ cloud, id: apiId },
);
return res.data;
}
export async function createGraphqlApiKey(
cloud: CloudProvider,
apiId: string,
input: GraphqlApiKeyInput,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource, GraphqlApiKeyInput>(
apiEndpointKeys.clouds.graphql.apiKeys,
requestOptions(cloud, "graphql", { body: input }),
{ cloud, id: apiId },
);
return res.data;
}
export async function deleteGraphqlApiKey(
cloud: CloudProvider,
apiId: string,
keyId: string,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource>(
apiEndpointKeys.clouds.graphql.apiKey,
requestOptions(cloud, "graphql"),
{ cloud, id: apiId, keyId },
);
return res.data;
}
export async function createGraphqlDataSource(
cloud: CloudProvider,
apiId: string,
input: GraphqlDataSourceInput,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource, GraphqlDataSourceInput>(
apiEndpointKeys.clouds.graphql.dataSources,
requestOptions(cloud, "graphql", { body: input }),
{ cloud, id: apiId },
);
return res.data;
}
export async function deleteGraphqlDataSource(
cloud: CloudProvider,
apiId: string,
name: string,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource>(
apiEndpointKeys.clouds.graphql.dataSource,
requestOptions(cloud, "graphql"),
{ cloud, id: apiId, name },
);
return res.data;
}
export async function createGraphqlResolver(
cloud: CloudProvider,
apiId: string,
input: GraphqlResolverInput,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource, GraphqlResolverInput>(
apiEndpointKeys.clouds.graphql.resolvers,
requestOptions(cloud, "graphql", { body: input }),
{ cloud, id: apiId },
);
return res.data;
}
export async function deleteGraphqlResolver(
cloud: CloudProvider,
apiId: string,
typeName: string,
fieldName: string,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource>(
apiEndpointKeys.clouds.graphql.resolver,
requestOptions(cloud, "graphql"),
{ cloud, id: apiId, typeName, fieldName },
);
return res.data;
}
export async function describeQueryCatalog(
cloud: CloudProvider,
database?: string,
@@ -72,6 +72,7 @@ import { AutoScalingPanel } from "@/components/AutoScalingPanel";
import { FileSystemPanel } from "@/components/FileSystemPanel";
import { DataCatalogPanel } from "@/components/DataCatalogPanel";
import { QueryPanel } from "@/components/QueryPanel";
import { GraphqlPanel } from "@/components/GraphqlPanel";
import { CertificatePanel } from "@/components/CertificatePanel";
import { PipePanel } from "@/components/PipePanel";
import { CloudWatchAlarmPanel } from "@/components/CloudWatchAlarmPanel";
@@ -1011,6 +1012,9 @@ export function DynamicResourceView({
{service === "query" && cloud === "aws" && (
<QueryPanel resource={activeSelected} runtimeReachable={canUseRuntime} />
)}
{service === "graphql" && cloud === "aws" && (
<GraphqlPanel resource={activeSelected} runtimeReachable={canUseRuntime} />
)}
{service === "cdn" && cloud === "aws" && (
<CloudFrontPanel resource={activeSelected} runtimeReachable={canUseRuntime} />
)}
@@ -0,0 +1,142 @@
import {QueryClient, QueryClientProvider} from '@tanstack/react-query'
import {render, screen, within} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {beforeEach, expect, test, vi} from 'vitest'
import {GraphqlPanel} from './GraphqlPanel'
import type {CloudResource} from '@/types/resource'
const api = vi.hoisted(() => ({
getCloudResource: vi.fn(),
listCloudResources: vi.fn(),
updateGraphqlSchema: vi.fn(),
createGraphqlApiKey: vi.fn(),
deleteGraphqlApiKey: vi.fn(),
createGraphqlDataSource: vi.fn(),
deleteGraphqlDataSource: vi.fn(),
createGraphqlResolver: vi.fn(),
deleteGraphqlResolver: vi.fn(),
}))
vi.mock('@/api/cloudProxyClient', () => api)
vi.mock('@/lib/accountStore', () => ({useAccountId: () => '000000000000'}))
const sdl = 'type Note { id: ID! text: String }\ntype Query { note(id: ID!): Note notes: [Note] }'
function graphqlApi(metadata: Record<string, unknown> = {}): CloudResource {
return {
id: 'a1', name: 'notes-api', cloud: 'aws', service: 'graphql', type: 'graphqlApi', region: 'us-east-1', createdAt: null,
metadata: {
apiId: 'a1', authenticationType: 'API_KEY', authenticationLabel: 'API key',
graphqlUrl: 'http://localhost:4566/v1/apis/a1/graphql', realtimeUrl: 'ws://localhost:4566/v1/apis/a1/graphql/realtime',
definition: sdl, schemaStatus: {status: 'SUCCESS', details: null},
types: [{name: 'Query', fields: ['note', 'notes']}, {name: 'Note', fields: ['id', 'text']}],
apiKeys: [{id: 'da2-key', description: 'web', expiresAt: '2026-11-01T22:00:00.000Z'}],
dataSources: [{name: 'notesTable', type: 'AMAZON_DYNAMODB', description: null, tableName: 'notes', functionArn: null, serviceRoleArn: 'arn:aws:iam::000000000000:role/appsync'}],
resolvers: [{typeName: 'Query', fieldName: 'note', dataSourceName: 'notesTable', kind: 'UNIT', runtime: 'APPSYNC_JS', code: ''}],
...metadata,
},
}
}
function renderPanel(resource: CloudResource) {
api.getCloudResource.mockResolvedValue(resource)
const client = new QueryClient({defaultOptions: {queries: {retry: false}}})
return render(<QueryClientProvider client={client}><GraphqlPanel resource={resource} runtimeReachable/></QueryClientProvider>)
}
beforeEach(() => {
vi.clearAllMocks()
api.listCloudResources.mockResolvedValue([{id: 'notes', name: 'notes', metadata: {}}])
for (const fn of [api.updateGraphqlSchema, api.createGraphqlApiKey, api.deleteGraphqlApiKey, api.createGraphqlDataSource, api.deleteGraphqlDataSource, api.createGraphqlResolver, api.deleteGraphqlResolver]) {
fn.mockResolvedValue(graphqlApi())
}
})
test('shows the endpoint, saved schema, keys, data sources and resolvers, and says resolvers do not run', async () => {
renderPanel(graphqlApi())
expect(await screen.findByText('http://localhost:4566/v1/apis/a1/graphql')).toBeInTheDocument()
expect(screen.getByLabelText('Schema definition')).toHaveValue(sdl)
expect(screen.getByText('da2-key')).toBeInTheDocument()
expect(screen.getByText('Query.note')).toBeInTheDocument()
expect(screen.getByText(/does not run resolvers yet/)).toBeInTheDocument()
})
test('offers a starter schema for a new API and saves an edited one', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi({definition: null, types: [], resolvers: [], schemaStatus: null}))
const schema = await screen.findByLabelText('Schema definition')
expect(await screen.findByText(/This starter schema is not saved/)).toBeInTheDocument()
await user.clear(schema)
await user.type(schema, 'type Query {{ hello: String }')
await user.click(screen.getByRole('button', {name: 'Save schema'}))
expect(api.updateGraphqlSchema).toHaveBeenCalledWith('aws', 'a1', 'type Query { hello: String }')
expect(await screen.findByText('Schema saved.')).toBeInTheDocument()
})
test('saves the starter schema as shown when it is not edited', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi({definition: null, types: [], resolvers: [], schemaStatus: null}))
await screen.findByText(/This starter schema is not saved/)
await user.click(screen.getByRole('button', {name: 'Save schema'}))
expect(api.updateGraphqlSchema).toHaveBeenCalledWith('aws', 'a1', expect.stringContaining('type Query {'))
})
test('creates an API key that lasts the chosen days', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi())
const form = await screen.findByRole('form', {name: 'Create API key'})
await user.type(within(form).getByLabelText('Description'), 'mobile')
const days = within(form).getByLabelText('Expires in (days)')
await user.clear(days)
await user.type(days, '30')
await user.click(within(form).getByRole('button', {name: 'Create API key'}))
expect(api.createGraphqlApiKey).toHaveBeenCalledWith('aws', 'a1', {description: 'mobile', expiresInDays: 30})
})
test('creates a DynamoDB data source from a chosen table and role', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi())
const form = await screen.findByRole('form', {name: 'Create data source'})
await user.type(within(form).getByLabelText('Name'), 'notesStore')
await user.selectOptions(within(form).getByLabelText('Type'), 'AMAZON_DYNAMODB')
await user.selectOptions(within(form).getByLabelText('Table'), await within(form).findByRole('option', {name: 'notes'}))
await user.type(within(form).getByLabelText('Service role ARN'), 'arn:aws:iam::000000000000:role/appsync')
await user.click(within(form).getByRole('button', {name: 'Create data source'}))
expect(api.createGraphqlDataSource).toHaveBeenCalledWith('aws', 'a1', {name: 'notesStore', type: 'AMAZON_DYNAMODB', tableName: 'notes', serviceRoleArn: 'arn:aws:iam::000000000000:role/appsync'})
})
test('attaches a resolver to a field without one, starting from the data source template', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi())
const form = await screen.findByRole('form', {name: 'Attach resolver'})
await user.selectOptions(within(form).getByLabelText('Type'), 'Query')
const field = within(form).getByLabelText('Field')
expect(within(field).queryByRole('option', {name: 'note'})).not.toBeInTheDocument()
await user.selectOptions(field, 'notes')
await user.selectOptions(within(form).getByLabelText('Data source'), 'notesTable')
expect((within(form).getByLabelText('Resolver code') as HTMLTextAreaElement).value).toContain("@aws-appsync/utils/dynamodb")
await user.click(within(form).getByRole('button', {name: 'Attach resolver'}))
expect(api.createGraphqlResolver).toHaveBeenCalledWith('aws', 'a1', expect.objectContaining({typeName: 'Query', fieldName: 'notes', dataSourceName: 'notesTable'}))
expect(await screen.findByText('Attached a resolver to Query.notes.')).toBeInTheDocument()
})
test('deletes a key and detaches a resolver after confirming', async () => {
const user = userEvent.setup()
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderPanel(graphqlApi())
await user.click(await screen.findByRole('button', {name: 'Delete da2-key'}))
expect(api.deleteGraphqlApiKey).toHaveBeenCalledWith('aws', 'a1', 'da2-key')
await user.click(screen.getByRole('button', {name: 'Detach Query.note'}))
expect(api.deleteGraphqlResolver).toHaveBeenCalledWith('aws', 'a1', 'Query', 'note')
})
@@ -0,0 +1,295 @@
import {Copy, RefreshCw} from 'lucide-react'
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
import {useEffect, useState} from 'react'
import {
createGraphqlApiKey,
createGraphqlDataSource,
createGraphqlResolver,
deleteGraphqlApiKey,
deleteGraphqlDataSource,
deleteGraphqlResolver,
getCloudResource,
listCloudResources,
updateGraphqlSchema,
} from '@/api/cloudProxyClient'
import {cloudQueryKeys} from '@/api/queries/cloudQueries'
import {useAccountId} from '@/lib/accountStore'
import {formatDateTime} from '@/lib/format'
import type {CloudResource, GraphqlDataSourceInput} from '@/types/resource'
type Props = {
resource?: CloudResource
runtimeReachable: boolean
}
type ApiKey = {id: string; description: string | null; expiresAt: string | null}
type DataSource = {name: string; type: string | null; description: string | null; tableName: string | null; functionArn: string | null; serviceRoleArn: string | null}
type Resolver = {typeName: string; fieldName: string; dataSourceName: string | null; kind: string | null; runtime: string | null; code: string | null}
type GraphqlType = {name: string; fields: string[]}
type SourceForm = {name: string; type: GraphqlDataSourceInput['type']; tableName: string; functionArn: string; serviceRoleArn: string}
const STARTER_SCHEMA = `type Note {
id: ID!
text: String
}
type Query {
note(id: ID!): Note
}
type Mutation {
addNote(id: ID!, text: String!): Note
}
schema {
query: Query
mutation: Mutation
}
`
const SOURCE_LABELS: Record<string, string> = {NONE: 'None (local resolver)', AMAZON_DYNAMODB: 'DynamoDB table', AWS_LAMBDA: 'Lambda function'}
const EMPTY_SOURCE: SourceForm = {name: '', type: 'NONE', tableName: '', functionArn: '', serviceRoleArn: ''}
/** The resolver AppSync's console starts from for each kind of data source. */
function starterCode(sourceType: string | null | undefined): string {
if (sourceType === 'AMAZON_DYNAMODB') {
return `import * as ddb from '@aws-appsync/utils/dynamodb'
export function request(ctx) {
return ddb.get({ key: { id: ctx.args.id } })
}
export function response(ctx) {
return ctx.result
}
`
}
if (sourceType === 'AWS_LAMBDA') {
return `export function request(ctx) {
return { operation: 'Invoke', payload: { field: ctx.info.fieldName, arguments: ctx.args } }
}
export function response(ctx) {
return ctx.result
}
`
}
return `export function request(ctx) {
return { payload: ctx.args }
}
export function response(ctx) {
return ctx.result
}
`
}
export function GraphqlPanel({resource, runtimeReachable}: Props) {
const accountId = useAccountId()
const queryClient = useQueryClient()
const [definition, setDefinition] = useState<string | null>(null)
const [keyForm, setKeyForm] = useState({description: '', days: '7'})
const [sourceForm, setSourceForm] = useState<SourceForm>(EMPTY_SOURCE)
const [resolverForm, setResolverForm] = useState({typeName: '', fieldName: '', dataSourceName: '', code: ''})
const [notice, setNotice] = useState('')
const detailKey = ['appsync-api', accountId, resource?.id]
const detailQuery = useQuery({
queryKey: detailKey,
queryFn: ({signal}) => getCloudResource('aws', 'graphql', resource?.id ?? '', signal),
enabled: Boolean(resource) && runtimeReachable,
})
const tablesQuery = useQuery({
queryKey: cloudQueryKeys.resources('aws', 'nosql'),
queryFn: ({signal}) => listCloudResources('aws', 'nosql', undefined, signal),
enabled: Boolean(resource) && runtimeReachable && sourceForm.type === 'AMAZON_DYNAMODB',
})
const functionsQuery = useQuery({
queryKey: cloudQueryKeys.resources('aws', 'serverless'),
queryFn: ({signal}) => listCloudResources('aws', 'serverless', undefined, signal),
enabled: Boolean(resource) && runtimeReachable && sourceForm.type === 'AWS_LAMBDA',
})
useEffect(() => {
setNotice('')
setDefinition(null)
setKeyForm({description: '', days: '7'})
setSourceForm(EMPTY_SOURCE)
setResolverForm({typeName: '', fieldName: '', dataSourceName: '', code: ''})
}, [resource?.id])
const id = resource?.id ?? ''
const settle = (updated: CloudResource, message: string) => {
queryClient.setQueryData(detailKey, updated)
setNotice(message)
}
const saveSchema = useMutation({
mutationFn: (text: string) => updateGraphqlSchema('aws', id, text),
onSuccess: (updated) => { setDefinition(null); settle(updated, 'Schema saved.') },
})
const addKey = useMutation({
mutationFn: () => createGraphqlApiKey('aws', id, {...(keyForm.description.trim() ? {description: keyForm.description.trim()} : {}), expiresInDays: Number(keyForm.days)}),
onSuccess: (updated) => { setKeyForm({description: '', days: '7'}); settle(updated, 'Created an API key.') },
})
const removeKey = useMutation({
mutationFn: (keyId: string) => deleteGraphqlApiKey('aws', id, keyId),
onSuccess: (updated, keyId) => settle(updated, `Deleted API key ${keyId}.`),
})
const addSource = useMutation({
mutationFn: () => createGraphqlDataSource('aws', id, {
name: sourceForm.name.trim(),
type: sourceForm.type,
...(sourceForm.type === 'AMAZON_DYNAMODB' ? {tableName: sourceForm.tableName} : {}),
...(sourceForm.type === 'AWS_LAMBDA' ? {functionArn: sourceForm.functionArn} : {}),
...(sourceForm.type !== 'NONE' ? {serviceRoleArn: sourceForm.serviceRoleArn.trim()} : {}),
}),
onSuccess: (updated) => { const name = sourceForm.name.trim(); setSourceForm(EMPTY_SOURCE); settle(updated, `Created data source ${name}.`) },
})
const removeSource = useMutation({
mutationFn: (name: string) => deleteGraphqlDataSource('aws', id, name),
onSuccess: (updated, name) => settle(updated, `Deleted data source ${name}.`),
})
const addResolver = useMutation({
mutationFn: () => createGraphqlResolver('aws', id, resolverForm),
onSuccess: (updated) => {
const field = `${resolverForm.typeName}.${resolverForm.fieldName}`
setResolverForm({typeName: '', fieldName: '', dataSourceName: '', code: ''})
settle(updated, `Attached a resolver to ${field}.`)
},
})
const removeResolver = useMutation({
mutationFn: (resolver: Resolver) => deleteGraphqlResolver('aws', id, resolver.typeName, resolver.fieldName),
onSuccess: (updated, resolver) => settle(updated, `Detached the resolver from ${resolver.typeName}.${resolver.fieldName}.`),
})
if (!resource) {
return <section className="table-panel"><div className="empty compact"><h3>Select a GraphQL API</h3><p>Choose an API to edit its schema, keys, data sources and resolvers.</p></div></section>
}
const api = detailQuery.data ?? resource
const metadata = api.metadata
const savedDefinition = typeof metadata.definition === 'string' ? metadata.definition : ''
const schemaText = definition ?? (savedDefinition || (detailQuery.data ? STARTER_SCHEMA : ''))
const schemaStatus = metadata.schemaStatus as {status: string; details: string | null} | null | undefined
const apiKeys = Array.isArray(metadata.apiKeys) ? metadata.apiKeys as ApiKey[] : []
const dataSources = Array.isArray(metadata.dataSources) ? metadata.dataSources as DataSource[] : []
const resolvers = Array.isArray(metadata.resolvers) ? metadata.resolvers as Resolver[] : []
const types = Array.isArray(metadata.types) ? metadata.types as GraphqlType[] : []
const chosenType = types.find((type) => type.name === resolverForm.typeName)
const openFields = (chosenType?.fields ?? []).filter((field) => !resolvers.some((resolver) => resolver.typeName === chosenType?.name && resolver.fieldName === field))
const mutations = [saveSchema, addKey, removeKey, addSource, removeSource, addResolver, removeResolver]
const disabled = !runtimeReachable || mutations.some((mutation) => mutation.isPending)
const error = detailQuery.error ?? mutations.find((mutation) => mutation.error)?.error
const run = (action: () => void) => { setNotice(''); action() }
const copy = (value: string) => { void navigator.clipboard?.writeText(value) }
const chooseSource = (dataSourceName: string) => {
const source = dataSources.find((candidate) => candidate.name === dataSourceName)
const starterOfCurrent = starterCode(dataSources.find((candidate) => candidate.name === resolverForm.dataSourceName)?.type)
const keepCode = resolverForm.code && resolverForm.code !== starterOfCurrent
setResolverForm({...resolverForm, dataSourceName, code: keepCode ? resolverForm.code : starterCode(source?.type)})
}
return <section className="table-panel" style={{marginTop: 16}} aria-label={`GraphQL API ${api.name}`}>
<div className="input-row resource-table-bar">
<div><p className="eyebrow">AppSync GraphQL API</p><span className="muted">{String(metadata.authenticationLabel ?? '')} authorization</span></div>
<div className="cdn-actions">
<button className="button" type="button" disabled={!runtimeReachable || detailQuery.isFetching} onClick={() => { void detailQuery.refetch() }}><RefreshCw size={14}/>{detailQuery.isFetching ? 'Loading' : 'Refresh'}</button>
</div>
</div>
<dl className="graphql-endpoints">
{typeof metadata.graphqlUrl === 'string' && <><dt>GraphQL endpoint</dt><dd><code>{metadata.graphqlUrl}</code> <button className="button compact" type="button" aria-label="Copy GraphQL endpoint" onClick={() => copy(String(metadata.graphqlUrl))}><Copy size={12}/></button></dd></>}
{typeof metadata.realtimeUrl === 'string' && <><dt>Real-time endpoint</dt><dd><code>{metadata.realtimeUrl}</code></dd></>}
</dl>
<p className="muted compact-text graphql-note">TheCloud keeps the schema, keys, data sources and resolvers, and its endpoint checks each query against the schema and the caller&apos;s key. It does not run resolvers yet, so every field of a query resolves to null.</p>
<form className="graphql-section" aria-label="Schema" onSubmit={(event) => { event.preventDefault(); run(() => saveSchema.mutate(schemaText)) }}>
<div className="graphql-section-head"><p className="eyebrow">Schema</p>{schemaStatus && <code className={`query-state query-state--${schemaStatus.status === 'SUCCESS' ? 'succeeded' : schemaStatus.status === 'FAILED' ? 'failed' : 'running'}`}>{schemaStatus.status}</code>}</div>
<textarea className="textarea mono graphql-schema" aria-label="Schema definition" value={schemaText} spellCheck={false} rows={14} onChange={(event) => setDefinition(event.target.value)} disabled={disabled}/>
{!savedDefinition && detailQuery.data && <small className="muted">No schema yet. This starter schema is not saved until you save it.</small>}
<div><button className="button primary" type="submit" disabled={disabled || !schemaText.trim() || (definition === null && Boolean(savedDefinition))}>{saveSchema.isPending ? 'Saving' : 'Save schema'}</button></div>
</form>
<div className="input-row resource-table-bar"><div><p className="eyebrow">API keys</p><span className="muted">Clients send one in the x-api-key header{metadata.authenticationType === 'API_KEY' ? '.' : ' when API keys are an authorization mode.'}</span></div></div>
{apiKeys.length === 0 ? <p className="muted compact-text graphql-note">No API keys.</p>
: <div className="cognito-table"><table className="table"><thead><tr><th>Key</th><th>Description</th><th>Expires</th><th aria-label="Actions"/></tr></thead><tbody>{apiKeys.map((key) => (
<tr key={key.id}>
<td className="mono">{key.id} <button className="button compact" type="button" aria-label={`Copy ${key.id}`} onClick={() => copy(key.id)}><Copy size={12}/></button></td>
<td>{key.description ?? '—'}</td>
<td>{formatDateTime(key.expiresAt) ?? '—'}</td>
<td className="efs-row-actions"><button className="button compact danger" type="button" disabled={disabled} aria-label={`Delete ${key.id}`} onClick={() => run(() => {
if (window.confirm(`Delete API key ${key.id}? Clients using it are refused.`)) removeKey.mutate(key.id)
})}>Delete</button></td>
</tr>
))}</tbody></table></div>}
<form className="dynamic-form graphql-inline-form" aria-label="Create API key" onSubmit={(event) => { event.preventDefault(); run(() => addKey.mutate()) }}>
<label className="dynamic-field"><span>Description</span><input className="input" value={keyForm.description} onChange={(event) => setKeyForm({...keyForm, description: event.target.value})} disabled={disabled}/></label>
<label className="dynamic-field"><span>Expires in (days)</span><input className="input" type="number" min={1} max={365} value={keyForm.days} onChange={(event) => setKeyForm({...keyForm, days: event.target.value})} disabled={disabled} required/></label>
<div><button className="button" type="submit" disabled={disabled}>{addKey.isPending ? 'Creating' : 'Create API key'}</button></div>
</form>
<div className="input-row resource-table-bar"><div><p className="eyebrow">Data sources</p><span className="muted">What resolvers read from and write to.</span></div></div>
{dataSources.length === 0 ? <p className="muted compact-text graphql-note">No data sources yet.</p>
: <div className="cognito-table"><table className="table"><thead><tr><th>Name</th><th>Type</th><th>Target</th><th aria-label="Actions"/></tr></thead><tbody>{dataSources.map((source) => (
<tr key={source.name}>
<td className="mono">{source.name}</td>
<td>{SOURCE_LABELS[source.type ?? ''] ?? source.type ?? '—'}</td>
<td className="mono graphql-target">{source.tableName ?? source.functionArn ?? '—'}</td>
<td className="efs-row-actions"><button className="button compact danger" type="button" disabled={disabled} aria-label={`Delete data source ${source.name}`} onClick={() => run(() => {
if (window.confirm(`Delete data source ${source.name}?`)) removeSource.mutate(source.name)
})}>Delete</button></td>
</tr>
))}</tbody></table></div>}
<form className="dynamic-form graphql-source-form" aria-label="Create data source" onSubmit={(event) => { event.preventDefault(); run(() => addSource.mutate()) }}>
<label className="dynamic-field"><span>Name</span><input className="input mono" value={sourceForm.name} onChange={(event) => setSourceForm({...sourceForm, name: event.target.value})} disabled={disabled} required pattern="[_A-Za-z][_0-9A-Za-z]*" title="Letters, numbers and underscores, starting with a letter or underscore"/></label>
<label className="dynamic-field"><span>Type</span><select className="input" value={sourceForm.type} onChange={(event) => setSourceForm({...sourceForm, type: event.target.value as SourceForm['type']})} disabled={disabled}>
{Object.entries(SOURCE_LABELS).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
</select></label>
{sourceForm.type === 'AMAZON_DYNAMODB' && <label className="dynamic-field"><span>Table</span><select className="input" value={sourceForm.tableName} onChange={(event) => setSourceForm({...sourceForm, tableName: event.target.value})} disabled={disabled} required>
<option value="">{tablesQuery.data?.length ? 'Choose a table' : 'No tables yet'}</option>
{(tablesQuery.data ?? []).map((table) => <option key={table.id} value={table.name}>{table.name}</option>)}
</select></label>}
{sourceForm.type === 'AWS_LAMBDA' && <label className="dynamic-field"><span>Function</span><select className="input" value={sourceForm.functionArn} onChange={(event) => setSourceForm({...sourceForm, functionArn: event.target.value})} disabled={disabled} required>
<option value="">{functionsQuery.data?.length ? 'Choose a function' : 'No functions yet'}</option>
{(functionsQuery.data ?? []).filter((fn) => typeof fn.metadata.arn === 'string').map((fn) => <option key={fn.id} value={String(fn.metadata.arn)}>{fn.name}</option>)}
</select></label>}
{sourceForm.type !== 'NONE' && <label className="dynamic-field graphql-span"><span>Service role ARN</span><input className="input mono" value={sourceForm.serviceRoleArn} placeholder="arn:aws:iam::000000000000:role/appsync-access" onChange={(event) => setSourceForm({...sourceForm, serviceRoleArn: event.target.value})} disabled={disabled} required pattern="arn:aws[a-z\-]*:iam::\d{12}:role/.+" title="The IAM role AppSync assumes, as AWS requires"/></label>}
<div><button className="button" type="submit" disabled={disabled}>{addSource.isPending ? 'Creating' : 'Create data source'}</button></div>
</form>
<div className="input-row resource-table-bar"><div><p className="eyebrow">Resolvers</p><span className="muted">JavaScript (APPSYNC_JS) resolvers attached to fields of the schema.</span></div></div>
{resolvers.length === 0 ? <p className="muted compact-text graphql-note">No resolvers yet.</p>
: <div className="cognito-table"><table className="table"><thead><tr><th>Field</th><th>Data source</th><th>Runtime</th><th aria-label="Actions"/></tr></thead><tbody>{resolvers.map((resolver) => (
<tr key={`${resolver.typeName}.${resolver.fieldName}`}>
<td className="mono">{resolver.typeName}.{resolver.fieldName}</td>
<td className="mono">{resolver.dataSourceName ?? '—'}</td>
<td>{resolver.runtime ?? '—'}</td>
<td className="efs-row-actions"><button className="button compact danger" type="button" disabled={disabled} aria-label={`Detach ${resolver.typeName}.${resolver.fieldName}`} onClick={() => run(() => {
if (window.confirm(`Detach the resolver from ${resolver.typeName}.${resolver.fieldName}?`)) removeResolver.mutate(resolver)
})}>Detach</button></td>
</tr>
))}</tbody></table></div>}
{types.length === 0 ? <p className="muted compact-text graphql-note">Save a schema to attach resolvers to its fields.</p>
: dataSources.length === 0 ? <p className="muted compact-text graphql-note">Create a data source to attach resolvers.</p>
: <form className="graphql-section" aria-label="Attach resolver" onSubmit={(event) => { event.preventDefault(); run(() => addResolver.mutate()) }}>
<div className="dynamic-form graphql-source-form">
<label className="dynamic-field"><span>Type</span><select className="input" value={resolverForm.typeName} onChange={(event) => setResolverForm({...resolverForm, typeName: event.target.value, fieldName: ''})} disabled={disabled} required>
<option value="">Choose a type</option>
{types.map((type) => <option key={type.name} value={type.name}>{type.name}</option>)}
</select></label>
<label className="dynamic-field"><span>Field</span><select className="input" value={resolverForm.fieldName} onChange={(event) => setResolverForm({...resolverForm, fieldName: event.target.value})} disabled={disabled || !chosenType} required>
<option value="">{chosenType && openFields.length === 0 ? 'Every field has a resolver' : 'Choose a field'}</option>
{openFields.map((field) => <option key={field} value={field}>{field}</option>)}
</select></label>
<label className="dynamic-field"><span>Data source</span><select className="input" value={resolverForm.dataSourceName} onChange={(event) => chooseSource(event.target.value)} disabled={disabled} required>
<option value="">Choose a data source</option>
{dataSources.map((source) => <option key={source.name} value={source.name}>{source.name}</option>)}
</select></label>
</div>
<textarea className="textarea mono graphql-code" aria-label="Resolver code" value={resolverForm.code} spellCheck={false} rows={10} placeholder="Choose a data source to start from its template." onChange={(event) => setResolverForm({...resolverForm, code: event.target.value})} disabled={disabled} required/>
<div><button className="button" type="submit" disabled={disabled}>{addResolver.isPending ? 'Attaching' : 'Attach resolver'}</button></div>
</form>}
{notice && <p className="cognito-outcome cognito-outcome--ok" role="status">{notice}</p>}
{error instanceof Error && <p className="error-text compact-text" role="alert">{error.message}</p>}
</section>
}
@@ -1,6 +1,7 @@
import {
Activity,
Boxes,
Braces,
Circle,
Clock,
Container,
@@ -44,6 +45,7 @@ import autoScalingIcon from '../../../../aws-icons-svg/Compute/EC2-Auto-Scaling.
import efsIcon from '../../../../aws-icons-svg/Storage/EFS.svg'
import glueIcon from '../../../../aws-icons-svg/Analytics/Glue.svg'
import athenaIcon from '../../../../aws-icons-svg/Analytics/Athena.svg'
import appSyncIcon from '../../../../aws-icons-svg/App-Integration/AppSync.svg'
import certificateManagerIcon from '../../../../aws-icons-svg/Security-Identity-Compliance/Certificate-Manager.svg'
import cloudWatchIcon from '../../../../aws-icons-svg/Management-Governance/CloudWatch.svg'
import cloudFormationIcon from '@/assets/aws-services/cloudformation.svg'
@@ -109,6 +111,7 @@ const SERVICE_ICONS: Record<string, LucideIcon> = {
filesystems: FolderTree,
datacatalog: Table2,
query: SearchCode,
graphql: Braces,
certificates: FileBadge,
monitoring: Activity,
loadbalancing: Scale,
@@ -162,6 +165,7 @@ const AWS_SERVICE_ICON_ASSETS: Record<string, string> = {
filesystems: efsIcon,
datacatalog: glueIcon,
query: athenaIcon,
graphql: appSyncIcon,
certificates: certificateManagerIcon,
monitoring: cloudWatchIcon,
workflows: stepFunctionsIcon,
+16
View File
@@ -6675,3 +6675,19 @@ tr[aria-current="true"] td { background: var(--hover-md); }
.query-note { padding: 0 16px 12px; margin: 0; }
.query-history-sql { text-align: left; max-width: 640px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; }
@media (max-width: 760px) { .query-layout { grid-template-columns: minmax(0, 1fr); } }
/* AppSync: endpoints as a definition list, schema and resolver code as tall editors. */
.graphql-endpoints { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 12px; margin: 0; padding: 12px 16px 4px; }
.graphql-endpoints dt { color: var(--text-2); font-size: 11px; font-weight: 600; text-transform: uppercase; align-self: center; }
.graphql-endpoints dd { margin: 0; overflow-wrap: anywhere; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.graphql-note { padding: 0 16px 12px; margin: 0; }
.graphql-section { display: grid; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--border); }
.graphql-section-head { display: flex; align-items: center; gap: 10px; }
.graphql-section-head p { margin: 0; }
.graphql-schema, .graphql-code { min-height: 180px; resize: vertical; }
.graphql-inline-form { grid-template-columns: repeat(auto-fit, minmax(160px, 260px)); align-items: end; padding: 4px 16px 12px; }
.graphql-source-form { grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); align-items: end; padding: 4px 16px 12px; }
.graphql-section .graphql-source-form { padding: 0; }
.graphql-span { grid-column: span 2; }
.graphql-target { overflow-wrap: anywhere; }
@media (max-width: 640px) { .graphql-span { grid-column: auto; } .graphql-endpoints { grid-template-columns: minmax(0, 1fr); } }
+21
View File
@@ -362,6 +362,27 @@ export interface AutoScalingCapacityInput {
maxSize?: number
}
export interface GraphqlApiKeyInput {
description?: string
expiresInDays?: number
}
export interface GraphqlDataSourceInput {
name: string
description?: string
type: 'NONE' | 'AMAZON_DYNAMODB' | 'AWS_LAMBDA'
tableName?: string
functionArn?: string
serviceRoleArn?: string
}
export interface GraphqlResolverInput {
typeName: string
fieldName: string
dataSourceName: string
code: string
}
export interface QueryInput {
sql: string
database?: string
+2
View File
@@ -30,6 +30,7 @@ export type ItemActionName = 'list' | 'get' | 'put' | 'delete' | 'query'
export type DistributionActionName = 'setEnabled' | 'createInvalidation'
export type AutoScalingActionName = 'setCapacity' | 'terminateInstance'
export type CertificateActionName = 'download' | 'export' | 'revoke'
export type GraphqlActionName = 'updateSchema' | 'createApiKey' | 'deleteApiKey' | 'createDataSource' | 'deleteDataSource' | 'createResolver' | 'deleteResolver'
export type QueryActionName = 'run' | 'results' | 'stop' | 'history' | 'catalog'
export type DataCatalogActionName = 'createTable' | 'deleteTable'
export type FileSystemActionName = 'createMountTarget' | 'deleteMountTarget' | 'createAccessPoint' | 'deleteAccessPoint' | 'attachFunction' | 'detachFunction'
@@ -101,6 +102,7 @@ export interface ServiceSchema {
fileSystemActions?: Array<CapabilitySchema<FileSystemActionName>>
dataCatalogActions?: Array<CapabilitySchema<DataCatalogActionName>>
queryActions?: Array<CapabilitySchema<QueryActionName>>
graphqlActions?: Array<CapabilitySchema<GraphqlActionName>>
monitoringActions?: Array<CapabilitySchema<MonitoringActionName>>
}
filters: FieldSchema[]