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
+1
View File
@@ -14,6 +14,7 @@
"@aws-sdk/client-api-gateway": "^3.1076.0",
"@aws-sdk/client-apigatewayv2": "^3.1076.0",
"@aws-sdk/client-appconfig": "^3.1076.0",
"@aws-sdk/client-appsync": "^3.1146.0",
"@aws-sdk/client-athena": "^3.1146.0",
"@aws-sdk/client-auto-scaling": "^3.1146.0",
"@aws-sdk/client-cloudformation": "^3.1111.0",
@@ -0,0 +1,165 @@
import {describe, expect, test} from 'bun:test'
import {
type AppSyncClient,
CreateApiKeyCommand,
CreateDataSourceCommand,
CreateGraphqlApiCommand,
CreateResolverCommand,
DeleteResolverCommand,
GetGraphqlApiCommand,
GetIntrospectionSchemaCommand,
GetSchemaCreationStatusCommand,
ListApiKeysCommand,
ListDataSourcesCommand,
ListGraphqlApisCommand,
ListResolversCommand,
StartSchemaCreationCommand,
} from '@aws-sdk/client-appsync'
import {AwsGraphqlAdapter, objectTypes, schemaFailure, sdlFrom} from './AwsGraphqlAdapter'
import {ValidationError} from '../cloud-spi/errors'
type SendResult = Record<string, unknown>
const sdl = `"""A note"""
type Note { id: ID! text: String }
# the entry points
type Query { note(id: ID!): Note notes(filter: NoteFilter, limit: Int = 10): [Note] }
type Mutation {
addNote(text: String!): Note
}
input NoteFilter { text: String }
schema { query: Query mutation: Mutation }`
const api = {
apiId: 'a1', name: 'notes-api', authenticationType: 'API_KEY', arn: 'arn:aws:appsync:eu-west-1:000000000000:apis/a1',
uris: {GRAPHQL: 'http://localhost:4566/v1/apis/a1/graphql', REALTIME: 'ws://localhost:4566/v1/apis/a1/graphql/realtime'},
}
function adapterWith(handler: (command: object) => SendResult | undefined = () => undefined) {
const sent: object[] = []
const client = {
async send(command: object) {
sent.push(command)
const result = handler(command)
if (result) return result
if (command instanceof GetGraphqlApiCommand) return {graphqlApi: api}
if (command instanceof CreateGraphqlApiCommand) return {graphqlApi: api}
if (command instanceof GetIntrospectionSchemaCommand) return {schema: new TextEncoder().encode(sdl)}
if (command instanceof GetSchemaCreationStatusCommand) return {status: 'SUCCESS'}
if (command instanceof ListApiKeysCommand) return {apiKeys: [{id: 'da2-key', description: 'web', expires: 1793570400}]}
if (command instanceof ListDataSourcesCommand) return {dataSources: [{name: 'notesTable', type: 'AMAZON_DYNAMODB', dynamodbConfig: {tableName: 'notes'}, serviceRoleArn: 'arn:aws:iam::000000000000:role/appsync'}]}
if (command instanceof ListResolversCommand) {
return command.input.typeName === 'Query' ? {resolvers: [{typeName: 'Query', fieldName: 'note', dataSourceName: 'notesTable', kind: 'UNIT', runtime: {name: 'APPSYNC_JS'}, code: 'export function request() {}'}]} : {resolvers: []}
}
return {}
},
}
return {sent, adapter: new AwsGraphqlAdapter(client as unknown as AppSyncClient, async () => {})}
}
describe('AwsGraphqlAdapter', () => {
test('reads the object types and fields a resolver can attach to', () => {
expect(objectTypes(sdl)).toEqual([
{name: 'Query', fields: ['note', 'notes']},
{name: 'Mutation', fields: ['addNote']},
{name: 'Note', fields: ['id', 'text']},
])
expect(objectTypes('type Query { a: String }\nextend type Query { b: Int }')).toEqual([{name: 'Query', fields: ['a', 'b']}])
})
test('reads the SDL whether it comes bare, as from AWS, or wrapped, as from the runtime', () => {
expect(sdlFrom('type Query { a: String }')).toBe('type Query { a: String }')
expect(sdlFrom(JSON.stringify({schema: {definition: 'type Query { a: String }'}}))).toBe('type Query { a: String }')
})
test('explains a rejected schema in the parser\'s words', () => {
const runtime = JSON.stringify({reason: 'CODE_ERROR', detail: {codeErrors: [{errorType: 'PARSER_ERROR', value: "Invalid syntax with offending token '<EOF>' at line 1 column 20"}]}})
expect(schemaFailure(runtime)).toBe("Invalid syntax with offending token '<EOF>' at line 1 column 20")
expect(schemaFailure('Failed to parse schema document')).toBe('Failed to parse schema document')
expect(schemaFailure(undefined)).toBe('AppSync rejected it')
})
test('lists APIs with their endpoint and authorization', async () => {
const {adapter} = adapterWith((command) => command instanceof ListGraphqlApisCommand ? {graphqlApis: [api]} : undefined)
const [listed] = await adapter.list()
expect([listed.id, listed.name, listed.metadata.authenticationLabel, listed.metadata.graphqlUrl]).toEqual(['a1', 'notes-api', 'API key', 'http://localhost:4566/v1/apis/a1/graphql'])
expect(await adapter.list({search: 'other'})).toEqual([])
})
test('describes the schema, keys, data sources and resolvers', async () => {
const {adapter, sent} = adapterWith()
const detail = await adapter.get('a1')
expect(detail?.metadata.definition).toBe(sdl)
expect(detail?.metadata.apiKeys).toEqual([{id: 'da2-key', description: 'web', expiresAt: '2026-11-01T22:00:00.000Z'}])
expect(detail?.metadata.dataSources).toEqual([{name: 'notesTable', type: 'AMAZON_DYNAMODB', description: null, tableName: 'notes', functionArn: null, serviceRoleArn: 'arn:aws:iam::000000000000:role/appsync'}])
expect(detail?.metadata.resolvers).toEqual([{typeName: 'Query', fieldName: 'note', dataSourceName: 'notesTable', kind: 'UNIT', runtime: 'APPSYNC_JS', code: 'export function request() {}'}])
expect((sent.filter((command) => command instanceof ListResolversCommand) as ListResolversCommand[]).map((command) => command.input.typeName)).toEqual(['Query', 'Mutation', 'Note'])
})
test('a new API-key API gets its first key, and Cognito needs a user pool', async () => {
const {adapter, sent} = adapterWith()
await adapter.create({values: {name: 'notes-api', authenticationType: 'API_KEY'}})
expect(sent.some((command) => command instanceof CreateApiKeyCommand)).toBe(true)
await adapter.create({values: {name: 'members', authenticationType: 'AMAZON_COGNITO_USER_POOLS', userPoolId: 'us-east-1_AbC123'}})
const cognito = (sent.filter((command) => command instanceof CreateGraphqlApiCommand) as CreateGraphqlApiCommand[])[1]
expect(cognito.input.userPoolConfig).toEqual({userPoolId: 'us-east-1_AbC123', awsRegion: 'us-east-1', defaultAction: 'ALLOW'})
await expect(adapter.create({values: {name: 'members', authenticationType: 'AMAZON_COGNITO_USER_POOLS'}})).rejects.toBeInstanceOf(ValidationError)
})
test('saving a schema waits for AppSync to compile it and reports a rejection', async () => {
let polls = 0
const {adapter, sent} = adapterWith((command) => command instanceof GetSchemaCreationStatusCommand ? {status: ++polls < 3 ? 'PROCESSING' : 'SUCCESS'} : undefined)
await adapter.updateGraphqlSchema('a1', 'type Query { a: String }')
expect(new TextDecoder().decode((sent.find((command) => command instanceof StartSchemaCreationCommand) as StartSchemaCreationCommand).input.definition)).toBe('type Query { a: String }')
expect(polls).toBeGreaterThanOrEqual(3)
const failing = adapterWith((command) => command instanceof GetSchemaCreationStatusCommand ? {status: 'FAILED', details: 'Syntax Error: Unexpected Name "typo"'} : undefined)
await expect(failing.adapter.updateGraphqlSchema('a1', 'typo Query')).rejects.toThrow('The schema was not saved: Syntax Error: Unexpected Name "typo"')
})
test('creates an API key that expires after the given days', async () => {
const {adapter, sent} = adapterWith()
const before = Math.floor(Date.now() / 1000)
await adapter.createGraphqlApiKey('a1', {description: 'mobile', expiresInDays: 30})
const create = sent.find((command) => command instanceof CreateApiKeyCommand) as CreateApiKeyCommand
expect(create.input.description).toBe('mobile')
expect((create.input.expires ?? 0) - before).toBeGreaterThanOrEqual(30 * 86_400)
await expect(adapter.createGraphqlApiKey('a1', {expiresInDays: 400})).rejects.toBeInstanceOf(ValidationError)
})
test('creates DynamoDB and Lambda data sources with a role, in the API region', async () => {
const {adapter, sent} = adapterWith()
const role = 'arn:aws:iam::000000000000:role/appsync'
await adapter.createGraphqlDataSource('a1', {name: 'notesTable', type: 'AMAZON_DYNAMODB', tableName: 'notes', serviceRoleArn: role})
await adapter.createGraphqlDataSource('a1', {name: 'notesFn', type: 'AWS_LAMBDA', functionArn: 'arn:aws:lambda:eu-west-1:000000000000:function:notes', serviceRoleArn: role})
await adapter.createGraphqlDataSource('a1', {name: 'local', type: 'NONE'})
const [table, fn, none] = (sent.filter((command) => command instanceof CreateDataSourceCommand) as CreateDataSourceCommand[]).map((command) => command.input)
expect(table).toEqual({apiId: 'a1', name: 'notesTable', type: 'AMAZON_DYNAMODB', serviceRoleArn: role, dynamodbConfig: {tableName: 'notes', awsRegion: 'eu-west-1'}})
expect(fn.lambdaConfig).toEqual({lambdaFunctionArn: 'arn:aws:lambda:eu-west-1:000000000000:function:notes'})
expect(none).toEqual({apiId: 'a1', name: 'local', type: 'NONE'})
await expect(adapter.createGraphqlDataSource('a1', {name: 'notesTable', type: 'AMAZON_DYNAMODB', tableName: 'notes'})).rejects.toBeInstanceOf(ValidationError)
await expect(adapter.createGraphqlDataSource('a1', {name: 'bad-name', type: 'NONE'})).rejects.toBeInstanceOf(ValidationError)
})
test('attaches a JavaScript resolver only to a field the schema has', async () => {
const {adapter, sent} = adapterWith()
const code = 'export function request(ctx) { return {} }\nexport function response(ctx) { return ctx.result }'
await adapter.createGraphqlResolver('a1', {typeName: 'Mutation', fieldName: 'addNote', dataSourceName: 'notesTable', code})
expect((sent.find((command) => command instanceof CreateResolverCommand) as CreateResolverCommand).input).toEqual({
apiId: 'a1', typeName: 'Mutation', fieldName: 'addNote', dataSourceName: 'notesTable', kind: 'UNIT', code, runtime: {name: 'APPSYNC_JS', runtimeVersion: '1.0.0'},
})
await expect(adapter.createGraphqlResolver('a1', {typeName: 'Query', fieldName: 'nope', dataSourceName: 'notesTable', code})).rejects.toThrow('Query has no field nope')
await expect(adapter.createGraphqlResolver('a1', {typeName: 'Ghost', fieldName: 'a', dataSourceName: 'notesTable', code})).rejects.toThrow('The schema has no type Ghost')
await expect(adapter.createGraphqlResolver('a1', {typeName: 'Query', fieldName: 'note', dataSourceName: 'notesTable', code: 'return 1'})).rejects.toBeInstanceOf(ValidationError)
})
test('detaches a resolver', async () => {
const {adapter, sent} = adapterWith()
await adapter.deleteGraphqlResolver('a1', 'Query', 'note')
expect((sent.find((command) => command instanceof DeleteResolverCommand) as DeleteResolverCommand).input).toEqual({apiId: 'a1', typeName: 'Query', fieldName: 'note'})
})
})
@@ -0,0 +1,405 @@
import {
type ApiKey,
type AppSyncClient,
CreateApiKeyCommand,
CreateDataSourceCommand,
CreateGraphqlApiCommand,
CreateResolverCommand,
type DataSource,
DeleteApiKeyCommand,
DeleteDataSourceCommand,
DeleteGraphqlApiCommand,
DeleteResolverCommand,
GetGraphqlApiCommand,
GetIntrospectionSchemaCommand,
GetSchemaCreationStatusCommand,
type GetSchemaCreationStatusCommandOutput,
type GraphqlApi,
ListApiKeysCommand,
ListDataSourcesCommand,
ListGraphqlApisCommand,
ListResolversCommand,
type Resolver,
StartSchemaCreationCommand,
} from '@aws-sdk/client-appsync'
import {NotFoundError, RuntimeError, ValidationError} from '../cloud-spi/errors'
import {
awsGraphqlSchema,
GRAPHQL_API_KEY_MAX_DAYS,
GRAPHQL_API_NAME_PATTERN,
GRAPHQL_AUTH_TYPES,
GRAPHQL_DATA_SOURCE_NAME_PATTERN,
GRAPHQL_DATA_SOURCE_TYPES,
} from '../cloud-spi/graphqlSchema'
import type {
CloudResource,
CloudServiceAdapter,
CreateResourceInput,
GraphqlApiKeyInput,
GraphqlDataSourceInput,
GraphqlResolverInput,
ResourceQuery,
ServiceSchema,
} from '../cloud-spi/types'
const AUTH_LABELS: Record<string, string> = {API_KEY: 'API key', AWS_IAM: 'IAM', AMAZON_COGNITO_USER_POOLS: 'Cognito user pool', OPENID_CONNECT: 'OpenID Connect', AWS_LAMBDA: 'Lambda'}
const DAY_SECONDS = 86_400
/** How long a schema save waits for AppSync to finish compiling it before reporting PROCESSING. */
const SCHEMA_WAIT_ATTEMPTS = 20
const SCHEMA_WAIT_MS = 250
const ROLE_ARN = /^arn:aws[a-z-]*:iam::\d{12}:role\/.+$/
const LAMBDA_ARN = /^arn:aws[a-z-]*:lambda:[a-z0-9-]+:\d{12}:function:.+$/
/**
* Talks to AWS AppSync, verified against Floci core (community, `latest`).
*
* Notes from probing the runtime:
* - APIs, schemas, API keys, data sources and resolvers are all stored, and the
* GraphQL endpoint checks queries against the schema and the caller's key.
* - Resolvers are never run, so every field of a query comes back null. The
* console says so instead of offering a query runner that looks broken.
* - GetIntrospectionSchema wraps the SDL in {"schema": {"definition": …}} where
* AWS returns the SDL itself; both are read.
* - ListTypes returns nothing, so the types a resolver can attach to come from
* the schema's own SDL.
*/
export class AwsGraphqlAdapter implements CloudServiceAdapter {
readonly cloud = 'aws' as const
readonly service = 'graphql' as const
constructor(private readonly appsync: AppSyncClient, private readonly sleep: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) {}
schema(): ServiceSchema {
return awsGraphqlSchema()
}
async list(query: ResourceQuery = {}): Promise<CloudResource[]> {
const found: GraphqlApi[] = []
let next: string | undefined
do {
const res = await this.appsync.send(new ListGraphqlApisCommand({maxResults: 25, ...(next ? {nextToken: next} : {})}))
found.push(...(res.graphqlApis ?? []))
next = res.nextToken
} while (next)
const search = query.search?.trim().toLowerCase()
return found.map((api) => toResource(api)).filter((api) => !search
|| api.name.toLowerCase().includes(search)
|| api.id.toLowerCase().includes(search))
}
async get(id: string): Promise<CloudResource | null> {
let api: GraphqlApi | undefined
try {
api = (await this.appsync.send(new GetGraphqlApiCommand({apiId: id}))).graphqlApi
} catch (error) {
if (errorName(error) === 'NotFoundException') return null
throw error
}
if (!api) return null
const [definition, schemaStatus, apiKeys, dataSources] = await Promise.all([this.definition(id), this.schemaStatus(id), this.apiKeys(id), this.dataSources(id)])
const types = definition ? objectTypes(definition) : []
const resolvers = (await Promise.all(types.map((type) => this.resolvers(id, type.name)))).flat()
return toResource(api, {definition, schemaStatus, apiKeys, dataSources, resolvers, types})
}
async create(input: CreateResourceInput): Promise<CloudResource> {
const values = input.values
const name = text(values.name)
if (!new RegExp(GRAPHQL_API_NAME_PATTERN).test(name)) throw new ValidationError('name must be up to 128 letters, numbers, spaces, dashes or underscores')
const authenticationType = text(values.authenticationType) || 'API_KEY'
if (!(GRAPHQL_AUTH_TYPES as readonly string[]).includes(authenticationType)) throw new ValidationError(`authenticationType must be one of ${GRAPHQL_AUTH_TYPES.join(', ')}`)
const userPoolId = text(values.userPoolId)
if (authenticationType === 'AMAZON_COGNITO_USER_POOLS' && !userPoolId) throw new ValidationError('userPoolId is required for Cognito user pool authorization')
const created = await this.appsync.send(new CreateGraphqlApiCommand({
name,
authenticationType: authenticationType as (typeof GRAPHQL_AUTH_TYPES)[number],
...(authenticationType === 'AMAZON_COGNITO_USER_POOLS' ? {userPoolConfig: {userPoolId, awsRegion: userPoolId.split('_')[0], defaultAction: 'ALLOW'}} : {}),
}))
const apiId = created.graphqlApi?.apiId
if (!apiId) throw new RuntimeError('AppSync did not return the new API id')
// The AppSync console gives a new API-key API its first key, valid for seven days.
if (authenticationType === 'API_KEY') await this.appsync.send(new CreateApiKeyCommand({apiId, expires: expiry(7)}))
return this.detail(apiId)
}
async delete(id: string): Promise<void> {
await this.appsync.send(new DeleteGraphqlApiCommand({apiId: id}))
}
async updateGraphqlSchema(apiId: string, definition: string): Promise<CloudResource> {
const sdl = typeof definition === 'string' ? definition.trim() : ''
if (!sdl) throw new ValidationError('Enter a schema to save')
await this.appsync.send(new StartSchemaCreationCommand({apiId, definition: new TextEncoder().encode(sdl)}))
let status: GetSchemaCreationStatusCommandOutput | null = null
for (let attempt = 0; attempt < SCHEMA_WAIT_ATTEMPTS; attempt++) {
status = await this.appsync.send(new GetSchemaCreationStatusCommand({apiId}))
if (status.status !== 'PROCESSING') break
await this.sleep(SCHEMA_WAIT_MS)
}
if (status?.status === 'FAILED') throw new ValidationError(`The schema was not saved: ${schemaFailure(status.details)}`)
return this.detail(apiId)
}
async createGraphqlApiKey(apiId: string, input: GraphqlApiKeyInput): Promise<CloudResource> {
const days = input.expiresInDays ?? 7
if (!Number.isInteger(days) || days < 1 || days > GRAPHQL_API_KEY_MAX_DAYS) throw new ValidationError(`expiresInDays must be a whole number from 1 to ${GRAPHQL_API_KEY_MAX_DAYS}`)
const description = text(input.description)
await this.appsync.send(new CreateApiKeyCommand({apiId, expires: expiry(days), ...(description ? {description} : {})}))
return this.detail(apiId)
}
async deleteGraphqlApiKey(apiId: string, keyId: string): Promise<CloudResource> {
await this.appsync.send(new DeleteApiKeyCommand({apiId, id: keyId}))
return this.detail(apiId)
}
async createGraphqlDataSource(apiId: string, input: GraphqlDataSourceInput): Promise<CloudResource> {
const name = text(input.name)
if (!new RegExp(GRAPHQL_DATA_SOURCE_NAME_PATTERN).test(name)) throw new ValidationError('name must start with a letter or underscore and use only letters, numbers and underscores')
const type = text(input.type)
if (!(GRAPHQL_DATA_SOURCE_TYPES as readonly string[]).includes(type)) throw new ValidationError(`type must be one of ${GRAPHQL_DATA_SOURCE_TYPES.join(', ')}`)
const description = text(input.description)
const serviceRoleArn = text(input.serviceRoleArn)
if (type !== 'NONE' && !ROLE_ARN.test(serviceRoleArn)) throw new ValidationError('serviceRoleArn must be the IAM role AppSync uses to reach the table or function')
const tableName = text(input.tableName)
if (type === 'AMAZON_DYNAMODB' && !tableName) throw new ValidationError('tableName is required for a DynamoDB data source')
const functionArn = text(input.functionArn)
if (type === 'AWS_LAMBDA' && !LAMBDA_ARN.test(functionArn)) throw new ValidationError('functionArn must be a Lambda function ARN')
const region = await this.region(apiId)
await this.appsync.send(new CreateDataSourceCommand({
apiId,
name,
type: type as (typeof GRAPHQL_DATA_SOURCE_TYPES)[number],
...(description ? {description} : {}),
...(type !== 'NONE' ? {serviceRoleArn} : {}),
...(type === 'AMAZON_DYNAMODB' ? {dynamodbConfig: {tableName, awsRegion: region}} : {}),
...(type === 'AWS_LAMBDA' ? {lambdaConfig: {lambdaFunctionArn: functionArn}} : {}),
}))
return this.detail(apiId)
}
async deleteGraphqlDataSource(apiId: string, name: string): Promise<CloudResource> {
await this.appsync.send(new DeleteDataSourceCommand({apiId, name}))
return this.detail(apiId)
}
async createGraphqlResolver(apiId: string, input: GraphqlResolverInput): Promise<CloudResource> {
const typeName = text(input.typeName)
const fieldName = text(input.fieldName)
const dataSourceName = text(input.dataSourceName)
const code = typeof input.code === 'string' ? input.code : ''
if (!dataSourceName) throw new ValidationError('dataSourceName is required')
if (!/export\s+function\s+request\b/.test(code) || !/export\s+function\s+response\b/.test(code)) {
throw new ValidationError('code must export a request(ctx) and a response(ctx) function')
}
// AppSync refuses a resolver for a field the schema does not have; the runtime does not, so check here.
const definition = await this.definition(apiId)
const type = definition ? objectTypes(definition).find((candidate) => candidate.name === typeName) : undefined
if (!type) throw new ValidationError(`The schema has no type ${typeName}`)
if (!type.fields.includes(fieldName)) throw new ValidationError(`${typeName} has no field ${fieldName}`)
await this.appsync.send(new CreateResolverCommand({
apiId, typeName, fieldName, dataSourceName, kind: 'UNIT', code, runtime: {name: 'APPSYNC_JS', runtimeVersion: '1.0.0'},
}))
return this.detail(apiId)
}
async deleteGraphqlResolver(apiId: string, typeName: string, fieldName: string): Promise<CloudResource> {
await this.appsync.send(new DeleteResolverCommand({apiId, typeName, fieldName}))
return this.detail(apiId)
}
private async detail(apiId: string): Promise<CloudResource> {
const detail = await this.get(apiId)
if (!detail) throw new NotFoundError(`GraphQL API ${apiId} not found`)
return detail
}
private async region(apiId: string): Promise<string> {
const api = (await this.appsync.send(new GetGraphqlApiCommand({apiId}))).graphqlApi
return api?.arn?.split(':')[3] || 'us-east-1'
}
private async definition(apiId: string): Promise<string | null> {
try {
const res = await this.appsync.send(new GetIntrospectionSchemaCommand({apiId, format: 'SDL'}))
return res.schema ? sdlFrom(new TextDecoder().decode(res.schema)) : null
} catch (error) {
if (errorName(error) === 'NotFoundException') return null
throw error
}
}
private async schemaStatus(apiId: string): Promise<{status: string; details: string | null} | null> {
try {
const res = await this.appsync.send(new GetSchemaCreationStatusCommand({apiId}))
return res.status ? {status: res.status, details: res.details ?? null} : null
} catch (error) {
if (errorName(error) === 'NotFoundException') return null
throw error
}
}
private async apiKeys(apiId: string): Promise<ApiKey[]> {
const found: ApiKey[] = []
let next: string | undefined
do {
const res = await this.appsync.send(new ListApiKeysCommand({apiId, maxResults: 25, ...(next ? {nextToken: next} : {})}))
found.push(...(res.apiKeys ?? []))
next = res.nextToken
} while (next)
return found
}
private async dataSources(apiId: string): Promise<DataSource[]> {
const found: DataSource[] = []
let next: string | undefined
do {
const res = await this.appsync.send(new ListDataSourcesCommand({apiId, maxResults: 25, ...(next ? {nextToken: next} : {})}))
found.push(...(res.dataSources ?? []))
next = res.nextToken
} while (next)
return found.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''))
}
private async resolvers(apiId: string, typeName: string): Promise<Resolver[]> {
const found: Resolver[] = []
let next: string | undefined
do {
const res = await this.appsync.send(new ListResolversCommand({apiId, typeName, maxResults: 25, ...(next ? {nextToken: next} : {})}))
found.push(...(res.resolvers ?? []))
next = res.nextToken
} while (next)
return found
}
}
type ApiDetail = {
definition: string | null
schemaStatus: {status: string; details: string | null} | null
apiKeys: ApiKey[]
dataSources: DataSource[]
resolvers: Resolver[]
types: Array<{name: string; fields: string[]}>
}
function toResource(api: GraphqlApi, detail?: ApiDetail): CloudResource {
const id = api.apiId ?? ''
const authenticationType = api.authenticationType ?? null
return {
id,
name: api.name ?? id,
cloud: 'aws',
service: 'graphql',
type: 'graphqlApi',
region: api.arn?.split(':')[3] || null,
createdAt: null,
metadata: {
apiId: id,
arn: api.arn ?? null,
authenticationType,
authenticationLabel: authenticationType ? AUTH_LABELS[authenticationType] ?? authenticationType : null,
userPoolId: api.userPoolConfig?.userPoolId ?? null,
graphqlUrl: api.uris?.GRAPHQL ?? null,
realtimeUrl: api.uris?.REALTIME ?? null,
...(detail ? {
definition: detail.definition,
schemaStatus: detail.schemaStatus,
types: detail.types,
apiKeys: detail.apiKeys.map((key) => ({
id: key.id ?? '',
description: key.description || null,
expiresAt: key.expires ? new Date(key.expires * 1000).toISOString() : null,
})),
dataSources: detail.dataSources.map((source) => ({
name: source.name ?? '',
type: source.type ?? null,
description: source.description || null,
tableName: source.dynamodbConfig?.tableName ?? null,
functionArn: source.lambdaConfig?.lambdaFunctionArn ?? null,
serviceRoleArn: source.serviceRoleArn ?? null,
})),
resolvers: detail.resolvers.map((resolver) => ({
typeName: resolver.typeName ?? '',
fieldName: resolver.fieldName ?? '',
dataSourceName: resolver.dataSourceName ?? null,
kind: resolver.kind ?? null,
runtime: resolver.runtime?.name ?? (resolver.requestMappingTemplate ? 'VTL' : null),
code: resolver.code ?? null,
})),
} : {}),
},
}
}
/**
* Why a schema was rejected. AWS sends a sentence; the runtime sends JSON whose
* codeErrors carry the parser's messages, which are what a person needs.
*/
export function schemaFailure(details: string | undefined): string {
if (!details) return 'AppSync rejected it'
try {
const parsed = JSON.parse(details) as {detail?: {codeErrors?: Array<{value?: unknown}>}}
const messages = (parsed.detail?.codeErrors ?? []).map((error) => error.value).filter((value): value is string => typeof value === 'string' && value !== '')
return messages.length > 0 ? messages.join('; ') : details
} catch {
return details
}
}
/** AWS returns the SDL itself; the runtime wraps it as {"schema": {"definition": …}}. */
export function sdlFrom(body: string): string {
const trimmed = body.trim()
if (!trimmed.startsWith('{"')) return body
try {
const parsed = JSON.parse(trimmed) as {schema?: {definition?: unknown}}
return typeof parsed.schema?.definition === 'string' ? parsed.schema.definition : body
} catch {
return body
}
}
/**
* The object types of an SDL schema and their field names: what a resolver can
* attach to. A small reader, not a GraphQL parser: it drops comments, strings
* and arguments, then reads `type Name { field: … }` blocks.
*/
export function objectTypes(sdl: string): Array<{name: string; fields: string[]}> {
const stripped = sdl
.replace(/"""[\s\S]*?"""/g, '')
.replace(/"(?:[^"\\\n]|\\.)*"/g, '')
.replace(/#[^\n]*/g, '')
const types: Array<{name: string; fields: string[]}> = []
for (const match of stripped.matchAll(/(?:^|\s)(?:extend\s+)?type\s+([_A-Za-z][_0-9A-Za-z]*)[^{]*\{([^}]*)\}/g)) {
let body = match[2]
// Arguments may nest one level of input object literals; drop them before reading fields.
for (let previous = ''; previous !== body;) { previous = body; body = body.replace(/\([^()]*\)/g, '') }
const fields = [...body.matchAll(/([_A-Za-z][_0-9A-Za-z]*)\s*:/g)].map((field) => field[1])
const existing = types.find((type) => type.name === match[1])
if (existing) existing.fields.push(...fields.filter((field) => !existing.fields.includes(field)))
else types.push({name: match[1], fields})
}
const rootOrder = ['Query', 'Mutation', 'Subscription']
return types.sort((a, b) => {
const rank = (name: string) => rootOrder.includes(name) ? rootOrder.indexOf(name) : rootOrder.length
return rank(a.name) - rank(b.name) || a.name.localeCompare(b.name)
})
}
function expiry(days: number): number {
return Math.floor(Date.now() / 1000) + days * DAY_SECONDS
}
function text(value: unknown): string {
return typeof value === 'string' ? value.trim() : ''
}
function errorName(error: unknown): string | undefined {
return typeof error === 'object' && error !== null ? (error as {name?: string}).name : undefined
}
+3
View File
@@ -40,6 +40,7 @@ import { PipesClient } from "@aws-sdk/client-pipes";
import { EFSClient } from "@aws-sdk/client-efs";
import { GlueClient } from "@aws-sdk/client-glue";
import { AthenaClient } from "@aws-sdk/client-athena";
import { AppSyncClient } from "@aws-sdk/client-appsync";
const endpoint = process.env.FLOCI_ENDPOINT;
const region = process.env.AWS_REGION || "us-east-1";
@@ -111,6 +112,7 @@ export type AwsClients = {
efs: EFSClient;
glue: GlueClient;
athena: AthenaClient;
appsync: AppSyncClient;
};
export type AwsClientName = keyof AwsClients;
@@ -166,6 +168,7 @@ function buildClients(accountId: string): AwsClients {
efs: new EFSClient(base),
glue: new GlueClient(base),
athena: new AthenaClient(base),
appsync: new AppSyncClient(base),
};
}
@@ -0,0 +1,83 @@
import type {CloudProvider, FieldSchema, ServiceSchema, TableColumnSchema} from './types'
/** CreateGraphqlApi's name characters; the console keeps names to a readable length. */
export const GRAPHQL_API_NAME_PATTERN = '^[A-Za-z0-9_\\- ]{1,128}$'
/** CreateDataSource's name rule: a GraphQL-style identifier. */
export const GRAPHQL_DATA_SOURCE_NAME_PATTERN = '^[_A-Za-z][_0-9A-Za-z]{0,64}$'
export const GRAPHQL_AUTH_TYPES = ['API_KEY', 'AWS_IAM', 'AMAZON_COGNITO_USER_POOLS'] as const
export const GRAPHQL_DATA_SOURCE_TYPES = ['NONE', 'AMAZON_DYNAMODB', 'AWS_LAMBDA'] as const
/** AppSync's bounds on an API key's lifetime. */
export const GRAPHQL_API_KEY_MAX_DAYS = 365
const apiColumns: TableColumnSchema[] = [
{name: 'name', label: 'Name'},
{name: 'id', label: 'API ID', path: 'metadata.apiId'},
{name: 'auth', label: 'Authorization', path: 'metadata.authenticationLabel'},
{name: 'endpoint', label: 'GraphQL endpoint', path: 'metadata.graphqlUrl', emptyText: '—'},
]
const apiFilters: FieldSchema[] = [{name: 'search', label: 'Search', type: 'text', required: false}]
export function awsGraphqlSchema(): ServiceSchema {
return {
cloud: 'aws',
service: 'graphql',
displayName: 'AppSync GraphQL APIs',
fields: [
{
name: 'name',
label: 'API name',
type: 'text',
required: true,
validation: {pattern: GRAPHQL_API_NAME_PATTERN, message: 'Use up to 128 letters, numbers, spaces, dashes and underscores'},
},
{
name: 'authenticationType',
label: 'Authorization',
type: 'select',
required: false,
defaultValue: 'API_KEY',
description: 'How clients prove who they are. With an API key, AppSync creates the first key for you.',
options: [
{label: 'API key', value: 'API_KEY'},
{label: 'IAM (signed requests)', value: 'AWS_IAM'},
{label: 'Cognito user pool', value: 'AMAZON_COGNITO_USER_POOLS'},
],
},
{
name: 'userPoolId',
label: 'User pool ID',
type: 'text',
required: false,
requiredWhen: {field: 'authenticationType', equals: 'AMAZON_COGNITO_USER_POOLS'},
visibleWhen: {field: 'authenticationType', values: ['AMAZON_COGNITO_USER_POOLS']},
description: 'The Cognito user pool whose ID tokens the API accepts, such as us-east-1_AbC123.',
validation: {pattern: '^[\\w-]+_[0-9a-zA-Z]+$', message: 'Use a user pool ID such as us-east-1_AbC123'},
},
],
actions: ['list', 'create', 'delete', 'inspect'],
capabilities: {
resourceActions: [
{name: 'list', label: 'List GraphQL APIs', enabled: true, status: 'available', runtimeRequired: true},
{name: 'create', label: 'Create GraphQL API', enabled: true, status: 'available', runtimeRequired: true},
{name: 'delete', label: 'Delete GraphQL API', enabled: true, status: 'available', runtimeRequired: true},
{name: 'inspect', label: 'Inspect GraphQL API', enabled: true, status: 'available', runtimeRequired: true},
],
graphqlActions: [
{name: 'updateSchema', label: 'Save schema', enabled: true, status: 'available', runtimeRequired: true},
{name: 'createApiKey', label: 'Create API key', enabled: true, status: 'available', runtimeRequired: true},
{name: 'deleteApiKey', label: 'Delete API key', enabled: true, status: 'available', runtimeRequired: true},
{name: 'createDataSource', label: 'Create data source', enabled: true, status: 'available', runtimeRequired: true},
{name: 'deleteDataSource', label: 'Delete data source', enabled: true, status: 'available', runtimeRequired: true},
{name: 'createResolver', label: 'Attach resolver', enabled: true, status: 'available', runtimeRequired: true},
{name: 'deleteResolver', label: 'Detach resolver', enabled: true, status: 'available', runtimeRequired: true},
],
},
filters: apiFilters,
columns: apiColumns,
}
}
export function graphqlSchemaFor(cloud: CloudProvider): ServiceSchema | null {
return cloud === 'aws' ? awsGraphqlSchema() : null
}
@@ -238,6 +238,13 @@ export const SERVICE_CATALOG = {
},
identity: {displayName: 'Identity', iconKey: 'iam', group: 'Security', order: 5},
apigateway: {displayName: 'API Gateway', iconKey: 'apigateway', group: 'Integration', order: 10},
graphql: {
displayName: 'GraphQL APIs',
displayNameByCloud: {aws: 'AppSync'},
iconKey: 'graphql',
group: 'Integration',
order: 12,
},
email: {
displayName: 'Email',
displayNameByCloud: {aws: 'SES Mailbox'},
+35
View File
@@ -188,6 +188,7 @@ export type UserPoolActionName =
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'
@@ -255,6 +256,7 @@ export interface ServiceSchema {
fileSystemActions?: CapabilitySchema<FileSystemActionName>[]
dataCatalogActions?: CapabilitySchema<DataCatalogActionName>[]
queryActions?: CapabilitySchema<QueryActionName>[]
graphqlActions?: CapabilitySchema<GraphqlActionName>[]
monitoringActions?: CapabilitySchema<MonitoringActionName>[]
/** API Gateway v2 (HTTP and WebSocket APIs): what the routes, stages and security panel can do. */
httpApiActions?: CapabilitySchema<HttpApiActionName>[]
@@ -562,6 +564,32 @@ export interface AccessPointInput {
permissions: string
}
export interface GraphqlApiKeyInput {
description?: string
/** Days until the key expires: 1 to 365, 7 when left out, as in the AppSync console. */
expiresInDays?: number
}
export interface GraphqlDataSourceInput {
name: string
description?: string
type: 'NONE' | 'AMAZON_DYNAMODB' | 'AWS_LAMBDA'
/** AMAZON_DYNAMODB: the table the resolvers read and write. */
tableName?: string
/** AWS_LAMBDA: the function the resolvers invoke. */
functionArn?: string
/** The role AppSync assumes to reach the table or function; AWS requires one for both. */
serviceRoleArn?: string
}
export interface GraphqlResolverInput {
typeName: string
fieldName: string
dataSourceName: string
/** An APPSYNC_JS resolver: request() and response() exported from one module. */
code: string
}
export interface QueryInput {
sql: string
/** The Glue database unqualified table names resolve in. */
@@ -1294,6 +1322,13 @@ export interface CloudServiceAdapter {
/** With `replace`, the group launches a new instance in its place; otherwise desired capacity drops by one. */
terminateAutoScalingInstance?(groupName: string, instanceId: string, replace: boolean): Promise<void>
getCertificatePem?(certificateId: string): Promise<CertificatePem>
updateGraphqlSchema?(apiId: string, definition: string): Promise<CloudResource>
createGraphqlApiKey?(apiId: string, input: GraphqlApiKeyInput): Promise<CloudResource>
deleteGraphqlApiKey?(apiId: string, keyId: string): Promise<CloudResource>
createGraphqlDataSource?(apiId: string, input: GraphqlDataSourceInput): Promise<CloudResource>
deleteGraphqlDataSource?(apiId: string, name: string): Promise<CloudResource>
createGraphqlResolver?(apiId: string, input: GraphqlResolverInput): Promise<CloudResource>
deleteGraphqlResolver?(apiId: string, typeName: string, fieldName: string): Promise<CloudResource>
startQuery?(workGroup: string, input: QueryInput): Promise<QueryExecutionSummary>
/** The query's state, and its first rows once it has succeeded. */
getQueryResult?(workGroup: string, queryId: string): Promise<QueryResult>
+21 -1
View File
@@ -2,7 +2,7 @@ import {describe, expect, test} from 'bun:test'
import {createCloudAdapterRegistry} from './cloudProxy'
import {checkChildCapabilities} from './cloud-spi/childCapabilities'
import {isServiceType} from './cloud-spi/serviceCatalog'
import type {AutoScalingActionName, CloudProvider, CloudServiceAdapter, CloudServiceType, CertificateActionName, DatabaseActionName, DataCatalogActionName, DistributionActionName, FileSystemActionName, HttpApiActionName, QueryActionName, KubernetesActionName, MonitoringActionName, ResourceActionName, UserPoolActionName} from './cloud-spi/types'
import type {AutoScalingActionName, CloudProvider, CloudServiceAdapter, CloudServiceType, CertificateActionName, DatabaseActionName, DataCatalogActionName, DistributionActionName, FileSystemActionName, GraphqlActionName, HttpApiActionName, QueryActionName, KubernetesActionName, MonitoringActionName, ResourceActionName, UserPoolActionName} from './cloud-spi/types'
/**
* Guards the schema-to-implementation contract for every registered adapter.
@@ -81,6 +81,16 @@ const METHOD_FOR_CERTIFICATE_ACTION: Record<CertificateActionName, keyof CloudSe
revoke: 'revokeCertificate',
}
const METHOD_FOR_GRAPHQL_ACTION: Record<GraphqlActionName, keyof CloudServiceAdapter> = {
updateSchema: 'updateGraphqlSchema',
createApiKey: 'createGraphqlApiKey',
deleteApiKey: 'deleteGraphqlApiKey',
createDataSource: 'createGraphqlDataSource',
deleteDataSource: 'deleteGraphqlDataSource',
createResolver: 'createGraphqlResolver',
deleteResolver: 'deleteGraphqlResolver',
}
const METHOD_FOR_QUERY_ACTION: Record<QueryActionName, keyof CloudServiceAdapter> = {
run: 'startQuery',
results: 'getQueryResult',
@@ -239,6 +249,15 @@ describe('registered adapters honour their schema', () => {
).toBe('function')
}
const graphqlClaims = (adapter.schema().capabilities?.graphqlActions ?? []).filter((capability) => capability.status === 'available')
for (const capability of graphqlClaims) {
const method = METHOD_FOR_GRAPHQL_ACTION[capability.name]
expect(
typeof adapter[method],
`${label} advertises ${capability.name} as available but has no ${String(method)}()`,
).toBe('function')
}
const queryClaims = (adapter.schema().capabilities?.queryActions ?? []).filter((capability) => capability.status === 'available')
for (const capability of queryClaims) {
const method = METHOD_FOR_QUERY_ACTION[capability.name]
@@ -292,6 +311,7 @@ describe('registered adapters honour their schema', () => {
...(adapter.schema().capabilities?.fileSystemActions ?? []),
...(adapter.schema().capabilities?.dataCatalogActions ?? []),
...(adapter.schema().capabilities?.queryActions ?? []),
...(adapter.schema().capabilities?.graphqlActions ?? []),
...(adapter.schema().capabilities?.certificateActions ?? []),
...(adapter.schema().capabilities?.monitoringActions ?? []),
...(adapter.schema().capabilities?.httpApiActions ?? []),
+2
View File
@@ -56,6 +56,7 @@ import {AwsPipesAdapter} from './adapter-aws/AwsPipesAdapter'
import {AwsFileSystemsAdapter} from './adapter-aws/AwsFileSystemsAdapter'
import {AwsDataCatalogAdapter} from './adapter-aws/AwsDataCatalogAdapter'
import {AwsQueryAdapter} from './adapter-aws/AwsQueryAdapter'
import {AwsGraphqlAdapter} from './adapter-aws/AwsGraphqlAdapter'
import {AwsMonitoringAdapter} from './adapter-aws/AwsMonitoringAdapter'
import {awsClientsForAccount, resolveAccountId} from './aws'
import {createEc2Service} from './services/ec2'
@@ -115,6 +116,7 @@ export function createCloudAdapterRegistry(accountId?: string | null): CloudAdap
new AwsFileSystemsAdapter(clients.efs, clients.lambda, clients.ec2),
new AwsDataCatalogAdapter(clients.glue),
new AwsQueryAdapter(clients.athena),
new AwsGraphqlAdapter(clients.appsync),
new AwsMonitoringAdapter(clients.cloudwatch),
new AzureStorageAdapter(),
new AzureServiceBusAdapter(),
+31
View File
@@ -22,6 +22,7 @@ import {awsAutoScalingSchema} from '../cloud-spi/autoScalingSchema'
import {awsFileSystemsSchema} from '../cloud-spi/fileSystemsSchema'
import {awsDataCatalogSchema} from '../cloud-spi/dataCatalogSchema'
import {awsQuerySchema} from '../cloud-spi/querySchema'
import {awsGraphqlSchema} from '../cloud-spi/graphqlSchema'
import {awsCertificatesSchema} from '../cloud-spi/certificatesSchema'
import {awsMonitoringSchema} from '../cloud-spi/monitoringSchema'
import {awsAppConfigSchema} from '../cloud-spi/appConfigSchema'
@@ -878,6 +879,36 @@ describe('cloud schema routes', () => {
expect(calls).toEqual([['capacity', 'web-asg', {desiredCapacity: 3}], ['terminate', 'web-asg', 'i-abc', true]])
})
test('manages the schema, keys, data sources and resolvers through the AppSync adapter', async () => {
const calls: unknown[] = []
const api = {id: 'a1', name: 'notes', cloud: 'aws' as const, service: 'graphql' as const, type: 'graphqlApi', region: null, createdAt: null, metadata: {}}
const app = appWithRoutes([mockAdapter('aws', {
service: 'graphql',
schema: awsGraphqlSchema,
updateGraphqlSchema: async (id, definition) => { calls.push(['schema', id, definition]); return api },
createGraphqlApiKey: async (id, input) => { calls.push(['key', id, input.expiresInDays]); return api },
deleteGraphqlApiKey: async (id, keyId) => { calls.push(['delete-key', id, keyId]); return api },
createGraphqlDataSource: async (id, input) => { calls.push(['source', id, input.name, input.type]); return api },
deleteGraphqlDataSource: async (id, name) => { calls.push(['delete-source', id, name]); return api },
createGraphqlResolver: async (id, input) => { calls.push(['resolver', id, input.typeName, input.fieldName]); return api },
deleteGraphqlResolver: async (id, typeName, fieldName) => { calls.push(['delete-resolver', id, typeName, fieldName]); return api },
})])
const json = (method: string, body: unknown) => ({method, headers: {'content-type': 'application/json'}, body: JSON.stringify(body)})
const base = '/api/clouds/aws/services/graphql/resources/a1'
expect((await app.request(`${base}/schema`, json('PUT', {definition: 'type Query { a: String }'}))).status).toBe(200)
expect((await app.request(`${base}/api-keys`, json('POST', {expiresInDays: 30}))).status).toBe(201)
expect((await app.request(`${base}/api-keys/da2-x`, {method: 'DELETE'})).status).toBe(200)
expect((await app.request(`${base}/data-sources`, json('POST', {name: 'none', type: 'NONE'}))).status).toBe(201)
expect((await app.request(`${base}/data-sources/none`, {method: 'DELETE'})).status).toBe(200)
expect((await app.request(`${base}/resolvers`, json('POST', {typeName: 'Query', fieldName: 'a', dataSourceName: 'none', code: ''}))).status).toBe(201)
expect((await app.request(`${base}/resolvers/Query/a`, {method: 'DELETE'})).status).toBe(200)
expect(calls).toEqual([
['schema', 'a1', 'type Query { a: String }'], ['key', 'a1', 30], ['delete-key', 'a1', 'da2-x'],
['source', 'a1', 'none', 'NONE'], ['delete-source', 'a1', 'none'], ['resolver', 'a1', 'Query', 'a'], ['delete-resolver', 'a1', 'Query', 'a'],
])
})
test('runs, reads, lists and cancels queries through the Athena adapter', async () => {
const calls: unknown[] = []
const execution = {id: 'q1', sql: 'SELECT 1', database: 'shop', workGroup: 'analysts', state: 'SUCCEEDED', stateReason: null, statementType: 'DML', submittedAt: null, completedAt: null, runtimeMs: 5, dataScannedBytes: 0, outputLocation: 's3://r/q1.csv'}
+55
View File
@@ -6,6 +6,9 @@ import type {
AccessPointInput,
CatalogTableInput,
QueryInput,
GraphqlApiKeyInput,
GraphqlDataSourceInput,
GraphqlResolverInput,
FileSystemAttachmentInput,
CertificateRevocationReason,
CloudProvider,
@@ -558,6 +561,58 @@ export function createCloudRoutes(injectedService?: CloudProxyService) {
})
})
app.put('/:cloud/services/graphql/resources/:id/schema', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => {
const body = await c.req.json<{definition?: string}>()
return c.json(await svc(c).updateGraphqlSchema(cloud, c.req.param('id'), body.definition ?? ''))
})
})
app.post('/:cloud/services/graphql/resources/:id/api-keys', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).createGraphqlApiKey(cloud, c.req.param('id'), await c.req.json<GraphqlApiKeyInput>()), 201))
})
app.delete('/:cloud/services/graphql/resources/:id/api-keys/:keyId', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).deleteGraphqlApiKey(cloud, c.req.param('id'), c.req.param('keyId'))))
})
app.post('/:cloud/services/graphql/resources/:id/data-sources', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).createGraphqlDataSource(cloud, c.req.param('id'), await c.req.json<GraphqlDataSourceInput>()), 201))
})
app.delete('/:cloud/services/graphql/resources/:id/data-sources/:name', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).deleteGraphqlDataSource(cloud, c.req.param('id'), c.req.param('name'))))
})
app.post('/:cloud/services/graphql/resources/:id/resolvers', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).createGraphqlResolver(cloud, c.req.param('id'), await c.req.json<GraphqlResolverInput>()), 201))
})
app.delete('/:cloud/services/graphql/resources/:id/resolvers/:typeName/:fieldName', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).deleteGraphqlResolver(cloud, c.req.param('id'), c.req.param('typeName'), c.req.param('fieldName'))))
})
app.get('/:cloud/services/query/catalog', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
@@ -97,6 +97,9 @@ import type {
AccessPointInput,
CatalogTableInput,
QueryCatalog,
GraphqlApiKeyInput,
GraphqlDataSourceInput,
GraphqlResolverInput,
QueryExecutionSummary,
QueryInput,
QueryResult,
@@ -971,6 +974,48 @@ export class CloudProxyService {
return adapter.revokeCertificate(certificateId, reason)
}
async updateGraphqlSchema(cloud: CloudProvider, apiId: string, definition: string): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.updateGraphqlSchema) throw new NotSupportedError(`Saving schemas is not supported for ${cloud}/graphql`)
return adapter.updateGraphqlSchema(apiId, definition)
}
async createGraphqlApiKey(cloud: CloudProvider, apiId: string, input: GraphqlApiKeyInput): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.createGraphqlApiKey) throw new NotSupportedError(`API keys are not supported for ${cloud}/graphql`)
return adapter.createGraphqlApiKey(apiId, input)
}
async deleteGraphqlApiKey(cloud: CloudProvider, apiId: string, keyId: string): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.deleteGraphqlApiKey) throw new NotSupportedError(`API keys are not supported for ${cloud}/graphql`)
return adapter.deleteGraphqlApiKey(apiId, keyId)
}
async createGraphqlDataSource(cloud: CloudProvider, apiId: string, input: GraphqlDataSourceInput): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.createGraphqlDataSource) throw new NotSupportedError(`Data sources are not supported for ${cloud}/graphql`)
return adapter.createGraphqlDataSource(apiId, input)
}
async deleteGraphqlDataSource(cloud: CloudProvider, apiId: string, name: string): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.deleteGraphqlDataSource) throw new NotSupportedError(`Data sources are not supported for ${cloud}/graphql`)
return adapter.deleteGraphqlDataSource(apiId, name)
}
async createGraphqlResolver(cloud: CloudProvider, apiId: string, input: GraphqlResolverInput): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.createGraphqlResolver) throw new NotSupportedError(`Resolvers are not supported for ${cloud}/graphql`)
return adapter.createGraphqlResolver(apiId, input)
}
async deleteGraphqlResolver(cloud: CloudProvider, apiId: string, typeName: string, fieldName: string): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.deleteGraphqlResolver) throw new NotSupportedError(`Resolvers are not supported for ${cloud}/graphql`)
return adapter.deleteGraphqlResolver(apiId, typeName, fieldName)
}
async startQuery(cloud: CloudProvider, workGroup: string, input: QueryInput): Promise<QueryExecutionSummary> {
const adapter = this.requireAdapter(cloud, 'query')
if (!adapter.startQuery) throw new NotSupportedError(`Running queries is not supported for ${cloud}/query`)