Appearance
GraphQL (ctx.graphql)
ctx.graphql.query runs a GraphQL operation against the CoCoCo API from inside a script. It uses the same schema as the public API, runs with the permissions of the identity executing the script, and is limited to the script's tenant.
Signature
text
ctx.graphql.query(query: string, variables: table?) -> (ok, res)query: the operation text, a query or a mutation. Subscriptions are not supported.variables: a table of variable values. Omit it or passnilfor none.- On success
resis{ data = …, errors = … }. Both fields are optional.
Three kinds of failure
| Where it failed | What you see |
|---|---|
| The operation text is not valid GraphQL syntax, or the operation could not be executed at all | ok == false, res is a message string |
| The operation failed validation (for example an unknown field), or a field failed while resolving | ok == true, res.errors is a list of { message } |
| A mutation's input was refused | ok == true, the payload's own errors { path message } field is non-empty |
A non-string query or a non-table variables raises.
Query example
lua
local ok, result = ctx.graphql.query([[
query ListCustomers($first: Int!) {
listCustomers(first: $first) {
edges { node { id name email isActive } }
totalCount
}
}
]], { first = 5 })
if not ok then error(result) end
if result.errors then error(ctx.json.encode(result.errors)) end
local data = result.data
if data == nil then error("GraphQL returned no data") end
local customers = {}
for _, edge in ipairs(data.listCustomers.edges) do
table.insert(customers, { name = edge.node.name, email = edge.node.email })
end
return { total = data.listCustomers.totalCount, customers = customers }List fields return connections (edges { node { … } }, totalCount), as described in core patterns.
Mutation example
lua
local MUTATION = [[
mutation UpsertCustomer($input: UpsertCustomerInput!) {
upsertCustomer(input: $input) {
customer { id name }
errors { path message }
}
}
]]
local ok, result = ctx.graphql.query(MUTATION, {
input = { name = "Beta Industries", email = "ops@beta.example" },
})
if not ok then error(result) end
if result.errors then error(ctx.json.encode(result.errors)) end
local data = result.data
if data == nil then error("GraphQL returned no data") end
local payload = data.upsertCustomer
if #payload.errors > 0 then
return { saved = false, errors = payload.errors }
end
return { saved = true, id = payload.customer.id }The same operation, checked against the public schema:
graphql
mutation UpsertCustomer($input: UpsertCustomerInput!) {
upsertCustomer(input: $input) {
customer { id name }
errors { path message }
}
}Tips
- Keep the operation in a long string (
[[ … ]]) and pass values as variables rather than concatenating them into the query text. - Test operations in the console's GraphQL playground (
/#/graphql-playground) first. - Look up types in the schema reference.