docs: migrate to docusaurus

GITHUB_PR_NUMBER: 8048
GITHUB_PR_URL: https://github.com/hasura/graphql-engine/pull/8048

PR-URL: https://github.com/hasura/graphql-engine-mono/pull/3395
Co-authored-by: Sai Krishna Prasad Kandula <22497932+KRRISH96@users.noreply.github.com>
Co-authored-by: Vishnu Bharathi <4211715+scriptnull@users.noreply.github.com>
Co-authored-by: Rikin Kachhia <54616969+rikinsk@users.noreply.github.com>
GitOrigin-RevId: 43019ef28a72561ba78a3cac9c783ccaa125e3f6
This commit is contained in:
hasura-bot 2022-03-28 02:12:27 -07:00
parent 7d8a794821
commit 4bba04d0f6
1033 changed files with 85176 additions and 0 deletions

20
docs-new/.gitignore vendored Normal file
View File

@ -0,0 +1,20 @@
# Dependencies
/node_modules
# Production
/build
# Generated files
.docusaurus
.cache-loader
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

93
docs-new/CONTRIBUTING.md Normal file
View File

@ -0,0 +1,93 @@
# Contributing
Hasura GraphQL engine docs are built using [Docusaurus 2](https://docusaurus.io/) and are written in MDX.
## Docs issues in the repo
Issues in the repo for documentation are labelled as `c/docs`
(see [list](https://github.com/hasura/graphql-engine/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen++label%3Ac%2Fdocs)).
Issues also labelled as `good first issue` are aimed at those making their first contribution to the repo
(see [list](https://github.com/hasura/graphql-engine/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen++label%3Ac%2Fdocs+label%3A%22good+first+issue%22)).
Issues also marked as `help wanted`
(see [list](https://github.com/hasura/graphql-engine/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen++label%3Ac%2Fdocs+label%3A%22help+wanted%22))
are those that require community contributions.
Please note that some of these issues, labelled with both `c/docs` and `c/console`/`c/server`, are part of a
change/task that requires modifications in some component of GraphQL engine and the docs.
Feel free to open pull requests to address these issues or to add/fix docs features/content, even if a
corresponding issue doesn't exist. If you are unsure about whether to go ahead and work on something like
the latter, please get in touch with the maintainers in the `GraphQL engine`->`contrib` channel in the
community [Discord](https://discord.gg/vBPpJkS).
## Setup requirements
- [Node](https://nodejs.org/)
- [Yarn](https://yarnpkg.com/getting-started)
## Steps for contributing
We use the [fork-and-branch git workflow](https://blog.scottlowe.org/2015/01/27/using-fork-branch-git-workflow/).
- Fork the repo and clone it:
```bash
git clone https://github.com/<your-username>/graphql-engine
```
- Move to the `docs` folder via the command line and checkout to a new branch:
```bash
cd docs
git checkout -b <new-branch-name>
```
- Install dependencies:
```
yarn install
```
- For development, live reload and auto build while you're editing and saving files:
```bash
yarn start
```
- Make the required changes.
- (Optional) Build docs to produce build files and verify:
```bash
yarn build
```
- The generated docs are in `build`.
- View the built files by running a webserver:
```bash
yarn serve
```
- Commit the changes. Follow the common guidelines for commit messages at the [main contributing guide](../CONTRIBUTING.md#common-guidelines).
- Push the changes to your fork and submit a pull request.
### Changelog
In order for all the checks to pass on GitHub, it's required to do one of the following:
- Make an entry to the `CHANGELOG.md` file (under "Next release") to describe the change from a user's perspective.
- Add the `no-changelog-required` label.
For docs, a changelog entry is required for the following:
- Entire new docs pages
- Considerable changes in the overall structure
For small changes (such as fixes, adding examples, UI changes etc.), the `no-changelog-required` label will suffice.
## Some guidelines while adding docs
### Style guide
Please follow our [guide on how to write docs pages](https://github.com/hasura/graphql-engine/wiki/How-to-write-docs-pages) in order to keep the structure and style of our docs consistent.
<!-- TODO: REMOVE THIS fter updating above linked wiki file -->
[Page Structure](./wiki/page-structure.mdx)
### Pre-commit checks
- Just before committing your changes, delete your local `build` folder completely and then build docs again. Scan the output and look for any syntax warnings (e.g. title underline too short, could not lex literal block, etc.).
Ideally there should not be any syntax warnings that are being thrown.
## Notes
- Docs are currently deployed manually. Changes will not reflect immediately after a PR gets merged.
- The search is powered by [Algolia](https://www.algolia.com/) and is updated everyday. Your local changes
will not be reflected in search results.

33
docs-new/README.md Normal file
View File

@ -0,0 +1,33 @@
# Website
This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator.
### Installation
```
$ yarn
```
### Local Development
```
$ yarn start
```
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
### Build
```
$ yarn build
```
This command generates static content into the `build` directory and can be served using any static contents hosting service.
### Deployment
```
$ GIT_USER=<Your GitHub username> USE_SSH=true yarn deploy
```
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.

3
docs-new/babel.config.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
};

View File

@ -0,0 +1,3 @@
{
"label": "Hasura Docs"
}

View File

@ -0,0 +1,4 @@
{
"label": "Hasura Cloud",
"position": 2
}

View File

@ -0,0 +1,4 @@
{
"label": "Account management",
"position": 13
}

View File

@ -0,0 +1,59 @@
---
sidebar_label: Change email
description: Hasura Cloud Email Change
keywords:
- hasura
- docs
- cloud
- email
---
import Thumbnail from "@site/src/components/Thumbnail";
# Change email address on Hasura Cloud
## Introduction
You can edit the email address on your Hasura Cloud account to another email from the `Account Settings` page.
## Changing email for users logged in using email {#email-change}
[Sign in](https://cloud.hasura.io/login?redirect_url=/) to your Hasura Cloud account using email and click `My Account`.
On the `Account Settings` page, select the `Edit` button.
<Thumbnail
src="/img/graphql/cloud/account-settings/account-settings-tab.png"
alt="Account Management"
width="1100px"
/>
Enter the email you want to transfer the account to and click the `Change` button to send a transfer request.
<Thumbnail
src="/img/graphql/cloud/account-settings/edit-email-input.png"
alt="edit email section"
width="800px"
/>
The invitee receives an email verification mail. Once the invitee clicks the link, it logs out the existing user and redirects the invitee to the Hasura Cloud login page.
The user can now log in to Hasura Cloud using the new email and the password for the old email.
## Changing email for users with social logins
If you logged in to Hasura Cloud with your social login, you must reset your password to initiate the email change process.
On the [Sign in](https://cloud.hasura.io/login?redirect_url=/) page, select `Forgot?`.
<Thumbnail
src="/img/graphql/cloud/account-settings/forgot-password.png"
alt="Forgot password"
width="450px"
/>
Next, enter the new email id and click **Recover Password**.
Set a new password by clicking on the reset password link sent to your email address.
You can now log in with the email and this new password and follow the steps mentioned in the [above section](#email-change) to change the email.
You can also use the social login associated with the new email to log in to Hasura Cloud!

View File

@ -0,0 +1,22 @@
---
slug: index
title: "Account management"
description: Hasura Cloud Account Management
keywords:
- hasura
- docs
- cloud
- account
- email
sidebar_label: Account management
---
# Hasura Cloud account management
## Introduction
On your Hasura Cloud `My Account` page, you can manage account-related settings such as changing the email,
creating access tokens, and managing database session connections.
- [Change email address on Hasura Cloud](/graphql/cloud/account-management/email-change.mdx)

View File

@ -0,0 +1,182 @@
---
description: Hasura Cloud API reference
keywords:
- hasura
- cloud
- docs
- API
- API reference
sidebar_position: 15
---
import TOCInline from "@theme/TOCInline";
# API Reference
## Introduction
Hasura Cloud provides a GraphQL API to interact with the services to create and manage your projects.
You can use any GraphQL client and use the API with the right authentication header.
## Endpoint
API endpoint is `https://data.pro.hasura.io/v1/graphql`.
## Authentication
Authentication is done using a Personal Access Token that you can create from the Hasura Cloud Dashboard. You can find this option in the "My Account" section on bottom left.
Once you have the token it can be used with the header: `Authorization: pat <token>`.
:::info Note
This token can be used to authenticate against Hasura Cloud APIs and your Hasura Cloud projects. Make sure you keep it secure. The token will be valid until you delete it from the dashboard.
:::
## APIs
Each Hasura Cloud project is backed by an API entity called "Tenant", with a distinct "Tenant ID" which is different from "Project ID". Each Project is associated with a Tenant. In some cases, like Metrics API, the Project ID is used instead of Tenant ID.
List of some useful APIs:
<TOCInline toc={toc} filterTOC={(tocTree) => tocTree[3].children} />
### Create a Project
```graphql
mutation createProject {
createTenant(
cloud: "aws"
region: "us-east-2"
envs: [{
key: "HASURA_GRAPHQL_CORS_DOMAIN",
value: "*"
}, {
key: "MY_ENV_VAR_1",
value: "my value 1"
}]
) {
id
name
}
}
```
### Get Project tenant id
```graphql
query getProjectTenantId {
projects_by_pk(id: "7a79cf94-0e53-4520-a560-1b02bf522f08") {
id
tenant {
id
}
}
}
```
### Get Tenant details
```graphql
query getTenantDetails {
tenant_by_pk(id: "7a79cf94-0e53-4520-a560-1b02bf522f08") {
id
slug
project {
id
endpoint
}
}
}
```
### Delete a Tenant
```graphql
mutation deleteTenant {
deleteTenant(tenantId: "7a79cf94-0e53-4520-a560-1b02bf522f08") {
status
}
}
```
### Get ENV Vars
```graphql
query getTenantENV {
getTenantEnv(tenantId: "7a79cf94-0e53-4520-a560-1b02bf522f08") {
hash
envVars
}
}
```
### Update ENV Vars
```graphql
mutation updateTenantEnv {
updateTenantEnv(
tenantId: "7a79cf94-0e53-4520-a560-1b02bf522f08"
currentHash: "6902a395d70072fbf8d36288f0eacc36c9d82e68"
envs: [
{ key: "HASURA_GRAPHQL_ENABLE_CONSOLE", value: "true" },
{
key: "ACTIONS_ENDPOINT",
value: "https://my-actions-endpoint.com/actions"
}
]
) {
hash
envVars
}
}
```
### Create GitHub Preview App {#api-ref-create-preview-app}
Schedules the creation of a Hasura Cloud project with metadata and migrations from a branch of a GitHub repo.
```graphql
mutation createGitHubPreviewApp {
createGitHubPreviewApp(
payload: {
githubPersonalAccessToken: "<github_access_token>"
githubRepoDetails: {
branch: "main"
owner: "my-org"
repo: "my-repo",
directory: "backend/hasura"
},
projectOptions: {
cloud: "aws",
region: "us-east-2",
plan: "cloud_free",
name: "my-app_name"
envVars: [
{ key: "HASURA_GRAPHQL_AUTH_HOOK", value: "https://my-webhook.com" },
{ key: "MY_ENV_VAR_1", value: "my value 1" }
]
}
}
) {
githubPreviewAppJobID # job ID of the preview app creation job
}
}
```
The arguments mean the following:
- `githubPersonalAccessToken`: GitHub personal access token for Hasura Cloud to access the metadata and migrations from your repository
- `githubRepoDetails`: GitHub configuration of this preview app:
- `owner`: The GitHub profile or the org that the repo with metadata/migrations belongs to
- `repo`: Name of the GitHub repository that contains the metadata and migrations
- `branch`: Name of the branch to deploy
- `directory`: Path to the directory of the Hasura project (typically created by the Hasura CLI) in the repository
- `projectOptions`: Configuration of the created preview app:
- `name`: Name of the preview app; can contain lowercase characters, numbers and hyphens
- `cloud`: The cloud provider to deploy the preview app on. Currently only `aws` is supported
- `region`: AWS Region to deploy the preview app on (refer to the Hasura Cloud dashboard to see the available regions)
- `plan`: The pricing tier of the created preview app. Set `cloud_free` for free tier and `cloud_payg` for standard tier
- `envVars`: Env vars for the created preview app

View File

@ -0,0 +1,4 @@
{
"label": "Billing",
"position": 12
}

View File

@ -0,0 +1,42 @@
---
description: Hasura Cloud coupon and credits
keywords:
- hasura
- docs
- cloud
- coupon
- credits
sidebar_position: 2
---
import Thumbnail from "@site/src/components/Thumbnail";
# Coupons and credits
## Introduction
If you have a coupon, you can redeem it from the dashboard to get a credit waiver on your next invoice. Discounts will be adjusted while creating the invoice.
## Redeem a coupon
Navigate to the `Billing` tab, click on `Coupons and Credits`, enter the code and click on the redeem button. Only one coupon is applied.
:::info
Note If there is an active coupon and another coupon is applied, then the later coupon is used.
:::
<Thumbnail
src="/img/graphql/cloud/billing/coupon_redemption.png"
alt="Coupons and Credits"
/>
<Thumbnail
src="/img/graphql/cloud/billing/applied_coupon.png"
alt="Applied coupon"
/>
## View applied coupon
You can see the applied coupon on the `Active` tab under `Coupon and Credits` and you can view previous coupons on the `Past` tab.

View File

@ -0,0 +1,27 @@
---
description: Hasura Cloud billing
keywords:
- hasura
- docs
- cloud
- billing
- payment
- invoice
slug: index
---
import Thumbnail from "@site/src/components/Thumbnail";
# Hasura Cloud billing
## Introduction
All Hasura Cloud billing related details can be found under the `Billing` tab in the Hasura Cloud dashboard
<Thumbnail src="/img/graphql/cloud/billing/billing.png" alt="Billing" />
## Details
- [Manage payment methods](/graphql/cloud/billing/payment-methods.mdx)
- [Coupons and credits](/graphql/cloud/billing/credits.mdx)
- [Receipts](/graphql/cloud/billing/receipts.mdx)

View File

@ -0,0 +1,74 @@
---
description: Manage Payment Methods
keywords:
- hasura
- docs
- cloud
- payment
- cards
- manage cards
- payment methods
- manage payment methods
sidebar_position: 1
---
import Thumbnail from "@site/src/components/Thumbnail";
# Manage payment methods
## Introduction
You can add one or more cards as a payment method for the upcoming billing cycles on your Hasura Cloud account.
## Add a new card
Go to the billing section, and click on `View Cards`.
<Thumbnail
src="/img/graphql/cloud/billing/manage_cards.png"
alt="view saved cards"
/>
Click the `+` sign to add a new card.
<Thumbnail
src="/img/graphql/cloud/billing/add_new_card.png"
alt="add a new card"
width="437px"
/>
After adding appropriate values, click `Save`.
## Setting a default card
The default card is used for the payment of upcoming billing cycles.
Select the card you want to set as the default payment method or add a new card, check the `Set Card as Default` option and click `Save`.
<Thumbnail
src="/img/graphql/cloud/billing/set_existing_default.png"
alt="set an exiting card as the default card"
width="437px"
/>
<Thumbnail
src="/img/graphql/cloud/billing/set_new_default.png"
alt="Add a new card as the default card"
width="437px"
/>
## Delete a card
Select the card you want to delete and click the `Remove Card` option.
<Thumbnail
src="/img/graphql/cloud/billing/delete_card.png"
alt="Delete card"
width="437px"
/>
:::info Note
A card set as default can not be deleted if the user has billable projects or pending dues.
:::

View File

@ -0,0 +1,58 @@
---
description: Hasura Cloud receipts
keywords:
- hasura
- docs
- cloud
- payment
- receipts
sidebar_position: 3
---
import Thumbnail from "@site/src/components/Thumbnail";
# Receipts
## Introduction
Receipts, against successful payment of invoices for each billing cycle, are mailed to the email associated with your Hasura Cloud account.
If you wish to receive receipts on another email, in addition to your account's default email, please configure a billing email.
## Configure billing email
Go to the billing section and click on `Invoice Settings`.
<Thumbnail
src="/img/graphql/cloud/billing/invoice_settings.png"
alt="invoice settings"
/>
Click on `Billing Email` and enter the email you want to receive receipts on.
<Thumbnail
src="/img/graphql/cloud/billing/configure_billing_email.png"
alt="configure billing email"
width="437px"
/>
Click `Save`.
For all payments made, receipt will also be mailed to the billing email in addition to your account's default email.
## Delete billing email
Go to the billing section and click on `Invoice Settings`.
<Thumbnail
src="/img/graphql/cloud/billing/invoice_settings.png"
alt="invoice settings"
/>
Click on `Billing Email` and click `Remove billing email`.
<Thumbnail
src="/img/graphql/cloud/billing/delete_billing_email.png"
alt="delete billing email"
width="437px"
/>

View File

@ -0,0 +1,150 @@
---
description: Dedicated VPC with VPC peering and private network access
keywords:
- hasura
- cloud
- docs
- VPC
- VPC peering
sidebar_position: 11
---
import Thumbnail from "@site/src/components/Thumbnail";
# Dedicated VPC
## Introduction
Users can request a Dedicated VPC to be provisioned for them on Hasura Cloud so that they have better isolation in terms of their project placement and they can initiate VPC peering with their own networks for secure connectivity.
:::info Note
Dedicated VPC is only available as part of **Cloud Enterprise** plan. Peering requests are only available for **AWS** or services running on AWS. [Contact Sales](https://hasura.io/contact-us/) to know more.
:::
## Creating a VPC
Once the feature is enabled for your account, you'll see a new tab on the dashboard called **VPCs**. All existing VPCs can be found here. You can also initiate a request to create a new VPC. To request a new VPC, click on the **Create New VPC** button on top. It'll open up a form with the following fields:
<Thumbnail
src="/img/graphql/cloud/dedicated-vpc/view-vpc-list.png"
alt="VPC list"
width="1146px"
/>
Enter the following details:
- **VPC Display Name**
- **VPC CIDR block**: A valid private IPV4 CIDR block (it cannot be `10.2.0.0/16`, also it cannot conflict with your VPCs that you intend to peer with this VPC)
- **VPC Region**: region where the VPC should be provisioned (note that projects will also be created in this region, within the VPC)
Once you submit the request, the VPC will be shown as **Pending**. Hasura Cloud team may take 1-2 business days to complete your request. Once the VPC is provisioned, you will be able to see the VPC's details and create peering and projects.
If the provisioning failed, you'll see the VPC in a **Failed** state. Reach out to support to resolve this.
## Create projects within the VPC
Once the VPC is provisioned, create a project by clicking on the **New Project** button in VPC details screen or get in touch with us to migrate your existing hasura project to the VPC.
<Thumbnail
src="/img/graphql/cloud/dedicated-vpc/create-vpc-projects.png"
alt="Create VPC Project"
width="600px"
/>
All projects within a VPC is listed under **Projects**.
<Thumbnail
src="/img/graphql/cloud/dedicated-vpc/vpc-projects-list.png"
alt="VPC Projects List"
width="900px"
/>
## VPC Peering
Your Dedicated VPC can be peered with other networks that you own on AWS or managed services like Aiven or Timescale Cloud that run on AWS. It will enable private connectivity to your databases and other APIs from Hasura Cloud. You will not have to expose them publicly anymore.
You can view all the request and active peerings in the **Peerings** tab.
To create a new peering request, click on the **Initiate Peering Request** button.
<Thumbnail
src="/img/graphql/cloud/dedicated-vpc/create-peering-request.png"
alt="Create Peering Request"
width="900px"
/>
There are two types of peering requests:
- Hasura to Customer
- Customer to Hasura
### Hasura to Customer
This is typically used if you want to connect to RDS or Action/Event Trigger webhooks within an AWS VPC that you own.
<Thumbnail
src="/img/graphql/cloud/dedicated-vpc/hasura-to-customer-peering.png"
alt="Hasura to Customer"
width="600px"
/>
Fill in the form with the following details:
- **Display Name**
- **AWS Account ID**: Account ID for your AWS account which contains the VPC (typically a 12 digit number)
- **AWS VPC ID**: ID of your AWS VPC that you want to peer with (starts with `vpc-`)
- **AWS VPC CIDR**: CIDR of your AWS VPC (if you have more than one CIDR for the VPC, please contact us)
- **Region**: AWS region where your VPC is provisioned
Once you fill in these details and initiate the peering request, it will appear as **Request Pending**. Hasura Cloud team may take 1-2 business day to provision the peering request. Once it is provisioned, you will see that status is changed to **Action Required**.
Accept the request on your AWS account to activate the peering connection. Once you do this, status will turn to **Active**. Note that it might take some time for the status to get updated on the dashboard.
After accepting the peering request, you need to follow these steps to start using the private network:
- Access the subnet associated with the resource that you want to connect to Hasura cloud
- Access the route table for this subnet
- Add a new entry for the Dedicated VPC CIDR with target as the VPC peering connection ID
- Access the security group associated with the resource
- Add an inbound rule to allow required traffic (say port 5432) from Dedicated VPC CIDR
Once this is done, you should be able to use private IP addresses and private DNS names as Database URLs or Webhook URLs.
Reach out to support using the **Help & Support** tab on dashboard if you face any issues.
If the provisioning failed, you'll see the status as **Failed**. Reach out to support to resolve this.
### Customer to Hasura
This mode can be used if you're using a managed 3rd party service like Aiven or Timescale Cloud and want to initiate a peering request towards Hasura Cloud.
<Thumbnail
src="/img/graphql/cloud/dedicated-vpc/customer-to-hasura-peering.png"
alt="Customer to Hasura"
width="600px"
/>
This popup shows all the required info to create a peering request from the 3rd party service:
- **AWS Account ID**: This is the account ID of Hasura Cloud's AWS account
- **AWS VPC ID**: This is the ID for the Dedicated VPC that Hasura Cloud has provisioned for you on AWS
- **AWS VPC CIDR**: CIDR of your Dedicated VPC
- **AWS VPC Region**: Region where your VPC is provisioned
Enter these details into the peering connection form of the 3rd party service. Once you do that, the 3rd party service will show similar details so that they can be entered into the form on Hasura Cloud Dashboard.
:::info Note
VPC CIDR on the 3rd party service could be any valid CIDR block other than `10.2.0.0/16` and the CIDR of your VPC on Hasura Cloud.
:::
Once you enter and initiate the peering request, you will see the peering as **Request Pending** on the dashboard. Hasura Cloud team may take 1-2 days to process the request. Once Hasura accepts the request, you will see that the peering is **Active**.
Now you should be able to use private IP addresses and private DNS names as Database URLs or Webhook URLs.
Reach out to support using the **Help & Support** tab on dashboard if you face any issues.
If the provisioning failed, you'll see the status as **Failed**. Reach out to support to resolve this.

View File

@ -0,0 +1,4 @@
{
"label": "Getting Started",
"position": 1
}

View File

@ -0,0 +1,4 @@
{
"label": "Cloud databases guides",
"position": 1
}

View File

@ -0,0 +1,191 @@
---
description: Using Hasura with an Aiven Postgres database
keywords:
- hasura
- docs
- existing database
- guide
- aiven
sidebar_label: Aiven Postgres
sidebar_position: 1
---
import Thumbnail from "@site/src/components/Thumbnail";
# Using Hasura Cloud with an Aiven Postgres database
## Introduction
This guide explains how to connect a new or existing Aiven Postgres
database to a Hasura Cloud project.
## Step 0: Sign up or log in to Hasura Cloud
Navigate to [Hasura Cloud](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=navigate-to-hasura-cloud&tech=default)
and sign up or log in.
## Step 1: Create a Hasura Cloud project {#create-hasura-project-aiven}
On the Hasura Cloud dashboard, create a new project:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/create-hasura-cloud-project.png"
alt="Create Hasura Cloud project"
width="1000px"
/>
After the project is initialized successfully, click on `Launch console`
to open the Hasura console in your browser.
On the Hasura console, navigate to
`Data -> Manage -> Connect Database -> Connect existing database`:
You will get prompted for a Postgres Database URL. We will create this
in the next step and then come back here.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/existing-db-setup.png"
alt="Hasura Cloud database setup"
width="700px"
/>
## Step 2: Create a Postgres DB on Aiven (skip if you have an existing DB) {#create-pg-db-aiven}
Log into the [Aiven console](https://console.aiven.io/login).
On the Aiven console, click `+ Create a new service`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aiven/create-new-service.png"
alt="Create a new service on Aiven"
width="1000px"
/>
Select `Postgres`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aiven/select-postgres.png"
alt="Select Postgres on Aiven"
width="1000px"
/>
Scroll down and select the `Cloud Provider`, `Region` and `Service Plan`
based on your requirements.
In the end, enter a `Name` for the service:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aiven/create-service.png"
alt="Create a service on Aiven"
width="1000px"
/>
Then click `Create service`.
:::info Note
If you're using a database user other than the default one, make sure to
give it the right [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx).
:::
## Step 3: Allow connections to your DB from Hasura Cloud
On the `Services` dashboard, click on your DB:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aiven/select-db.png"
alt="Select DB on Aiven"
width="1000px"
/>
Scroll down to `Allowed IP Addresses` and click on `Change`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aiven/change-allowed-ip-addresses.png"
alt="Change allowed IP addresses on Aiven"
width="1000px"
/>
Copy the IP address from the copy icon in the `Hasura Cloud IP` field on
the project's details view on Hasura Cloud.
<Thumbnail
src="/img/graphql/cloud/projects/hasura-cloud-ip.png"
alt="Hasura Cloud IP field"
width="1000px"
/>
Add the Hasura IP address that you copied, click on the `+`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aiven/add-hasura-ip.png"
alt="Add the Hasura IP on Aiven"
width="1000px"
/>
Then click on `Save changes`.
## Step 4: Get the database connection URL {#get-db-url-aiven}
The structure of the database connection URL looks as follows:
```bash
postgresql://<user-name>:<password>@<public-ip>:<postgres-port>/<db>
```
To get it, navigate to the `Overview` tab of your database dashboard and
copy the `Service URI`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aiven/copy-service-uri.png"
alt="Copy the service URI on Aiven"
width="1000px"
/>
## Step 5: Finish connecting the database
Back on Hasura Console, enter the database URL that we retrieved in
[step 4](#get-db-url-aiven):
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="Database setup"
width="600px"
/>
Then click `Connect Database`.
:::info Note
For security reasons, it is recommended to set database URLs as
[env vars](/graphql/cloud/projects/env-vars.mdx) and using the env vars to connect
to the databases in place of the raw database URLs.
:::
Voilà. You are ready to start developing.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/hasura-console.png"
alt="Hasura console"
width="1100px"
/>
## Next steps
You can check out our [30-Minute Hasura Basics
Course](https://hasura.io/learn/graphql/hasura/introduction/) and other
[GraphQL & Hasura Courses](https://hasura.io/learn/) for a more detailed
introduction to Hasura.
You can also click the gear icon to manage your Hasura Cloud project.
(e.g. add [collaborators](/graphql/cloud/projects/collaborators.mdx),
[env vars](/graphql/cloud/projects/env-vars.mdx) or
[custom domains](/graphql/cloud/projects/domains.mdx)).
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="Project actions"
width="860px"
/>

View File

@ -0,0 +1,252 @@
---
description: Using Hasura with an AWS RDS Aurora database
keywords:
- hasura
- docs
- existing database
- guide
- aws rds aurora
sidebar_label: AWS RDS Aurora Postgres
sidebar_position: 2
---
import Thumbnail from "@site/src/components/Thumbnail";
# Using Hasura Cloud with an AWS RDS Aurora Postgres database
## Introduction
This guide explains how to connect a new or existing AWS RDS Aurora
Postgres database to a Hasura Cloud project.
## Step 0: Sign up or log in to Hasura Cloud
Navigate to [Hasura Cloud](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=navigate-to-hasura-cloud&tech=default)
and sign up or log in.
## Step 1: Create a Hasura Cloud project {#create-hasura-project-aws-rds-aurora}
On the Hasura Cloud dashboard, create a new project:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/create-hasura-cloud-project.png"
alt="Create Hasura Cloud project"
width="1000px"
/>
After the project is initialized successfully, click on `Launch console`
to open the Hasura console in your browser.
On the Hasura console, navigate to
`Data -> Manage -> Connect Database -> Connect existing database`:
You will get prompted for a Postgres Database URL. We will create this
in the next step and then come back here.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/existing-db-setup.png"
alt="Hasura Cloud database setup"
width="700px"
/>
## Step 2: Create an Aurora DB on AWS RDS (skip if you have an existing DB) {#create-pg-aws-rds-aurora}
Log into the [AWS console](https://console.aws.amazon.com//).
On the top left, click on `Services` and type "RDS" into the search
field. Then click on `RDS`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/search-for-rds.png"
alt="Navigate to RDS in AWS"
width="1000px"
/>
Click on the `Create database` button:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/create-database.png"
alt="Create database in AWS"
width="1000px"
/>
In `Engine options`, select `Amazon Aurora` as `Engine type`. Also,
select `Amazon Aurora with PostgreSQL compatibility` as `Edition`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/aurora/rds-select-aurora.png"
alt="Select Aurora for RDS instance on AWS"
width="600px"
/>
Scroll down to `Settings`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/rds-settings.png"
alt="Settings for RDS instance on AWS"
width="600px"
/>
Now you can choose a `DB instance identifier` as a name for your
database. The `Master username` is `postgres` by default. You can change
that if you have to. As for the password, you can click the checkbox for
AWS to auto-generate one for you, or you can type in a password of your
choice.
Scroll down and customize other database options such as
`DB instance size` and `Storage`, based on your requirements.
In the `Connectivity` section, expand the
`Additional connectivity configuration`. Then set `Public access` to
`Yes` and choose or add a new security group:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/rds-connectivity.png"
alt="Connectivity for RDS instance on AWS"
width="600px"
/>
When you're done, at the bottom, click the `Create database` button:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/rds-click-create.png"
alt="Create RDS instance on AWS"
width="700px"
/>
:::info Note
If you're using a database user other than the default one, make sure to
give it the right [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx).
:::
## Step 3: Allow connections to your DB from Hasura Cloud
On the database dashboard, click on `Connectivity & security`. On the
right, click on the security group that you selected or added in
[step 2](#create-pg-aws-rds-aurora).
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/aurora/find-security-group.png"
alt="Find the security group on AWS RDS"
width="1000px"
/>
Click on the security group:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/select-security-group.png"
alt="Click on the security group"
width="1000px"
/>
Click on `Edit inbound rules`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/inbound-rules.png"
alt="Edit inbound rules for AWS RDS database"
width="1000px"
/>
Click on `Add rule`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/add-inbound-rule.png"
alt="Add an inbound rule for AWS RDS database"
width="1000px"
/>
Copy the IP address from the copy icon in the `Hasura Cloud IP` field on
the project's details view on Hasura Cloud.
<Thumbnail
src="/img/graphql/cloud/projects/hasura-cloud-ip.png"
alt="Hasura Cloud IP field"
width="1000px"
/>
Add the Hasura IP address that you copied:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/add-hasura-ip.png"
alt="Add the Hasura IP for AWS RDS database"
width="1000px"
/>
Then click `Save rules`.
## Step 4: Construct the database connection URL {#construct-db-url-aurora}
The structure of the database connection URL looks as follows:
```bash
postgresql://<user-name>:<password>@<public-ip>:<postgres-port>/<db>
```
On the database dashboard, click on `Connectivity & security`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/aurora/get-db-connection-string.png"
alt="Construct the database connection string for AWS RDS"
width="1000px"
/>
- `user-name`: If you have a separate database user the user name will
be their name. If you didn't specify a user, the default user name
is `postgres`.
- `password`: If you have a separate database user, use their
password. Otherwise, use the password that you chose when creating
the database.
- `public-ip`: On the screenshot above, the `Endpoint` is the public
IP.
- `postgres-port`: On the screenshot above you can find it under
`Port`. The default port for Postgres is `5432`.
- `db`: The DB is `postgres` by default unless otherwise specified.
## Step 5: Finish connecting the database
Back on Hasura Console, enter the database URL that we retrieved in
[step 4](#construct-db-url-aurora):
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="Database setup"
width="600px"
/>
Then click `Connect Database`.
:::info Note
For security reasons, it is recommended to set database URLs as
[env vars](/graphql/cloud/projects/env-vars.mdx) and using the env vars to connect
to the databases in place of the raw database URLs.
:::
Voilà. You are ready to start developing.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/hasura-console.png"
alt="Hasura console"
width="1100px"
/>
## Next steps
You can check out our [30-Minute Hasura Basics
Course](https://hasura.io/learn/graphql/hasura/introduction/) and other
[GraphQL & Hasura Courses](https://hasura.io/learn/) for a more detailed
introduction to Hasura.
You can also click the gear icon to manage your Hasura Cloud project.
(e.g. add [collaborators](/graphql/cloud/projects/collaborators.mdx),
[env vars](/graphql/cloud/projects/env-vars.mdx) or
[custom domains](/graphql/cloud/projects/domains.mdx)).
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="Project actions"
width="860px"
/>

View File

@ -0,0 +1,249 @@
---
description: Using Hasura with an AWS RDS Postgres database
keywords:
- hasura
- docs
- existing database
- guide
- aws rds postgres
sidebar_label: AWS RDS Postgres
sidebar_position: 3
---
import Thumbnail from "@site/src/components/Thumbnail";
# Using Hasura Cloud with an AWS RDS Postgres database
## Introduction
This guide explains how to connect a new or existing AWS RDS Postgres
database to a Hasura Cloud project.
## Step 0: Sign up or log in to Hasura Cloud
Navigate to [Hasura Cloud](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=navigate-to-hasura-cloud&tech=default)
and sign up or log in.
## Step 1: Create a Hasura Cloud project {#create-hasura-project-aws-rds-postgres}
On the Hasura Cloud dashboard, create a new project:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/create-hasura-cloud-project.png"
alt="Create Hasura Cloud project"
width="1000px"
/>
After the project is initialized successfully, click on `Launch console`
to open the Hasura console in your browser.
On the Hasura console, navigate to
`Data -> Manage -> Connect Database -> Connect existing database`:
You will get prompted for a Postgres Database URL. We will create this
in the next step and then come back here.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/existing-db-setup.png"
alt="Hasura Cloud database setup"
width="700px"
/>
## Step 2: Create a Postgres DB on AWS (skip if you have an existing DB) {#create-aws-rds-postgres-db}
Log into the [AWS console](https://console.aws.amazon.com//).
On the top left, click on `Services` and type "RDS" into the search
field. Then click on `RDS`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/search-for-rds.png"
alt="Navigate to RDS in AWS"
width="1000px"
/>
Click the `Create database` button:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/create-database.png"
alt="Create database in AWS"
width="1000px"
/>
In `Engine options`, select `Postgres` as `Engine type`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/postgres/rds-select-postgres.png"
alt="Select Postgres for RDS instance on AWS"
width="600px"
/>
Scroll down to `Settings`. Now you can choose a `DB instance identifier`
as a name for your database. The `Master username` is `postgres` by
default. You can change that if you have to. As for the password, you
can click the checkbox for AWS to auto-generate one for you, or you can
type in a password of your choice.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/rds-settings.png"
alt="Settings for RDS instance on AWS"
width="600px"
/>
Scroll down and customize other database options such as
`DB instance size` and `Storage`, based on your requirements.
In the `Connectivity` section, expand the
`Additional connectivity configuration`. Then set `Public access` to
`Yes` and choose or add a new security group:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/rds-connectivity.png"
alt="Connectivity for RDS instance on AWS"
width="600px"
/>
When you're done, at the bottom, click the `Create database` button:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/rds-click-create.png"
alt="Create RDS instance on AWS"
width="700px"
/>
:::info Note
If you're using a database user other than the default one, make sure to
give it the right [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx).
:::
## Step 3: Allow connections to your DB from Hasura Cloud
On the database dashboard, click on `Connectivity & security`. On the
right, click on the security group that you selected or added in
[step 2](/graphql/cloud/getting-started/cloud-databases/aws-postgres.mdx#create-aws-rds-postgres-db).
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/postgres/find-security-group.png"
alt="Find the security group on AWS RDS"
width="1000px"
/>
Click on the security group:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/select-security-group.png"
alt="Click on the security group"
width="1000px"
/>
Click on `Edit inbound rules`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/inbound-rules.png"
alt="Edit inbound rules for AWS RDS database"
width="1000px"
/>
Click on `Add rule`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/add-inbound-rule.png"
alt="Add an inbound rule for AWS RDS database"
width="1000px"
/>
Copy the IP address from the copy icon in the `Hasura Cloud IP` field on
the project's details view on Hasura Cloud.
<Thumbnail
src="/img/graphql/cloud/projects/hasura-cloud-ip.png"
alt="Hasura Cloud IP field"
width="1000px"
/>
Add the Hasura IP address that you copied:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/add-hasura-ip.png"
alt="Add the Hasura IP for AWS RDS database"
width="1000px"
/>
Then click `Save rules`.
## Step 4: Construct the database connection URL {#construct-db-url-aws-postgres}
The structure of the database connection URL looks as follows:
```bash
postgresql://<user-name>:<password>@<public-ip>:<postgres-port>/<db>
```
On the database dashboard, click on `Connectivity & security`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/aws/postgres/get-db-connection-string.png"
alt="Construct the database connection string for AWS RDS"
width="1000px"
/>
- `user-name`: If you have a separate database user the user name will
be their name. If you didn't specify a user, the default user name
is `postgres`.
- `password`: If you have a separate database user, use their
password. Otherwise, use the password that you chose when creating
the database.
- `public-ip`: On the screenshot above, the `Endpoint` is the public
IP.
- `postgres-port`: On the screenshot above you can find it under
`Port`. The default port for Postgres is `5432`.
- `db`: The DB is `postgres` by default unless otherwise specified.
## Step 5: Finish connecting the database
Back on Hasura Console, enter the database URL that we retrieved in
[step 4](/graphql/cloud/getting-started/cloud-databases/aws-postgres.mdx#construct-db-url-aws-postgres):
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="Database setup"
width="600px"
/>
Then click `Connect Database`.
:::info Note
For security reasons, it is recommended to set database URLs as
[env vars](/graphql/cloud/projects/env-vars.mdx) and using the env vars to connect
to the databases in place of the raw database URLs.
:::
Voilà. You are ready to start developing.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/hasura-console.png"
alt="Hasura console"
width="1100px"
/>
## Next steps
You can check out our [30-Minute Hasura Basics
Course](https://hasura.io/learn/graphql/hasura/introduction/) and other
[GraphQL & Hasura Courses](https://hasura.io/learn/) for a more detailed
introduction to Hasura.
You can also click the gear icon to manage your Hasura Cloud project.
(e.g. add [collaborators](/graphql/cloud/projects/collaborators.mdx),
[env vars](/graphql/cloud/projects/env-vars.mdx) or
[custom domains](/graphql/cloud/projects/domains.mdx)).
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="Project actions"
width="860px"
/>

View File

@ -0,0 +1,202 @@
---
description: Using Hasura with an Azure Postgres database
keywords:
- hasura
- docs
- existing database
- guide
- azure
sidebar_label: Azure Postgres
sidebar_position: 4
---
import Thumbnail from '@site/src/components/Thumbnail';
# Using Hasura Cloud with an Azure Postgres database
## Introduction
This guide explains how to connect a new or existing Azure Postgres
database to a Hasura Cloud project.
## Step 0: Sign up or log in to Hasura Cloud
Navigate to [Hasura Cloud](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=navigate-to-hasura-cloud&tech=default)
and sign up or log in.
## Step 1: Create a Hasura Cloud project {#create-hasura-project-azure}
On the Hasura Cloud dashboard, create a new project:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/create-hasura-cloud-project.png"
alt="Create Hasura Cloud project"
width="1000px"
/>
After the project is initialized successfully, click on `Launch console`
to open the Hasura console in your browser.
On the Hasura console, navigate to
`Data -> Manage -> Connect Database -> Connect existing database`:
You will get prompted for a Postgres Database URL. We will create this
in the next step and then come back here.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/existing-db-setup.png"
alt="Hasura Cloud database setup"
width="700px"
/>
## Step 2: Create a Postgres DB on Azure (skip if you have an existing DB)
Log into the [Azure portal](https://portal.azure.com).
On the Azure portal, type "postgres" in the search window and choose
`Azure Database for PostgreSQL servers`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/azure/select-postgres-db.png"
alt="Select Postgres database on Azure"
/>
Click the `+ Add` button to create a new Postgres database:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/azure/add-postgres-db.png"
alt="Add Postgres database on Azure"
/>
Choose the plan that fits your requirements. For this tutorial, we'll
choose `Single server`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/azure/pg-single-server.png"
alt="Select single server on Azure"
width="600px"
/>
Configure your database with all required fields:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/azure/configure-db.png"
alt="Configure database on Azure"
width="600px"
/>
Then click `Review + create`.
:::info Note
If you're using a database user other than the default one, make sure to
give it the right [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx#cloud-postgres-permissions).
:::
:::info Note
For Azure flexible server, Hasura v1.x does not work with
[JIT](https://www.postgresql.org/docs/11/runtime-config-query.html#GUC-JIT)
turned on. JIT can be turned off from Azure console. Hasura v2.x works
fine with JIT enabled.
:::
## Step 3: Allow connections to your DB from Hasura Cloud
On the database dashboard, click on `Connection security` under
`Settings` on the left navigation bar.
On `Allow access to Azure services`, click the `Yes` button. Then add a
Firewall rule for Hasura.
Copy the IP address from the copy icon in the `Hasura Cloud IP` field on
the project's details view on Hasura Cloud.
<Thumbnail
src="/img/graphql/cloud/projects/hasura-cloud-ip.png"
alt="Hasura Cloud IP field"
/>
Add the Hasura IP address that you copied:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/azure/add-hasura-ip.png"
alt="Add Hasura IP on Azure"
/>
Then click `Save` on the top left.
## Step 4: Construct the database connection URL {#get-db-url-azure}
The structure of the database connection URL looks as follows:
```bash
postgresql://<user-name>:<password>@<public-ip>:<postgres-port>/<db>
```
On the database dashboard, click on `Overview`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/azure/get-database-connection-string.png"
alt="Construct the database connection string for Azure"
/>
- `user-name`: If you have a separate database user, the user name
will be their name. If you didn't specify a user, use the
`Admin username` (see screenshot above). **Note:** you need to
escape the `@`. Replace it with `%40`.
- `password`: If you have a separate database user, use their
password. Otherwise, use the password that you chose when creating
the database.
- `public-ip`: On the screenshot above, the `Server name` is the
public IP.
- `postgres-port`: The default port for Postgres is `5432`.
- `db`: The DB is `postgres` by default unless otherwise specified.
## Step 5: Finish connecting the database
Back on Hasura Console, enter the database URL that we retrieved in
[step 4](#get-db-url-azure):
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="Database setup"
width="600px"
/>
Then click `Connect Database`.
:::info Note
For security reasons, it is recommended to set database URLs as
[env vars](/graphql/cloud/projects/env-vars.mdx#manage-project-env-vars) and using the env vars to connect
to the databases in place of the raw database URLs.
:::
Voilà. You are ready to start developing.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/hasura-console.png"
alt="Hasura console"
/>
## Next steps
You can check out our [30-Minute Hasura Basics
Course](https://hasura.io/learn/graphql/hasura/introduction/) and other
[GraphQL & Hasura Courses](https://hasura.io/learn/) for a more detailed
introduction to Hasura.
You can also click the gear icon to manage your Hasura Cloud project.
(e.g. add [collaborators](/graphql/cloud/projects/collaborators.mdx#manage-project-collaborators),
[env vars](/graphql/cloud/projects/env-vars.mdx#manage-project-env-vars) or
[custom domains](/graphql/cloud/projects/domains.mdx#manage-project-domains)).
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="Project actions"
width="860px"
/>

View File

@ -0,0 +1,186 @@
---
description: Using Hasura with a DO Postgres database
keywords:
- hasura
- docs
- existing database
- guide
- digital ocean
sidebar_label: Digital Ocean Postgres
sidebar_position: 5
---
import Thumbnail from '@site/src/components/Thumbnail';
# Using Hasura Cloud with a Digital Ocean Postgres database
## Introduction
This guide explains how to connect a new or existing Digital Ocean
Postgres database to a Hasura Cloud project.
## Step 0: Sign up or log in to Hasura Cloud
Navigate to [Hasura Cloud](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=navigate-to-hasura-cloud&tech=default)
and sign up or log in.
## Step 1: Create a Hasura Cloud project {#create-hasura-project-do}
On the Hasura Cloud dashboard, create a new project:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/create-hasura-cloud-project.png"
alt="Create Hasura Cloud project"
/>
After the project is initialized successfully, click on `Launch console`
to open the Hasura console in your browser.
On the Hasura console, navigate to
`Data -> Manage -> Connect Database -> Connect existing database`:
You will get prompted for a Postgres Database URL. We will create this
in the next step and then come back here.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/existing-db-setup.png"
alt="Hasura Cloud database setup"
width="700px"
/>
## Step 2: Create a Postgres DB on Digital Ocean (skip if you have an existing DB)
Log into [Digital Ocean](https://cloud.digitalocean.com/).
On the top right, click the `Create` button. Then click on `Databases`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/do/create-database.png"
alt="Create database on Digital Ocean"
/>
Scroll down and choose a `Cluster configuration`, as well as a
`Datacenter` based on your requirements.
Scroll to the bottom and choose a unique database cluster name. Also,
select a project the new database will be associated with.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/do/cluster-name.png"
alt="Select cluster name for database on Digital Ocean"
/>
Then click `Create a Database Cluster`.
## Step 3: Allow connections to your DB from Hasura Cloud
Navigate to the database cluster's `Overview` page:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/do/db-settings.png"
alt="Navigate to database settings in Digital Ocean"
/>
Scroll down to `Trusted sources` and click the `Edit` button:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/do/edit-trusted-sources.png"
alt="Edit trusted sources for database in Digital Ocean"
/>
Copy the IP address from the copy icon in the `Hasura Cloud IP` field on
the project's details view on Hasura Cloud.
<Thumbnail
src="/img/graphql/cloud/projects/hasura-cloud-ip.png"
alt="Hasura Cloud IP field"
/>
Enter the Hasura IP address that you copied:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/do/add-hasura-ip.png"
alt="Add Hasura IP to database in Digital Ocean"
width="700px"
/>
Then click `Save`.
:::info Note
If you're using a database user other than the default one, make sure to
give it the right [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx#cloud-postgres-permissions).
:::
## Step 4: Get the database connection URL {#get-db-url-do}
The structure of the database connection URL looks as follows:
```bash
postgresql://<user-name>:<password>@<public-ip>:<postgres-port>/<db>
```
To get it, navigate to the database cluster's `Overview` page:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/do/db-overview.png"
alt="Navigate to database overview in Digital Ocean"
/>
Scroll down to `Connection details`. Select `Public network` on the left
and `Connection string` on the right.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/do/connection-string.png"
alt="Get the database connection string in Digital Ocean"
width="600px"
/>
Then click the `Copy` button for the next step.
## Step 5: Finish connecting the database
Back on Hasura Console, enter the database URL that we retrieved in
[step 4](#get-db-url-do):
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="Getting Started"
width="600px"
/>
Then click `Connect Database`.
:::info Note
For security reasons, it is recommended to set database URLs as
[env vars](/graphql/cloud/projects/env-vars.mdx#manage-project-env-vars) and using the env vars to connect
to the databases in place of the raw database URLs.
:::
Voilà. You are ready to start developing.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/hasura-console.png"
alt="Hasura console"
/>
## Next steps
You can check out our [30-Minute Hasura Basics
Course](https://hasura.io/learn/graphql/hasura/introduction/) and other
[GraphQL & Hasura Courses](https://hasura.io/learn/) for a more detailed
introduction to Hasura.
You can also click the gear icon to manage your Hasura Cloud project.
(e.g. add [collaborators](/graphql/cloud/projects/collaborators.mdx#manage-project-collaborators),
[env vars](/graphql/cloud/projects/env-vars.mdx#manage-project-env-vars) or
[custom domains](/graphql/cloud/projects/domains.mdx#manage-project-domains)).
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="Project actions"
width="860px"
/>

View File

@ -0,0 +1,183 @@
---
sidebar_label: GCP Postgres
description: Using Hasura with a GCP Postgres database
keywords:
- hasura
- docs
- existing database
- guide
- gcp
sidebar_position: 6
---
import Thumbnail from "@site/src/components/Thumbnail";
# Using Hasura Cloud with a GCP Postgres database
## Introduction
This guide explains how to connect a new or existing GCP Postgres database to a Hasura Cloud project.
## Step 0: Sign up or log in to Hasura Cloud
Navigate to [Hasura Cloud](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=navigate-to-hasura-cloud&tech=default)
and sign up or log in.
## Step 1: Create a Hasura Cloud project {#create-hasura-project-gcp}
On the Hasura Cloud dashboard, create a new project:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/create-hasura-cloud-project.png"
alt="Create Hasura Cloud project"
width="1000px"
/>
After the project is initialized successfully, click on `Launch console` to open the Hasura console in your browser.
On the Hasura console, navigate to `Data -> Manage -> Connect Database -> Connect existing database`:
You will get prompted for a Postgres Database URL. We will create this in the next step and then come back here.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/existing-db-setup.png"
alt="Hasura Cloud database setup"
width="700px"
/>
## Step 2: Create a Postgres DB on GCP (skip if you have an existing DB) {#create-pg-db-gcp}
Log into the [GCP console](https://console.cloud.google.com/).
On the left-side navigation, scroll down to `Storage` and click on `SQL`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/gcp/navigate-to-sql.png"
alt="Navigate to SQL in GCP"
width="250px"
/>
On the top, click on `Create instance`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/gcp/create-instance.png"
alt="Create database instance in GCP"
width="1000px"
/>
Select Postgres:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/gcp/select-postgres.png"
alt="Select Postgres database instance in GCP"
width="1000px"
/>
Select an instance ID, as well as a default user password. If required,
choose a specific region and zone.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/gcp/configure-instance.png"
alt="Configure database instance in GCP"
width="500px"
/>
Then click `Create`.
## Step 3: Allow connections to your DB from Hasura Cloud
On the dashboard of your GCP database instance, on the left sidebar,
click on `Connections`. Then scroll down to the checkbox `Public IP`,
and click `+ Add network`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/gcp/connections.png"
alt="Navigate to connections in GCP"
width="600px"
/>
You can choose an optional name (e.g. "Hasura").
Copy the IP address from the copy icon in the `Hasura Cloud IP` field on the project's details view on Hasura Cloud.
<Thumbnail
src="/img/graphql/cloud/projects/hasura-cloud-ip.png"
alt="Hasura Cloud IP field"
width="1000px"
/>
Enter the Hasura IP address that you copied:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/gcp/add-network.png"
alt="Add a new network in GCP"
width="600px"
/>
Then click `Save`.
:::info Note
If you're using a database user other than the default one, make sure to give it the right [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx).
:::
## Step 4: Construct the database connection URL {#construct-db-url-gcp}
The structure of the database connection URL looks as follows:
```bash
postgresql://<user-name>:<password>@<public-ip>:<postgres-port>/<db>
```
- `user-name`: If you have a separate database user, the user name will be their name. If you didn't specify a user, the default user name is `postgres`.
- `password`: If you have a separate database user, use their password. Otherwise, use the password that you chose when creating the database.
- `public-ip`: The public IP can be optained by clicking on `Overview` on the left-side navigation and then scrolling down to `Connect to this instance`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/gcp/public-ip.png"
alt="Find the public IP for a GCP Postgres database"
width="700px"
/>
- `postgres-port`: The default port for Postgres is `5432` if not specified otherwise.
- `db`: The DB is `postgres` by default unless otherwise specified.
## Step 5: Finish connecting the database
Back on Hasura Console, enter the database URL that we retrieved in [step 4](#construct-db-url-gcp):
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="Database setup"
width="600px"
/>
Then click `Connect Database`.
:::info Note
For security reasons, it is recommended to set database URLs as [env vars](/graphql/cloud/projects/env-vars.mdx) and using the env vars to connect to the databases in place of the raw database URLs.
:::
Voilà. You are ready to start developing.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/hasura-console.png"
alt="Hasura console"
width="1100px"
/>
## Next steps
You can check out our [30-Minute Hasura Basics Course](https://hasura.io/learn/graphql/hasura/introduction/) and other [GraphQL & Hasura Courses](https://hasura.io/learn/) for a more detailed introduction to Hasura.
You can also click the gear icon to manage your Hasura Cloud project. (e.g. add [collaborators](/graphql/cloud/projects/collaborators.mdx),
[env vars](/graphql/cloud/projects/env-vars.mdx) or [custom domains](/graphql/cloud/projects/domains.mdx)).
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="Project actions"
width="860px"
/>

View File

@ -0,0 +1,23 @@
---
description: Use an existing database with Hasura Cloud
keywords:
- hasura
- cloud
- docs
- existing database
slug: index
---
# Guides for connecting Hasura Cloud with different cloud databases
Check out the following guides for tutorials on how to use Hasura Cloud
with a new or existing database provided by specific cloud vendors.
- [Aiven Postgres](/graphql/cloud/getting-started/cloud-databases/aiven.mdx)
- [AWS RDS Aurora Postgres](/graphql/cloud/getting-started/cloud-databases/aws-aurora.mdx)
- [AWS RDS Postgres](/graphql/cloud/getting-started/cloud-databases/aws-postgres.mdx)
- [Azure Postgres](/graphql/cloud/getting-started/cloud-databases/azure.mdx)
- [Digital Ocean Postgres](/graphql/cloud/getting-started/cloud-databases/digital-ocean.mdx)
- [GCP Postgres](/graphql/cloud/getting-started/cloud-databases/gcp.mdx)
- [TimescaleDB Cloud](/graphql/cloud/getting-started/cloud-databases/timescale-cloud.mdx)
- [YugabyteDB](/graphql/cloud/getting-started/cloud-databases/yugabyte.mdx)

View File

@ -0,0 +1,173 @@
---
sidebar_label: TimescaleDB Cloud
description: Using Hasura with a Timescale Postgres database
keywords:
- hasura
- docs
- existing database
- guide
- timescale
sidebar_position: 7
---
import Thumbnail from "@site/src/components/Thumbnail";
# Using Hasura Cloud with a Timescale Postgres database
## Introduction
This guide explains how to connect a new or existing Timescale Postgres
database to a Hasura Cloud project.
## Step 0: Sign up or log in to Hasura Cloud
Navigate to [Hasura Cloud](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=navigate-to-hasura-cloud&tech=default) and sign up or log in.
## Step 1: Create a Hasura Cloud project {#create-hasura-project-timescale}
On the Hasura Cloud dashboard, create a new project:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/create-hasura-cloud-project.png"
alt="Create Hasura Cloud project"
width="1000px"
/>
You will get prompted for a Postgres Database URL. We will create this in the next step and then come back here.
After the project is initialized successfully, click on `Launch console` to open the Hasura console in your browser.
On the Hasura console, navigate to `Data -> Manage -> Connect Database -> Connect existing database`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/existing-db-setup.png"
alt="Hasura Cloud database setup"
width="700px"
/>
## Step 2: Create a Postgres DB on Timescale (skip if you have an existing DB) {#create-pg-db-timescale}
Log into the [Timescale Cloud portal](https://portal.timescale.cloud/login).
On the Timescale dashboard, under `Services`, click on `+ Create new service`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/timescale/create-new-service.png"
alt="Create a new service on Timescale"
width="1000px"
/>
Select the Postgres option:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/timescale/select-postgres.png"
alt="Select Postgres on Timescale"
width="700px"
/>
Scroll down and select the `Cloud Provider`, `Region` and `Service Plan` based on your requirements.
In the end, enter a `Name` for the service:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/timescale/create-service.png"
alt="Create a service on Timescale"
width="1000px"
/>
Then click `Create service`.
:::info Note
If you're using a database user other than the default one, make sure to give it the right [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx).
:::
## Step 3: Allow connections to your DB from Hasura Cloud
On the `Services` dashboard, click on your DB:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/timescale/select-db.png"
alt="Select DB on Timescale"
width="1000px"
/>
Scroll down to `Allowed IP Addresses` and click on `Change`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/timescale/change-allowed-ip-addresses.png"
alt="Change allowed IP addresses on Timescale"
width="1000px"
/>
Copy the IP address from the copy icon in the `Hasura Cloud IP` field on the project's details view on Hasura Cloud.
<Thumbnail
src="/img/graphql/cloud/projects/hasura-cloud-ip.png"
alt="Hasura Cloud IP field"
width="1000px"
/>
Add the Hasura IP address that you copied, click on the `+` and then click on `Save changes`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/timescale/add-hasura-ip.png"
alt="Add the Hasura IP on Timescale"
width="500px"
/>
## Step 4: Get the database connection URL {#get-db-url-timescale}
The structure of the database connection URL looks as follows:
```bash
postgresql://<user-name>:<password>@<public-ip>:<postgres-port>/<db>
```
To get it, navigate to the `Overview` tab of your database dashboard and copy the `Service URI`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/timescale/copy-service-uri.png"
alt="Copy the service URI on Timescale"
width="1000px"
/>
## Step 5: Finish connecting the database
Back on Hasura Console, enter the database URL that we retrieved in [step 4](#get-db-url-timescale):
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="Database setup"
width="600px"
/>
Then click `Connect Database`.
:::info Note
For security reasons, it is recommended to set database URLs as [env vars](/graphql/cloud/projects/env-vars.mdx) and using the env vars to connect to the databases in place of the raw database URLs.
:::
Voilà. You are ready to start developing.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/hasura-console.png"
alt="Hasura console"
width="1100px"
/>
## Next steps
You can check out our [30-Minute Hasura Basics Course](https://hasura.io/learn/graphql/hasura/introduction/) and other [GraphQL & Hasura Courses](https://hasura.io/learn/) for a more detailed introduction to Hasura.
You can also click the gear icon to manage your Hasura Cloud project. (e.g. add [collaborators](/graphql/cloud/projects/collaborators.mdx),
[env vars](/graphql/cloud/projects/env-vars.mdx) or [custom domains](/graphql/cloud/projects/domains.mdx)).
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="Project actions"
width="860px"
/>

View File

@ -0,0 +1,143 @@
---
sidebar_label: YugabyteDB
description: Using Hasura with a Yugabyte Postgres database
keywords:
- hasura
- docs
- existing database
- guide
- yugabyte
sidebar_position: 8
---
import Thumbnail from "@site/src/components/Thumbnail";
# Using Hasura Cloud with a Yugabyte Postgres database
## Introduction
This guide explains how to connect a new or existing Yugabyte Postgres database to a Hasura Cloud project.
## Step 0: Sign up or log in to Hasura Cloud
Navigate to [Hasura Cloud](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=navigate-to-hasura-cloud&tech=default) and sign up or log in.
## Step 1: Create a Hasura Cloud project {#create-hasura-project-yugabyte}
On the Hasura Cloud dashboard, create a new project:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/create-hasura-cloud-project.png"
alt="Create Hasura Cloud project"
width="1000px"
/>
You will get prompted for a Postgres Database URL. We will create this in the next step and then come back here.
After the project is initialized successfully, click on `Launch console` to open the Hasura console in your browser.
On the Hasura console, navigate to `Data -> Manage -> Connect Database -> Connect existing database`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/existing-db-setup.png"
alt="Hasura Cloud database setup"
width="700px"
/>
## Step 2: Create a Postgres DB on Yugabyte (skip if you have an existing DB) {#create-pg-db-yugabyte}
Log into the [Yugabyte Cloud dashboard](https://cloud.yugabyte.com/login).
On the Yugabyte Cloud dashboard, click on `Create cluster`:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/yugabyte/create-cluster.png"
alt="Create cluster on Yugabyte"
width="1000px"
/>
Select a `Cloud Provider` and `Region` and then click `Create Cluster`.
:::info Note
If you're using a database user other than the default one, make sure to give it the right [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx).
:::
## Step 3: Construct the database connection URL {#construct-db-url-yugabyte}
The structure of the database connection URL looks as follows:
```bash
postgresql://<user-name>:<password>@<public-ip>:<postgres-port>/<db>
```
To get it, click on your cluster on the cluster dashboard:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/yugabyte/go-to-cluster.png"
alt="Go to cluster on Yugabyte"
width="700px"
/>
On your cluster's dashboard, click on `Connect` on the top right:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/yugabyte/connect.png"
alt="Connect to cluster on Yugabyte"
width="1000px"
/>
Now you can get the connection info from the following screen:
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/yugabyte/connection-info.png"
alt="Connection info for Yugabyte"
width="600px"
/>
- `user-name`: If you have a separate database user, the user name will be their name. If you didn't specify a user, the default user name is `admin` (see after `-U` in the screenshot above).
- `password`: If you have a separate database user, use their password. Otherwise, use the password is what follows `PGPASSWORD=` in the screenshot above.
- `public-ip`: The public IP is what follows `-h` in the screenshot above.
- `postgres-port`: The port is `10301` (see on the screenshot after `-p`). This can be configured if required.
- `db`: The DB is `yugabyte` (see on the screenshot after `-d`).
## Step 4: Finish connecting the database
Back on Hasura Console, enter the database URL that we retrieved in [step 3](#construct-db-url-yugabyte):
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="Database setup"
width="600px"
/>
Then click `Connect Database`.
:::info Note
For security reasons, it is recommended to set database URLs as [env vars](/graphql/cloud/projects/env-vars.mdx) and using the env vars to connect to the databases in place of the raw database URLs.
:::
Voilà. You are ready to start developing.
<Thumbnail
src="/img/graphql/cloud/cloud-dbs/hasura-console.png"
alt="Hasura console"
width="1100px"
/>
## Next steps
You can check out our [30-Minute Hasura Basics Course](https://hasura.io/learn/graphql/hasura/introduction/) and other [GraphQL & Hasura Courses](https://hasura.io/learn/) for a more detailed introduction to Hasura.
You can also click the gear icon to manage your Hasura Cloud project. (e.g. add [collaborators](/graphql/cloud/projects/collaborators.mdx),
[env vars](/graphql/cloud/projects/env-vars.mdx) or [custom domains](/graphql/cloud/projects/domains.mdx)).
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="Project actions"
width="860px"
/>

View File

@ -0,0 +1,190 @@
---
description: Hasura Cloud getting started
keywords:
- hasura
- cloud
- docs
- signup
slug: index
---
import Thumbnail from "@site/src/components/Thumbnail";
# Getting Started with Hasura Cloud
## Introduction
This guide talks about setting up Hasura Cloud with a new or existing
database.
## Step 1: Create an account
Navigate to
[cloud.hasura.io](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=navigate-to-cloud-hasura-io&tech=default),
and create a new Hasura Cloud account.
## Step 2: Create project {#cloud-connect-db}
Hasura Cloud creates an initial project. Click `Launch Console` to open
the Hasura console in your browser.
<Thumbnail
src="/img/graphql/cloud/getting-started/create-project.png"
alt="Connect new or existing database"
width="556px"
/>
## Step 3: Connect new/existing database {#create-new-db-with-cloud}
On the Hasura console, navigate to `Data -> Manage -> Connect Database`:
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db-console.png"
alt="Connect database"
width="1000px"
/>
- To use an existing database, choose `Connect existing database`.
- To try out with a new Postgres database, choose
`Create Heroku Database`.
<Thumbnail
src="/img/graphql/cloud/getting-started/db-setup.png"
alt="DB setup"
width="556px"
/>
### Step 3.1: Enter database connection URL (for existing database)
If you chose `Connect existing database`, enter your database connection
URL.
Click `Connect Database`.
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="Enter URL for existing database"
width="556px"
/>
If your database is hosted via any of the following managed cloud
database services, check out their respective detailed guides to get the
database connection URL and any other steps required to ensure
connectivity from Hasura Cloud:
- [Aiven Postgres](/graphql/cloud/getting-started/cloud-databases/aiven.mdx)
- [AWS RDS Aurora Postgres](/graphql/cloud/getting-started/cloud-databases/aws-aurora.mdx)
- [AWS RDS Postgres](/graphql/cloud/getting-started/cloud-databases/aws-postgres.mdx)
- [Azure Postgres](/graphql/cloud/getting-started/cloud-databases/azure.mdx)
- [Digital Ocean Postgres](/graphql/cloud/getting-started/cloud-databases/digital-ocean.mdx)
- [GCP Postgres](/graphql/cloud/getting-started/cloud-databases/gcp.mdx)
- [TimescaleDB Cloud](/graphql/cloud/getting-started/cloud-databases/timescale-cloud.mdx)
- [YugabyteDB](/graphql/cloud/getting-started/cloud-databases/yugabyte.mdx)
## Step 4: Try out Hasura
### Create a table
On the Hasura console, navigate to `Data -> Create table` and create a
sample table called `profiles` with the following columns:
```sql
profiles (
id SERIAL PRIMARY KEY, -- serial -> auto-incrementing integer
name TEXT
)
```
<Thumbnail
src="/img/graphql/core/getting-started/create-profile-table.png"
alt="Create a table"
/>
Now, insert some sample data into the table using the `Insert Row` tab
of the `profiles` table.
### Try out a query
Head to the `GraphiQL` tab in the console and try running the following
query:
```graphql
query {
profiles {
id
name
}
}
```
You'll see that you get all the inserted data!
<Thumbnail
src="/img/graphql/core/getting-started/profile-query.png"
alt="Try out a query"
/>
### Check out monitoring
You can navigate to the `Monitoring` tab in the console to check out the
extra features for reliability and security that Hasura Cloud has set up
for you.
<Thumbnail
src="/img/graphql/cloud/metrics/monitoring-tab-overview.png"
alt="Hasura Console: Monitoring tab"
/>
## Next steps
### Learn course
For a full hands-on tour of Hasura, check out our [30-Minute Hasura
Basics Course](https://hasura.io/learn/graphql/hasura/introduction/).
### Database operations
- [Database modelling](/graphql/core/databases/postgres/schema/index.mdx): Learn how to model your database
schema, as well as how to extend it.
- [Querying data](/graphql/core/databases/postgres/queries/index.mdx): Use GraphQL queries to query data from
your GraphQL API.
- [Inserting data](/graphql/core/databases/postgres/mutations/index.mdx): Use GraphQL mutations to insert data
into your GraphQL API.
### Business logic
There are several options for the implementation of business logic,
depending on your use case.
- [Actions](/graphql/core/actions/index.mdx): Actions can be used if you'd like to extend
your GraphQL schema by integrating with a REST endpoint.
- [Remote schemas](/graphql/core/remote-schemas/index.mdx): If you have an existing GraphQL
server or if you're comfortable with implementing one, you can use
remote schemas.
- [Event triggers](/graphql/core/event-triggers/index.mdx): To trigger a serverless function
based on a database event, use event triggers.
- [Scheduled triggers](/graphql/core/scheduled-triggers/index.mdx): Scheduled triggers are
used to execute custom business logic at specific points in time.
### Manage Hasura Cloud project
You can click the gear icon in the Hasura Cloud dashboard to manage your
Hasura Cloud project (e.g. add
[collaborators](/graphql/cloud/projects/collaborators.mdx),
[env vars](/graphql/cloud/projects/env-vars.mdx) or
[custom domains](/graphql/cloud/projects/domains.mdx)).
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="Project actions"
width="860px"
/>
:::info Additional Resources
Get Started with Hasura today - [Watch video guide](https://hasura.io/events/webinar/get-started-with-hasura/?pg=docs&plcmt=body&cta=getting-started&tech=).
:::
- [Cloud databases guides](/graphql/cloud/getting-started/cloud-databases/index.mdx)
- [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx)

View File

@ -0,0 +1,115 @@
---
description: Postgres permissions for Hasura Cloud projects
keywords:
- hasura
- cloud
- docs
- deployment
- postgres
- postgres permissions
sidebar_position: 2
---
# Postgres permissions
## Introduction
Hasura works out of the box with the default superuser, usually called
`postgres`, created by most managed cloud database providers.
If you use another database user, you will need to make sure that this
user has the right Postgres permissions.
## Postgres permissions
Here's a sample SQL block that you can run on your database (as a
**superuser**) to create the right credentials for a sample Hasura user
called `hasurauser`:
```sql
-- create a separate user for hasura (if you don't already have one)
CREATE USER hasurauser WITH PASSWORD 'hasurauser';
-- create pgcrypto extension, required for UUID
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- create the schemas required by the hasura cloud system
CREATE SCHEMA IF NOT EXISTS hdb_catalog;
CREATE SCHEMA IF NOT EXISTS hdb_views;
CREATE SCHEMA IF NOT EXISTS hdb_pro_catalog;
-- make the user an owner of the hasura cloud system schemas
ALTER SCHEMA hdb_catalog OWNER TO hasurauser;
ALTER SCHEMA hdb_views OWNER TO hasurauser;
ALTER SCHEMA hdb_pro_catalog OWNER TO hasurauser;
-- grant select permissions on information_schema and pg_catalog
GRANT SELECT ON ALL TABLES IN SCHEMA information_schema TO hasurauser;
GRANT SELECT ON ALL TABLES IN SCHEMA pg_catalog TO hasurauser;
-- grant all privileges on all tables in the public schema (this is optional and can be customized)
GRANT USAGE ON SCHEMA public TO hasurauser;
GRANT ALL ON ALL TABLES IN SCHEMA public TO hasurauser;
GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO hasurauser;
GRANT ALL ON ALL FUNCTIONS IN SCHEMA public TO hasurauser;
-- Similarly add these for other schemas as well, if you have any
-- GRANT USAGE ON SCHEMA <schema-name> TO hasurauser;
-- GRANT ALL ON ALL TABLES IN SCHEMA <schema-name> TO hasurauser;
-- GRANT ALL ON ALL SEQUENCES IN SCHEMA <schema-name> TO hasurauser;
-- GRANT ALL ON ALL FUNCTIONS IN SCHEMA <schema-name> TO hasurauser;
```
You may notice the following commands throw warnings/errors:
```sql
postgres=> GRANT SELECT ON ALL TABLES IN SCHEMA information_schema TO hasurauser;
WARNING: no privileges were granted for "sql_packages"
WARNING: no privileges were granted for "sql_features"
WARNING: no privileges were granted for "sql_implementation_info"
ERROR: permission denied for table sql_parts
postgres=> GRANT SELECT ON ALL TABLES IN SCHEMA pg_catalog TO hasurauser;
ERROR: permission denied for table pg_statistic
```
You can **ignore** these warnings/errors or skip granting these
permission as usually all users have relevant access to
`information_schema` and `pg_catalog` schemas by default (see keyword
[PUBLIC](https://www.postgresql.org/docs/current/sql-grant.html)).
:::info Note
If you first connect Postgres with the default superuser, and afterwards
with another user, you might get an error. You then need to reset the
permissions to the new user.
:::
### Note for GCP
On Google Cloud SQL, if you are creating a new user and giving the
[above](/graphql/core/deployment/postgres-requirements.mdx#postgres-permissions) privileges, then you may notice that the
following commands may throw warnings/errors:
```sql
postgres=> ALTER SCHEMA hdb_catalog OWNER TO hasurauser;
ERROR: must be member of role "hasurauser"
```
This happens because the superuser created by the cloud provider
sometimes has different permissions. To fix this, you can run the
following command first:
```sql
-- assuming "postgres" is the superuser that you are running the commands with.
postgres=> GRANT hasurauser to postgres;
GRANT
postgres=> ALTER SCHEMA hdb_catalog OWNER TO hasurauser;
```
## Further reading
For more information and a more detailed explanation on Postgres
permissions, refer to the
[Hasura core Postgres requirements](/graphql/core/deployment/postgres-requirements.mdx) page.

View File

@ -0,0 +1,35 @@
---
description: Hasura Cloud glossary
keywords:
- hasura
- docs
- cloud
- Glossary
sidebar_position: 16
---
# Glossary
## Hasura Cloud Project
A Project is an individual GraphQL API hosted by Hasura Cloud. You can create a Project by going to the cloud dashboard and then connecting a database from the Hasura console. You can also provision a database on cloud platforms like Heroku from the Hasura console itself.
Each project is allocated a unique auto-generated name and an ID. You can use this name or ID while communicating to Hasura team regarding this project. Each project is also assigned a GraphQL API endpoint of the format `https://<project-name>.hasura.app/v1/graphql`.
For example, a project might be called `usable-cobra-29` with ID `bf0ea856-76a2-42c2-8a91-66ca9b9206e8`.
## Hasura Cloud IP
A Hasura Cloud IP will be listed on the Hasura Cloud Dashboard for each project. Hasura will be connecting to your database from this IP address. If your database is not exposed to the internet, you must allow connections from this IP address on your firewall settings for Hasura Cloud Project to function properly. Otherwise, Hasura will not be able to connect to your database and the GraphQL API will not be available.
## Hasura Collaborator Token
When you open the Hasura Console on a Cloud Project, you will not be asked to enter the admin secret like Hasura Core version. Instead, if you are an admin, the console will be accessible with the admin secret already set, or if you are a collaborator with limited access you will be automatically logged into the Console via an OAuth2.0 based authorization flow. You will be given the right access based on your permissions for the particular Hasura Cloud Project.
After the login process is complete, you'll see a new header called `Hasura-Collaborator-Token` in the "Request Headers" section of GraphiQL. This token is used instead of admin secret to authenticate and authorize all the requests made from the Console. The token is only valid for 5mins and is refreshed silently by the Console. It is to be used only from Console.
For accessing the API from other clients, use the admin secret or create a Personal Access Token.
## Hasura Client Name
`Hasura-Client-Name` will be set to `hasura-console` by default. It is used to identify the client who is making the request in Hasura Pro metrics and monitoring tools.

View File

@ -0,0 +1,67 @@
---
description: Hasura Pro CLI
keywords:
- hasura
- docs
- command line interface
- cli
sidebar_position: 14
# adding to avoid redirect ad this was only index file under the directory
slug: hasurapro-cli/index
---
# Hasura Pro CLI
## Installing the Hasura Pro CLI
Hasura Pro CLI is distributed as a plugin to the [Hasura Core CLI](/graphql/core/hasura-cli/index.mdx)
- Follow the instructions [here](/graphql/core/hasura-cli/install-hasura-cli.mdx) to install Hasura Core CLI
- Then execute the following command to install the Hasura Pro CLI plugin:
```bash
hasura plugins install pro
```
- You can verify the installation by executing the `help` command:
```bash
hasura pro --help
```
## Authentication with the Hasura Pro CLI
All interactions from the CLI to Hasuras APIs are authenticated using a personal access token generated for your user account.
To set up a token, execute the following command on the CLI:
```bash
hasura pro login
```
This command will show a prompt for entering the personal access token.
Head to your [Hasura Cloud account settings](https://cloud.hasura.io) to create a new token. You can name it something like "cli". Note that the token will be shown only once and as soon as you copy the token, paste it in your terminal prompt.
:::info Keep this token secure!
This token can be used to authenticate against Hasura Pro APIs and your Hasura Cloud projects. Make sure you keep it secure. This is a one-time operation. The token will be valid until you delete it.
:::
## Upgrading the CLI
To upgrade to a newer version, you can use the `upgrade` command:
```bash
hasura plugins upgrade pro
```
## Uninstalling the CLI
To uninstall the CLI, use the `uninstall` command:
```bash
hasura plugins uninstall pro
```

View File

@ -0,0 +1,71 @@
---
title: Hasura Cloud Documentation
description: Hasura Cloud documentation
keywords:
- hasura
- docs
- manual
- graphql engine
- cloud
- hosted
slug: index
sidebar_label: Index
sidebar_position: 0
---
import Link from "@docusaurus/Link";
import VersionedLink from "@site/src/components/VersionedLink";
import {
CustomTOCList,
CustomTOCListSection,
CustomTOCListHead,
CustomTOCListContent,
} from "@site/src/components/CustomTOCList";
# Hasura Cloud Documentation
[Hasura Cloud](https://cloud.hasura.io/signup/?pg=docs&plcmt=body&cta=hasura-cloud&tech=default) offers hosted [GraphQL Engine](https://github.com/hasura/graphql-engine) projects with extra features for reliability and security. It includes all the [core features](/graphql/core/index.mdx) of GraphQL Engine, while taking care of infrastructure concerns, such as the number of instances, cores, memory, concurrent users, high-availability, realtime monitoring, caching, tracing, and rate-limiting. It supports both new and existing databases.
<CustomTOCList>
<CustomTOCListSection>
<CustomTOCListHead>Basics</CustomTOCListHead>
<CustomTOCListContent>
<VersionedLink to="/graphql/cloud/getting-started/index">
Getting Started with Hasura Cloud
</VersionedLink>
<VersionedLink to="/graphql/cloud/projects/create">Creating projects</VersionedLink>
<VersionedLink to="/graphql/cloud/projects/collaborators">
Project Collaborators
</VersionedLink>
<VersionedLink to="/graphql/cloud/projects/env-vars">Project Env vars</VersionedLink>
<VersionedLink to="/graphql/cloud/projects/domains">Project Domains</VersionedLink>
</CustomTOCListContent>
</CustomTOCListSection>
<CustomTOCListSection>
<CustomTOCListHead>FEATURES</CustomTOCListHead>
<CustomTOCListContent>
<VersionedLink to="/graphql/cloud/metrics/index">Metrics</VersionedLink>
<VersionedLink to="/graphql/cloud/regression-tests">Regression tests</VersionedLink>
<VersionedLink to="/graphql/cloud/read-replicas">Read replicas</VersionedLink>
<VersionedLink to="/graphql/cloud/response-caching">Query response caching</VersionedLink>
<VersionedLink to="/graphql/cloud/tracing">Distributed tracing</VersionedLink>
<VersionedLink to="/graphql/cloud/query-tags">Query Tags</VersionedLink>
<VersionedLink to="/graphql/cloud/dedicated-vpc">Dedicated VPC</VersionedLink>
</CustomTOCListContent>
</CustomTOCListSection>
<CustomTOCListSection>
<CustomTOCListHead>API SECURITY</CustomTOCListHead>
<CustomTOCListContent>
<VersionedLink to="/graphql/cloud/security/api-limits">API limits</VersionedLink>
<VersionedLink to="/graphql/cloud/security/allow-lists">Allow lists</VersionedLink>
</CustomTOCListContent>
</CustomTOCListSection>
<CustomTOCListSection>
<CustomTOCListHead>REFERENCE</CustomTOCListHead>
<CustomTOCListContent>
<VersionedLink to="/graphql/cloud/api-reference">API Reference</VersionedLink>
<VersionedLink to="/graphql/cloud/glossary">Glossary</VersionedLink>
<VersionedLink to="/graphql/cloud/hasurapro-cli/index">Hasura Pro CLI</VersionedLink>
</CustomTOCListContent>
</CustomTOCListSection>
</CustomTOCList>

View File

@ -0,0 +1,4 @@
{
"label": "Metrics",
"position": 3
}

View File

@ -0,0 +1,28 @@
---
sidebar_position: 3
description: Hasura Cloud error analysis
keywords:
- hasura
- docs
- cloud
- reliability
- errors
---
import Thumbnail from "@site/src/components/Thumbnail";
# Errors
Troubleshoot errors quickly with powerful analytical tools and filters:
<Thumbnail
src="/img/graphql/cloud/metrics/pro-tab-errors.png"
alt="Hasura Cloud Console errors tab"
/>
Drill into a specific operation via the magnifying-glass icon next to the operation summary in the 'Frequent errors' table. You'll be taken to a list of the failed operations, and can choose one to inspect the specific operation content, metadata, and error generated:
<Thumbnail
src="/img/graphql/cloud/metrics/inspect-error.png"
alt="Hasura Cloud Console inspect a failed operation"
/>

View File

@ -0,0 +1,32 @@
---
sidebar_label: Metrics
sidebar_position: 1
slug: index
description: Hasura Cloud metrics
keywords:
- hasura
- docs
- cloud
- metrics
---
import Thumbnail from "@site/src/components/Thumbnail";
# Metrics
Hasura Cloud projects include Pro features for enhanced reliability and performance
<Thumbnail
src="/img/graphql/cloud/metrics/monitoring-tab-overview.png"
alt="Hasura Cloud Console overview tab"
/>
## Features
- [Overview](/graphql/cloud/metrics/overview.mdx)
- [Errors](/graphql/cloud/metrics/errors.mdx)
- [Usage](/graphql/cloud/metrics/usage.mdx)
- [Operations](/graphql/cloud/metrics/operations.mdx)
- [Websockets](/graphql/cloud/metrics/websockets.mdx)
- [Subscription-workers](/graphql/cloud/metrics/subscription-workers.mdx)
- [Integrations](/graphql/cloud/metrics/integrations/index.mdx)

View File

@ -0,0 +1,3 @@
{
"label": "Integrations"
}

View File

@ -0,0 +1,158 @@
---
sidebar_position: 3
description: Azure monitor Integration on Hasura Cloud
keywords:
- hasura
- docs
- metrics
- integration
- export logs
- azure monitor
sidebar_label: Azure Monitor
---
import Thumbnail from "@site/src/components/Thumbnail";
# Azure Monitor Integration
## Introduction
You can export metrics and operation logs of your Hasura Cloud project to [Azure Monitor](https://azure.microsoft.com/en-in/services/monitor/). This can be configured on the integrations tab on the project's setting page.
:::info Note
Azure monitor Integration is only available for Hasura Cloud projects on the `Standard` (pay-as-you-go) tier and above.
:::
## Pre-requisites
- Create a [Service Principal](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#register-an-application-with-azure-ad-and-create-a-service-principal) in Azure.
- From the `Overview` tab of the created Service principal, retrieve `Application (client) ID` (Referred as `Active Directory Client ID` in this context) and `Directory (tenant) ID` (Referred as `Active Directory Tenant ID` in this context)
<Thumbnail
src="/img/graphql/cloud/metrics/service-principal-properties.png"
alt="Service Principal Properties"
width="1146px"
/>
- From the `Certificates & secrets` tab of the created service principal, Create a client secret by clicking `New client secret`. Add a suitable description and expiry period for the secret and click `Add`. Copy the value of the created secret (Referred to as `Active Directory Client Secret` in this context)
<Thumbnail
src="/img/graphql/cloud/metrics/service-principal-secret.png"
alt="Service Principal Secret"
width="1146px"
/>
- Create a [Log Analytics Workspace](https://docs.microsoft.com/en-us/azure/azure-monitor/logs/quick-create-workspace) in Azure.
- From the `Agents management` tab of the created log analytics workspace, retrieve `Workspace ID` and `Primary Key` (Referred as `Shared Key` in this context).
<Thumbnail
src="/img/graphql/cloud/metrics/log-analytics-workspace-config.png"
alt="Log Analytics workspace config parameters"
width="1146px"
/>
- From the `Properties` tab of the created log analytics workspace, retrieve `Resource ID` and `Location` (Referred to as `Region` in this context)
<Thumbnail
src="/img/graphql/cloud/metrics/log-analytics-properties.png"
alt="Log Analytics Properties"
width="1146px"
/>
- Assign the Role `Monitoring Metrics Publisher` to the Service principal against the Log analytics workspace. From the `Access control (IAM)` tab of the created log analytics workspace, Click on `Add` and select `Add role assignment`. In the Add role assignment panel, Select the Role as `Monitoring Metrics Publisher` and select the created service principal for role assignment and click `Save`.
<Thumbnail
src="/img/graphql/cloud/metrics/service-principal-role.png"
alt="Service Principal Role"
width="1146px"
/>
## Configure Azure Monitor integration
On the Project settings page, navigate to **Integrations > Azure Monitor**.
<Thumbnail
src="/img/graphql/cloud/metrics/integrate-azure-monitor.png"
alt="Configure Azure Monitor Integration"
width="1146px"
/>
Enter the values of config parameters obtained from the steps in pre-requisites in the Azure monitor integration form. In addition to the above parameters, the following fields are also needed:
| Field | Description |
|----------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [Namespace](https://docs.microsoft.com/en-us/azure/azure-monitor/essentials/metrics-custom-overview#namespace) | Namespaces are a way to categorize or group similar metrics together. |
| [Log type](https://docs.microsoft.com/en-us/azure/azure-monitor/logs/data-collector-api#request-headers) | The record type of the log that is being submitted. It can contain only letters, numbers, and the underscore (\_) character, and it can't exceed 100 characters. |
| Custom Attributes **(Optional)** | Custom Attributes associated with your logs. A default source tag `hasura-logs` is added to all exported logs. |
After adding appropriate values in the Azure monitor Integration panel, click `Save`.
## Checking the status of the integration
The green/red dot signifies the status of the integration. Green signifies successful exporting of logs to Azure monitor. When logs are successfully exported, `Last Exported` is continuously updated, indicating the timestamp of the last log line successfully exported to your Azure monitor dashboard.
<Thumbnail
src="/img/graphql/cloud/metrics/configure-azure-monitor-done.png"
alt="Azure monitor Integration successfully configured"
width="1146px"
/>
In case there is an error while exporting logs to Azure monitor, the dot is red and the HTTP status code of the error and the message is displayed right below it.
<Thumbnail
src="/img/graphql/cloud/metrics/configure-azure-monitor-fail.png"
alt="Azure monitor Integration unable to push logs"
width="1146px"
/>
## View metrics
The integration exports the following five metrics to Azure monitor:
| Metric Exported | Metric Name in Azure monitor |
|--------------------------------|-------------------------------|
| Average number of requests | `average_requests_per_minute` |
| Average request execution time | `average_execution_time` |
| Success rate of requests | `success_rate` |
| Active subscriptions | `active_subscriptions` |
| Number of websockets open | `websockets_open` |
Non-zero values of all the above metrics are exported over a minute time interval.
To navigate to [Azure monitor metrics dashboard](https://portal.azure.com/#blade/Microsoft_Azure_Monitoring/AzureMonitoringBrowseBlade/metrics) ,click `View Metrics`.
<Thumbnail
src="/img/graphql/cloud/metrics/azure-monitor-view-metrics.png"
alt="Azure monitor Integration successfully configured"
width="1146px"
/>
From the `Select a scope` panel, expand the resource group which contains the `Log analytics workspace` and select it and click `Apply`. In the filter menu, select the correct namespace and `Add filter` to view the individual metric.
<Thumbnail
src="/img/graphql/cloud/metrics/azure-monitor-metrics.png"
alt="Metrics successfully exported to Azure monitor"
width="1146px"
/>
## View logs
To navigate to [Azure monitor logs dashboard](https://portal.azure.com/#blade/Microsoft_Azure_Monitoring/AzureMonitoringBrowseBlade/logs), click `View Logs`.
<Thumbnail
src="/img/graphql/cloud/metrics/azure-monitor-view-logs.png"
alt="Azure monitor Integration successfully configured"
width="1146px"
/>
From the `Select a scope` panel, expand the resource group which contains the `Log analytics workspace` and select it and click `Apply`. The logs can be filtered using `Log type`. Use `{YOUR_LOG_TYPE}_CL` search parameter to filter the logs. Custom log types are displayed in the left of the Query panel.
<Thumbnail
src="/img/graphql/cloud/metrics/azure-monitor-logs.png"
alt="Logs successfully exported to Azure monitor"
width="1146px"
/>

View File

@ -0,0 +1,125 @@
---
sidebar_label: Datadog
sidebar_position: 2
description: Datadog Integration on Hasura Cloud
keywords:
- hasura
- docs
- metrics
- integration
- export logs
- datadog
---
import Thumbnail from "@site/src/components/Thumbnail";
# Datadog Integration
## Introduction
You can export metrics and operation logs of your Hasura Cloud project to your organisation's Datadog dashboard. This can be configured on the integrations tab on the project's setting page.
:::info Note
Datadog Integration is only available for Hasura Cloud projects on the `Standard` (pay-as-you-go) tier and above.
:::
## Configure Datadog integration
Navigate to the integrations tab on project settings page to find Datadog integration.
<Thumbnail
src="/img/graphql/cloud/metrics/integrate-datadog.png"
alt="Configure Datadog Integration"
width="1146px"
/>
Select the Datadog API region and enter the Datadog API key (can be retrieved by navigating to Datadog's settings page by clicking the `Get API Key` link), host, service name and tags to associate with exported logs and metrics.
| Field | Description |
|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Region | If you are in the Datadog EU site (app.datadoghq.eu), the Region should be EU; otherwise, it should be US. |
| API Key | API keys are unique to your organization. An API key is required by the Datadog Agent to submit metrics and events to Datadog. You can get the API key from [here](https://app.datadoghq.com/account/settings#api) if you are in Datadog US region and [here](https://app.datadoghq.eu/account/settings#api) if you're in Datadog EU region. |
| Host | The name of the originating host of the log and metrics. |
| Tags | Tags associated with your logs and metrics. Default tags `project_id` and `project_name` are exported with all logs and metrics. A source tag `hasura-cloud-metrics` is added to all exported logs. |
| Service Name | The name of the application or service generating the log events. |
<Thumbnail
src="/img/graphql/cloud/metrics/configure-datadog.png"
alt="Configure Datadog Integration"
/>
After adding appropriate values, click `Save`.
## Checking the status of the integration
The green/red dot signifies the status of the integration. Green signifies successful exporting of logs to datadog. When logs are successfully exported, `Last Exported` is continuously updated, indicating the timestamp of the last log line successfully exported to your Datadog dashboard.
<Thumbnail
src="/img/graphql/cloud/metrics/configure-datadog-done.png"
alt="Datadog Integration successfully configured"
width="1146px"
/>
In case there is an error while exporting logs to datadog, the dot is red and the HTTP status code of the error is displayed right below it.
<Thumbnail
src="/img/graphql/cloud/metrics/configure-datadog-fail.png"
alt="Datadog Integration successfully configured"
width="1146px"
/>
## View logs
The logs can be viewed in your Datadog dashboard, under the `Logs` tab. To navigate to the same, click `View Logs`.
<Thumbnail
src="/img/graphql/cloud/metrics/datadog-view-logs.png"
alt="Datadog Integration successfully configured"
width="1146px"
/>
<Thumbnail
src="/img/graphql/cloud/metrics/datadog-logs.png"
alt="Logs successfully exported to Datadog"
width="1146px"
/>
To view only logs exported by Hasura Cloud, filter your logs using `host` and/or `tags` you configured with this integration.
:::info Note
Datadog allows ingestion of logs with maximum size 256kB for a single log. If a log exceeds this limit, Datadog will truncate the log at 256kB.
:::
## View metrics
The integration exports the following five metrics to your Datadog dashboard:
| Metric Exported | Metric Name in Datadog |
|--------------------------------|-------------------------------|
| Average number of requests | `average_requests_per_minute` |
| Average request execution time | `average_execution_time` |
| Success rate of requests | `success_rate` |
| Active subscriptions | `active_subscriptions` |
| Number of websockets open | `websockets_open` |
Non zero values of all the above metrics are exported over a one minute time interval. Each metric name is prefixed with `hasura_cloud`.
Graphs for all the above metrics can be viewed in your Datadog dashboard, under the `Metrics` tab. To navigate to the same, click `View Metrics`.
<Thumbnail
src="/img/graphql/cloud/metrics/datadog-view-metrics.png"
alt="Datadog Integration successfully configured"
width="1146px"
/>
Select the graphs you want to view from the metrics explorer. Alternatively, select the `host` you configured with this integration to see all the graphs corresponding to metrics exported by Hasura Cloud.
<Thumbnail
src="/img/graphql/cloud/metrics/datadog-metrics.png"
alt="Metrics successfully exported to Datadog"
width="1146px"
/>

View File

@ -0,0 +1,24 @@
---
sidebar_position: 1
slug: index
description: Configure integrations with Hasura Cloud
keywords:
- hasura
- docs
- cloud
- integrations
- exporter
---
# Integrations with external services
You can export data like metrics and operation logs of your Hasura Cloud project to external services.
## Supported integrations
Check out the following guides for tutorials on how to integrate the following services with Hasura Cloud.
- [Datadog](/graphql/cloud/metrics/integrations/datadog.mdx)
- [New Relic](/graphql/cloud/metrics/integrations/newrelic.mdx)
- [Azure monitor](/graphql/cloud/metrics/integrations/azure-monitor.mdx)
- [Prometheus](/graphql/cloud/metrics/integrations/prometheus.mdx)

View File

@ -0,0 +1,120 @@
---
sidebar_position: 2
description: New Relic Integration on Hasura Cloud
keywords:
- hasura
- docs
- metrics
- integration
- export logs
- newrelic
- new relic
sidebar_label: New Relic
---
import Thumbnail from "@site/src/components/Thumbnail";
# New Relic Integration
## Introduction
You can export metrics and operation logs of your Hasura Cloud project to [New Relic](https://newrelic.com/). This can be configured on the integrations tab on the project's setting page.
:::info Note
New Relic Integration is only available for Hasura Cloud projects on the `Standard` (pay-as-you-go) tier and above.
:::
## Configure New Relic integration
Navigate to the integrations tab on project settings page to find New Relic integration.
<Thumbnail
src="/img/graphql/cloud/metrics/integrate-newrelic.png"
alt="Configure New Relic Integration"
width="1146px"
/>
Select the New Relic API region and enter the New Relic Insights Insert API key (follow [New Relic docs to retrieve the API key](https://docs.newrelic.com/docs/apis/get-started/intro-apis/new-relic-api-keys/#insights-insert-key)), host, service name and custom attributes to associate with exported logs and metrics.
| Field | Description |
|-------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Region | The region of the datacentre where your New Relic account stores its data. [Read more about regions on New Relic docs.](https://docs.newrelic.com/docs/using-new-relic/welcome-new-relic/get-started/our-eu-us-region-data-centers) |
| API Key | API keys are unique to your organization. An API key is required by the New Relic API to submit metrics and events to New Relic. You can get the API key from [here](https://one.newrelic.com/launcher/api-keys-ui.api-keys-launcher) if you are in New Relic US region and [here](https://one.eu.newrelic.com/launcher/api-keys-ui.api-keys-launcher) if you're in New Relic EU region. |
| Host | The name of the originating host of the log and metrics. |
| Custom Attributes | Custom Attributes associated with your logs and metrics. A default source tag `hasura-cloud-metrics` is added to all exported logs and metrics. Attributes `project_id` and `project_name` are added to all exported metrics. |
| Service Name | The name of the application or service generating the log events. |
<Thumbnail
src="/img/graphql/cloud/metrics/configure-newrelic.png"
alt="Configure New Relic Integration"
/>
After adding appropriate values, click `Save`.
## Checking the status of the integration
The green/red dot signifies the status of the integration. Green signifies successful exporting of logs to New Relic. When logs are successfully exported, `Last Exported` is continuously updated, indicating the timestamp of the last log line successfully exported to your New Relic account.
<Thumbnail
src="/img/graphql/cloud/metrics/configure-newrelic-done.png"
alt="New Relic Integration successfully configured"
width="1146px"
/>
In case there is an error while exporting logs to New Relic, the dot is red and the HTTP status code of the error is displayed right below it.
<Thumbnail
src="/img/graphql/cloud/metrics/configure-newrelic-fail.png"
alt="New Relic Integration successfully configured"
width="1146px"
/>
## View logs
The logs can be viewed in your New Relic dashboard, under the `Logs` tab ([read more on New Relic docs](https://docs.newrelic.com/docs/logs/log-management/get-started/get-started-log-management/#find-data)). To navigate to the same, click `View Logs`.
<Thumbnail
src="/img/graphql/cloud/metrics/newrelic-view-logs.png"
alt="New Relic Integration successfully configured"
width="1146px"
/>
<Thumbnail
src="/img/graphql/cloud/metrics/newrelic-logs.png"
alt="Logs successfully exported to New Relic"
width="1146px"
/>
To view only logs exported by Hasura Cloud, filter your logs using `attributes` you configured with this integration.
## View metrics
The integration exports the following five metrics to your New Relic account:
| Metric Exported | Metric Name in New Relic |
|--------------------------------|-------------------------------|
| Average number of requests | `average_requests_per_minute` |
| Average request execution time | `average_execution_time` |
| Success rate of requests | `success_rate` |
| Active subscriptions | `active_subscriptions` |
| Number of websockets open | `websockets_open` |
Non zero values of all the above metrics are exported over a one minute time interval. Each metric name is prefixed with `hasura_cloud`.
Graphs for all the above metrics can be viewed in your New Relic account. Under `Browse Data` select `Metrics` and choose the metrics name. To navigate to New Relic dashboard, click `View Metrics`.
<Thumbnail
src="/img/graphql/cloud/metrics/newrelic-view-metrics.png"
alt="New Relic Integration successfully configured"
width="1146px"
/>
Select the graphs you want to view from the metrics explorer.
<Thumbnail
src="/img/graphql/cloud/metrics/newrerlic-metrics.png"
alt="Metrics successfully exported to New Relic"
width="1146px"
/>

View File

@ -0,0 +1,184 @@
---
sidebar_label: Prometheus
sidebar_position: 4
description: Prometheus Integration on Hasura Cloud
keywords:
- hasura
- docs
- cloud
- metrics
- integration
- export metrics
- prometheus
- grafana
---
import Thumbnail from "@site/src/components/Thumbnail";
# Prometheus Integration
## Introduction
You can export metrics of your Hasura Cloud project to [Prometheus](https://prometheus.io/).
This can be configured on the integrations tab on the project's setting page.
:::info Note
Prometheus Integration is only available for Hasura Cloud projects on the `Standard` (pay-as-you-go) tier and above.
:::
## Configure Prometheus integration
Navigate to the integrations tab on project settings page to find Prometheus integration.
<Thumbnail
src="/img/graphql/cloud/metrics/integrate-prometheus.png"
alt="Configure Prometheus Integration"
width="1146px"
/>
Enter the Namespace and label values to be associated to the exported metrics and click on <em>Connect Integration</em>.
| Field | Description |
|----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Namespace (Optional) | The single word prefix relevant to the domain the metrics belong to. [Read more about namespace on Prometheus docs.](https://prometheus.io/docs/practices/naming/#metric-names) |
| Labels (Optional) | [Labels](https://prometheus.io/docs/practices/naming/#labels) are key-value pairs associated with your metrics used to differentiate the characteristics of the metric that is being measured. |
<Thumbnail
src="/img/graphql/cloud/metrics/configure-prometheus.png"
alt="Configure Prometheus Integration"
width="437px"
/>
## Prometheus instance configuration
The Prometheus instance(Agent) needs to be configured with Basic Auth
mode with Project ID as username and the generated Access token as Password.
The Connection URL is needed to configure the Scrape Target rule.
### Access Token
The Access Token is generated once the Integration is created.
The token is showed only once and cannot be retrieved again.
Access token is used as the password for Basic Authentication by the Prometheus Agent.
<Thumbnail
src="/img/graphql/cloud/metrics/prometheus-access-token.png"
alt="Prometheus Access Token"
width="1146px"
/>
The token can be re-generated from the Configuration Panel of the Integration. This action is permanent and cannot be reversed.
<Thumbnail
src="/img/graphql/cloud/metrics/prometheus-regenerate-token.png"
alt="Prometheus Access Token Regeneration"
width="1146px"
/>
### Connection URL
This is the secured webhook URL which exposes the Project Metrics in the
prometheus compatible format. It has 3 parts namely scheme, host name and metrics_path.
For example, if the connection URL is `https://prometheus-exporter.pro.hasura.io/metrics`,
then the scheme is `https`, host name (This includes sub-domains as well) is
`prometheus-exporter.pro.hasura.io` and metrics_path is `/metrics`.
<Thumbnail
src="/img/graphql/cloud/metrics/prometheus-connection-url.png"
alt="Prometheus Connection URL"
width="1146px"
/>
### Project ID
The Project ID is used as the Username for the Basic Authentication by the Prometheus agent.
<Thumbnail
src="/img/graphql/cloud/metrics/prometheus-project-id-copy.png"
alt="Prometheus Copy Project ID"
width="1146px"
/>
The following YAML template can be used as the [config file](https://prometheus.io/docs/prometheus/latest/configuration/configuration/)
to establish connectivity with the exposed Integration.
```yaml
global:
scrape_interval: 60s
scrape_configs:
- job_name: 'hasura_prometheus_exporter'
scrape_interval: 60s ## Recommended scrape interval is 60s
metrics_path: '/metrics' ## Replace with metrics Path of the connection URL
scheme: 'https' ## Replace with the scheme of the connection URL
basic_auth:
username: 'd01c60e1-1b11-564d-bb09-0a39e3e41b05' ## Replace with project ID
password: 'IrhO3GlR8oXTfsdfdsNs8Nj' ## Replace with Access Token
static_configs:
- targets: ['prometheus-exporter.pro.hasura.io'] ## Replace with the host name of the connection URL
```
## Checking the status of the integration
The green/red dot signifies the status of the integration. Green
signifies successful exporting of metrics to Prometheus. When metrics
are successfully exported, `Last Exported` is continuously updated,
indicating the timestamp of the last metric successfully exported to
your Prometheus Instance.
<Thumbnail
src="/img/graphql/cloud/metrics/prometheus-configure-done.png"
alt="Prometheus Integration successfully configured"
width="1146px"
/>
In case there is an error while exporting metrics to Prometheus,
the dot is red and the error message is displayed right below it.
<Thumbnail
src="/img/graphql/cloud/metrics/prometheus-configure-fail.png"
alt="Prometheus integration Pull failed"
width="1146px"
/>
## Metrics details
The integration exports the following five metrics to your Prometheus
Instance:
| Metric Exported | Metric Name in Prometheus |
|--------------------------------|-------------------------------|
| Average number of requests | `average_requests_per_minute` |
| Average request execution time | `average_execution_time` |
| Success rate of requests | `success_rate` |
| Active subscriptions | `active_subscriptions` |
| Number of websockets open | `websockets_open` |
:::info Note
If `average_requests_per_minute` is `0` (Which means no incoming
requests in the Last one minute), `average_execution_time` is reported
as `0` and `success_rate` is reported as 1 to avoid `NaN` values in
Prometheus.
:::
:::info Note
If `Namespace` and `Labels` are configured (Optional), the format of the
metric identifier is `namespace_metricName{key1=value1, key2=value2}`
:::
## View metrics
The metrics can be queried from the Prometheus Dashboard (or using tools like [Grafana](https://prometheus.io/docs/visualization/grafana/))
<Thumbnail
src="/img/graphql/cloud/metrics/prometheus-view-metrics.png"
alt="Prometheus view Metrics"
width="1200px"
/>

View File

@ -0,0 +1,87 @@
---
sidebar_position: 5
description: Hasura Cloud operation analysis
keywords:
- hasura
- docs
- cloud
- operations
---
import Thumbnail from "@site/src/components/Thumbnail";
# Operations
## Terminology
**Operation**
Any GraphQL (query, mutation, subscription) request made to v1/graphql endpoint of a GraphQL engine instance
**Operation name**
(Optional) Any GraphQL request can be labelled with a name by the client making the query. In this example, _getPollOptions_ is the operation name:
```graphql
query getPollOptions (
poll {
options {
id
name
description
}
}
}
```
**Operation ID**
A unique, auto-generated hash for each Operation name; can distinguish between different operations executed with the same name
**Operation type**
Whether the operation is a query, mutation, or subscription
**Request ID**
A unique, auto-generated ID for each request, comes from x-request-id HTTP header
**Websocket ID**
A unique ID generated by the server when a websocket connection is established by the client
**Websocket Operation ID**
A unique ID generated by the websocket client for each operation it is sending to the server
## Operations
Processed real-time logs of all requests to the GraphQL Engine. View all and inspect individual operations:
<Thumbnail
src="/img/graphql/cloud/metrics/pro-tab-operations.png"
alt="Hasura Cloud Console list operations"
/>
<Thumbnail
src="/img/graphql/cloud/metrics/pro-tab-operations-inspect.png"
alt="Hasura Cloud Console inspect operation"
/>
## Filtering operations
Click on the **Filter** header to open the menu of filter options
| Filter option | Filter type | Example or options |
|--------------------------|--------------------------|------------------------------------------------------------------------|
| Time range | timestamps | last hour, last 6 hours, last 12 hours, last 24 hours, or custom range |
| Operation ID | string (text field) | 5284946f4e15aa81bc868316d56aa68f |
| Operation Name | string (text field) | getPollOptions |
| Request ID | string (text field) | e15f7bj9-3b9f-4152-92a4-e745471514af |
| Show only errors | boolean (checkbox field) | true or false (default false) |
| Websocket ID | string (text field) | def703fc-851f-48e8-8e5c-cbdead37b2fe |
| Websocket Operation ID | string (text field) | 110 |
| Hide introspection query | boolean (checkbox field) | true or false (default false) |
| Operation Type | enum (select field) | query, mutation, subscription, all |
| Role | enum (select field) | from _x-hasura-user-role_: no role, admin, user, ... |
| Error Code | enum (select field) | no error code, access-denied, depth-limit-exceeded, ... |
| Client Name | enum (select field) | no client name, hasura-console, hasura-test-runner, ... |
| Transport | enum (select field) | http or ws |
| Status | enum (select field) | started or closed |
## Sorting operations
Each column in the **Operations List** can be sorted (ascending or descending) just by clicking on it. Very useful for identifying operations with unusually high execution time or response size!

View File

@ -0,0 +1,21 @@
---
sidebar_label: Overview
sidebar_position: 2
description: Hasura Cloud overview
keywords:
- hasura
- docs
- cloud
- overview
---
import Thumbnail from "@site/src/components/Thumbnail";
# Overview
The Overview displays aggregate stats over the last hour:
<Thumbnail
src="/img/graphql/cloud/metrics/monitoring-tab-overview.png"
alt="Hasura cloud stats monitoring"
/>

View File

@ -0,0 +1,20 @@
---
sidebar_position: 7
description: Hasura cloud subscription workers
keywords:
- hasura
- docs
- cloud
- subscription-workers
---
import Thumbnail from "@site/src/components/Thumbnail";
# Subscription workers
Subscription workers offer a subscription-worker-specific version of usage statistics:
<Thumbnail
src="/img/graphql/cloud/metrics/pro-tab-subscription-workers.png"
alt="Hasura Cloud Console subscription workers tab"
/>

View File

@ -0,0 +1,28 @@
---
sidebar_position: 4
description: Hasura Cloud usage analysis
keywords:
- hasura
- docs
- cloud
- reliability
- usage
---
import Thumbnail from "@site/src/components/Thumbnail";
# Usage
Learn about usage with aggregate summaries and filtering tools:
<Thumbnail
src="/img/graphql/cloud/metrics/pro-tab-usage.png"
alt="Hasura Cloud Console usage tab"
/>
Drill into an operation via its magnifying-glass icon in the 'Query List' table. You'll be taken to a list of similar operations, and can choose one to inspect for content, metadata, and error generated:
<Thumbnail
alt="Hasura Cloud Console inspect an operation"
src="/img/graphql/cloud/metrics/pro-tab-operations-inspect.png"
/>

View File

@ -0,0 +1,20 @@
---
sidebar_position: 6
description: Hasura Cloud websockets analysis
keywords:
- hasura
- docs
- cloud
- websockets
---
import Thumbnail from "@site/src/components/Thumbnail";
# Websockets
Websockets is a ws-specific version of usage statistics:
<Thumbnail
src="/img/graphql/cloud/metrics/pro-tab-websockets.png"
alt="Hasura Cloud Console websockets tab"
/>

View File

@ -0,0 +1,219 @@
---
description: Hasura Cloud preview apps on GitHub pull requests
keywords:
- hasura
- cloud
- docs
- preview
- review
- pr
- pull
- request
- github
sidebar_label: Preview apps
sidebar_position: 10
---
import Thumbnail from "@site/src/components/Thumbnail";
# Hasura Cloud Preview Apps
## Introduction
Hasura Cloud exposes an [API](/graphql/cloud/api-reference.mdx#api-ref-create-preview-app) to create preview apps with metadata and migrations from a branch of a GitHub repo. You can use this API for creating preview Hasura GraphQL Engine instances on pull requests and for previewing a Hasura project with metadata and migrations from a GitHub branch. This can be done either by triggering the API directly from your CI/CD or by using the [hasura-cloud-preview-apps](https://github.com/hasura/hasura-cloud-preview-apps) GitHub action.
:::info Note
Usage limits Usage is limited to 60 preview app API calls per month for users with only `Free` tier projects on Hasura Cloud. More plans coming soon.
:::
## Using the hasura-cloud-preview-apps GitHub action
### Step 1: Creating a Hasura Cloud Personal Token
Hasura Cloud APIs can be called programmatically through a Personal Access Token. You can create a personal access token from the `My Account` section in the bottom left of your cloud dashboard.
<Thumbnail
src="/img/graphql/cloud/preview-apps/access-token.png"
alt="Create Access Token"
width="1146px"
/>
Add this personal access token in your GitHub repo secrets as `HASURA_CLOUD_ACCESS_TOKEN`. You can do this in the `Settings` tab of your GitHub repo.
```bash
HASURA_CLOUD_ACCESS_TOKEN=<token>
```
### Step 2: Add a workflow to your GitHub repo
Create a file `.github/workflows/hasura-cloud-preview-app.yml` in your GitHub repo and add the following code:
```yaml
name: "preview-apps"
on: # rebuild any PRs and main branch changes
pull_request:
push:
branches:
- main
jobs:
hasura-cloud-preview:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Hasura Cloud Preview Apps
uses: hasura/hasura-cloud-preview-apps@v0.1.5
id: hasura_cloud_preview
with:
name: "repo-name-${{github.env.GITHUB_HEAD_REF}}${{github.event.number}}"
hasuraProjectDirectoryPath: hasura
hasuraEnv: |
ENV_VAR_1=value_1
env:
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
HASURA_CLOUD_ACCESS_TOKEN: ${{secrets.HASURA_CLOUD_ACCESS_TOKEN}}
- uses: hasura/comment-progress@v2.1.0
with:
github-token: ${{secrets.GITHUB_TOKEN}}
id: preview_app_comment
number: ${{github.event.number}}
repository: ${{env.GITHUB_REPOSITORY}}
message: |
Console URL available at ${{steps.hasura_cloud_preview.outputs.consoleURL}}
GraphQL Endpoint available at ${{steps.hasura_cloud_preview.outputs.graphQLEndpoint}}
```
Make sure you change the `name`, `hasuraProjectDirectoryPath` and `hasuraEnv` fields as per your preview app requirements and repo structure.
This workflow gets triggered on all pull requests to `main` branch and on pushes to `main` branch. It does the following:
- Clones the code from the given branch
- Creates the preview app with the provided options. Refer to [the GitHub action docs](https://github.com/hasura/hasura-cloud-preview-apps) for more options.
- Sets the following action outputs in the workflow so that you can use them for the subsequent jobs
- `graphQLEndpoint`: GraphQL endpoint of the created app
- `consoleURL`: Console URL of the created app
- `projectName`: Name of the created app
- `projectId`: The project ID of the created app
- Comments on the pull request (remove the last step if you don't want commenting)
### Step 3: Database Setup
If your Hasura instance uses a Postgres database, the `hasura/hasura-cloud-preview-apps` action can also create ephemeral databases on a given Postgres server for use in the preview apps. This way, if you pass the connection string to your Postgres server and the associated env vars to be exposed to Hasura, fresh databases' connection strings get added in the the given env vars.
To set this up:
1. Make sure your Postgres server accepts connections over the internet. If you don't have a Postgres server, you can follow [this guide](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-20-04) to set up a Postgres server on a Digital Ocean droplet or on a VM provided by any other vendor of your choice.
2. Add the connection URI of your Postgres server to the GitHub repo secrets as `POSTGRES_SERVER_CONNECTION_URI`.
3. Add the following snippet above `hasuraProjectDirectoryPath: hasura` to your `hasura-cloud-preview-app.yml` file.
```yaml
postgresDBConfig: |
POSTGRES_SERVER_CONNECTION_URI=${{secrets.POSTGRES_SERVER_CONNECTION_URI}}
PG_ENV_VARS_FOR_HASURA=PG_DB_URL_1,PG_DB_URL_2, PG_DB_URL3
```
The above snippet will create three temporary databases and expose their connection string to the created preview app through `PG_DB_URL1`, `PG_DB_URL2` and `PG_DB_URL3` env vars. Edit the snippet as per the env var requirements of your Hasura instance.
:::info
Note If you use databases other than Postgres, you can create the ephemeral databases yourself and pass the env vars in the `hasuraEnv` field.
:::
### Step 4: Set up the deletion of preview apps
Create a file `.github/workflows/delete-hasura-cloud-preview-app.yml` in your git repo and add the following code:
```yaml
on:
pull_request:
types: [closed]
jobs:
delete:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Hasura Cloud Preview Apps
uses: hasura/hasura-cloud-preview-apps@v0.1.5
with:
name: "repo-name-${{github.env.GITHUB_HEAD_REF}}${{github.event.number}}"
delete: true
env:
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} # ${{ secrets.GITHUB_TOKEN }} is provided by default by GitHub actions
HASURA_CLOUD_ACCESS_TOKEN: ${{secrets.HASURA_CLOUD_ACCESS_TOKEN}} # Hasura Cloud access token to contact Hasura Cloud APIs
```
This will make sure that whenever the pull request is closed, the preview app gets deleted.
:::info
Note If you have used `postgresDBConfig` in the creation workflow, make sure that you include it in the deletion workflow as well so that the created databases get deleted when the pull request is gets closed/merged.
:::
## Using the API manually
If the `hasura/hasura-cloud-preview-apps` GitHub action does not suit your needs, you can also directly contact the [createGitHubPreviewApp](/graphql/cloud/api-reference.mdx#api-ref-create-preview-app) API to manually setup preview apps on your GitHub repo.
```graphql
mutation createGitHubPreviewApp {
createGitHubPreviewApp(
payload: {
githubPersonalAccessToken: "<github_access_token>"
githubRepoDetails: {
branch: "main"
owner: "my-org"
repo: "my-repo"
directory: "backend/hasura"
}
projectOptions: {
cloud: "aws"
region: "us-east-2"
plan: "cloud_free"
name: "my-app_name"
envVars: [
{ key: "HASURA_GRAPHQL_AUTH_HOOK", value: "https://my-webhook.com" }
{ key: "MY_ENV_VAR_1", value: "my value 1" }
]
}
}
) {
githubPreviewAppJobID # job ID of the preview app creation job
}
}
```
This mutation queues the creation of the preview app and returns a UUID: `githubPreviewAppJobID`. You can get the creation status of the preview app by running the following query at `https://data.pro.hasura.io/v1/graphql`:
```graphql
query getPreviewAppCreationStatus($jobId: uuid!) {
jobs_by_pk(id: $jobId) {
id
status
tasks {
id
name
task_events {
id
event_type
public_event_data
error
}
}
}
}
```
Make sure to set the `githubPreviewAppJobID` in the the `id` argument to the GraphQL query.
## How it works?
Hasura cloud exposes the GraphQL mutations [createGitHubPreviewApp](/graphql/cloud/api-reference.mdx#api-ref-create-preview-app) that can be triggered programmatically using your personal access token. This mutation creates a Hasura Cloud project with the given set of environment variables and metadata-migrations from a branch of a GitHub repo.
When the mutation is triggered, Hasura Cloud queues the given preview app for creation. If a preview app with the given name exists for a user, it is cleaned up and metadata and migrations are applied on a fresh preview app. The cleanup is done so that every deployment is declarative and reproducible.

View File

@ -0,0 +1,4 @@
{
"label": "Projects & collaborators",
"position": 2
}

View File

@ -0,0 +1,72 @@
---
description: Managing collaborators on Hasura Cloud
keywords:
- hasura
- docs
- project
- team
- collaborators
sidebar_label: Project collaborators
sidebar_position: 3
---
import Thumbnail from "@site/src/components/Thumbnail";
# Project Collaborators
## Introduction
You can invite collaborators to your project and grant them partial or complete access to your Hasura console. The `Collaborators` tab shows the current people who have access to the project and the people who have been invited to the project.
## Invite a collaborator
Click `Invite a Collaborator` to invite a new collaborator by their email.
<Thumbnail
src="/img/graphql/cloud/projects/collaborators-view.png"
alt="Collaborators tab"
width="1146px"
/>
### Collaborator roles
Collaborators can have different levels of access in the Hasura console.
- **Admin** has complete access to the console i.e they can change the schema and the GraphQL engine metadata.
- **User** has limited privileges:
- The `Execute GraphQL` permission allows running queries, mutations and subscriptions from the `GraphiQL` tab of the console.
- The `View Metrics` permission allows inspecting operation data and metrics from the `PRO` tab of the console.
<Thumbnail
src="/img/graphql/cloud/projects/add-collaborator.png"
alt="Add collaborator"
width="437px"
/>
## Remove a collaborator
To remove a collaborator, click on the collaborator and then click on the remove icon on the top right:
<Thumbnail
src="/img/graphql/cloud/projects/remove-collaborator.png"
alt="Remove collaborator"
width="437px"
/>
If you have invited a collaborator, you can click on the `Invited` button to resend or revoke the invitation.
<Thumbnail
src="/img/graphql/cloud/projects/revoke-collaboration-invitation.png"
alt="Revoke collaboration invitation"
width="1146px"
/>
## Invitations
You can see the projects that you have been invited to collaborate on, on the project listing page.
<Thumbnail
src="/img/graphql/cloud/projects/project-collaboration-invitation.png"
alt="Projects invited to collaborate"
width="1146px"
/>

View File

@ -0,0 +1,109 @@
---
description: Creating projects on Hasura Cloud
keywords:
- hasura
- cloud
- docs
- start
sidebar_position: 1
---
import Thumbnail from "@site/src/components/Thumbnail";
# Creating projects
## Introduction
You can create a new Hasura Cloud project with either a new Postgres database, or an existing Postgres database with a publicly available IP address.
## Step 1: Project setup
To begin, navigate to the `Projects` page, and click the `New Project` link.
<Thumbnail
src="/img/graphql/cloud/projects/create-new-project.png"
alt="create new project button"
width="400px"
/>
This opens a form on the right where you can create your new project.
Choose a pricing plan, select a region and optionally enter the project name for your project in this form.
<Thumbnail
src="/img/graphql/cloud/projects/project-setup.png"
alt="project setup"
width="1100px"
/>
Once you have completed the project setup, click `Create Project`.
## Step 2: Database setup {#cloud-projects-db-setup}
To get started, Click `Launch Console` to open the Hasura console in your browser.
<Thumbnail
src="/img/graphql/cloud/getting-started/details-launch-console.png"
alt="database setup with new database"
width="900px"
/>
On the Hasura console, navigate to `Data -> Manage -> Connect Database`:
### New database
Hasura Cloud does not host databases, but does provide integrations with which you can create databases on managed cloud providers like Heroku. Integrations for AWS, GCP, and Azure are coming soon.
To get started, choose `Create Heroku Database -> Create Database`, and follow the prompts to authenticate with Heroku. Hasura Cloud will integrate with your Heroku account and manage the initial setup of a dev-tier Postgres instance. You can always upgrade the instance and manage options later through your Heroku account.
<Thumbnail
src="/img/graphql/cloud/projects/project-new-database-setup.png"
alt="database setup with new database"
width="700px"
/>
### Existing database
To use an existing database, choose `Connect existing database` and enter your database connection URL and enter your database connection string (looks like `postgres://username:password@hostname:port/dbname`).
<Thumbnail
src="/img/graphql/cloud/getting-started/connect-db.png"
alt="database setup with existing database"
width="700px"
/>
:::info
Note You can connect to databases either using env vars or by using their raw connection string/parameters. It is recommended to use env vars for better security _(as connection details are part of Hasura metadata)_ as well as to allow configuring different databases in different environments _(like staging/production)_ easily.
:::
### Allowing connections from Hasura Cloud IP {#cloud-projects-create-allow-nat-ip}
For some cloud services, like GCP, you'll need to adjust your Postgres connection settings to allow connections from the Hasura Cloud IP address. You can copy the IP address from the copy icon in the `Hasura Cloud IP` field on the project's details view.
<Thumbnail
src="/img/graphql/cloud/projects/hasura-cloud-ip.png"
alt="Hasura Cloud IP field"
width="1000px"
/>
<Thumbnail
src="/img/graphql/cloud/projects/gcp-postgres-authorized-network.png"
alt="whitelist Hasura instance IP in Postgres settings"
width="727px"
/>
## Postgres requirements
Hasura Cloud works with **Postgres versions 9.5 and above**.
Make sure your database user has the right [Postgres permissions](/graphql/cloud/getting-started/postgres-permissions.mdx).
## Connecting to a database not exposed over the internet
[Contact us](https://hasura.io/contact-us/) for VPC peering and on-premise solutions.
## More databases
Support for more databases (MySQL, SQL Server etc) is coming soon.

View File

@ -0,0 +1,20 @@
---
description: Deleting projects on Hasura Cloud
keywords:
- hasura
- docs
- delete
sidebar_position: 15
---
import Thumbnail from "@site/src/components/Thumbnail";
# Deleting projects
You can delete a project with the `Delete Project` button at the bottom of the project's details view.
<Thumbnail
src="/img/graphql/cloud/projects/projects-delete.png"
alt="delete a project"
width="1199px"
/>

View File

@ -0,0 +1,89 @@
---
description: Project Details on Hasura Cloud
keywords:
- hasura
- docs
- cloud
- rename
- labels
- details
- region
sidebar_label: Project details
sidebar_position: 2
---
import Thumbnail from "@site/src/components/Thumbnail";
# Project Details
## Introduction
You can view all the details about your project in the `General` tab.
<Thumbnail
src="/img/graphql/cloud/projects/general-details.png"
alt="General tab"
width="900px"
/>
## Name {#rename-project}
Every project has a unique name. This name is also a part of the default domain of your project. For example, if your project name is `neat-alien-78`, the project assumes the default domain `neat-alien-78.hasura.app`.
If you are the project owner, you can rename the project by clicking the edit icon in the `Name` field.
<Thumbnail
src="/img/graphql/cloud/projects/project-rename-before.png"
alt="Project rename"
width="900px"
/>
Once you type a name, hit `Save`.
<Thumbnail
src="/img/graphql/cloud/projects/project-rename-in-progress.png"
alt="Project renaming"
width="900px"
/>
If you have added custom domain(s) to your project, you must update the DNS settings of your custom domain(s) as per the project name change.
<Thumbnail
src="/img/graphql/cloud/projects/project-rename-dns-update.png"
alt="Project rename DNS update"
width="900px"
/>
:::info Note
After renaming, your project might undergo a short downtime due to the DNS resolution as per the new project name.
:::
## Region
The region field shows the project's region of deployment. The default region of deployment is `AWS, us-east-2 (Ohio)`. You can change the region by clicking the edit icon next to it. Read more about switching deployment regions `here <project_regions>`.
## Pricing Plan
This field shows the plan that the project is on. Read about switching pricing plans [here](/graphql/cloud/projects/pricing.mdx).
## Hasura Cloud IP
This is the NAT gateway IP of Hasura Cloud. If your database is not exposed to the internet, you can allow connections from this IP address so that Hasura Cloud can connect to your database.
## Labels
You can create and assign one or more labels to your projects (`dev`, `staging`, `production` etc). Click on the `+` button in the project labels pane to assign (or create and assign) a label.
<Thumbnail
src="/img/graphql/cloud/projects/project-assing-label.png"
alt="Project labels"
width="900px"
/>
As of now, you can create labels, assign them to projects and remove them from projects. A user can use only the labels that they have created and they can assign labels only to the projects that they own.
Project collaborators can only view the labels assigned to the project by the project owners.
Support for editing labels and permanently deleting them is coming soon.

View File

@ -0,0 +1,83 @@
---
description: Managing domains on Hasura Cloud
keywords:
- hasura
- docs
- project
- domains
sidebar_position: 6
---
import Thumbnail from "@site/src/components/Thumbnail";
# Project Domains
## Introduction
In the `Domains` tab, you can see the default Hasura domain, and you have the possibility to add custom domains.
## Adding a custom domain
You can add a custom domain to your Hasura Cloud project by following the steps below.
### Step 1: Navigate to add a custom domain
On the `Domains` tab, click on the `New Custom Domain` button.
<Thumbnail
src="/img/graphql/cloud/projects/add-custom-domain.png"
alt="Add custom domain"
width="727px"
/>
### Step 2: Add your custom domain
Enter your custom domain and click the `Add` button.
<Thumbnail
src="/img/graphql/cloud/projects/choose-custom-domain.png"
alt="Choose custom domain"
width="727px"
/>
### Step 3: Add the record to your DNS
After adding a custom domain, the following window will show up:
<Thumbnail
src="/img/graphql/cloud/projects/dns-settings.png"
alt="DNS settings"
width="727px"
/>
Add the default Hasura domain as a `CNAME` record to your DNS.
:::info Note
If you're using [Cloudflare](https://www.cloudflare.com) as your DNS provider, do not enable the proxy (orange cloud) until the certificate is generated. i.e. `Proxy status` should be `DNS only`. You can enable the proxy after SSL certificate is generated.
:::
Until this is done, the dashboard will show a notice that the DNS validation is pending.
<Thumbnail
src="/img/graphql/cloud/projects/dns-validation-pending.png"
alt="DNS validation pending"
width="727px"
/>
:::info Note
Depending on your DNS provider, it might take up to 24 hours for the DNS record to be added.
:::
## DNS validated
Once the DNS is validated, the dashboard will update the status with the following notice:
<Thumbnail
src="/img/graphql/cloud/projects/dns-validated.png"
alt="DNS validated"
width="727px"
/>

View File

@ -0,0 +1,34 @@
---
description: Managing env vars on Hasura Cloud
keywords:
- hasura
- docs
- project
- env vars
sidebar_position: 5
---
import TOCInline from "@theme/TOCInline";
import Thumbnail from "@site/src/components/Thumbnail";
# Project Env vars
## Introduction
The `Env vars` tab allows setting [Hasura GraphQL Engine env variables](/graphql/core/deployment/graphql-engine-flags/reference.mdx#command-flags) and adding other custom env variables as well.
## Adding an env var
Click on the `New Env Var` button and either choose an env var from the dropdown or add a custom env var.
<Thumbnail
src="/img/graphql/cloud/projects/new-envvars.png"
alt="add env var options"
width="1200px"
/>
<Thumbnail
src="/img/graphql/cloud/projects/add-env-var.png"
alt="add env var options"
width="1200px"
/>

View File

@ -0,0 +1,136 @@
---
description: Guide for managing development environments for Hasura Cloud
keywords:
- hasura
- docs
- cloud
- guide
- local dev
- staging
- production
- environment
sidebar_label: Managing development environments
sidebar_position: 10
---
# Managing development environments with Hasura Cloud
## Introduction
This guide will show how to configure your Hasura project for easy switching between development environments.
## Moving from Hasura Cloud to local development
### Step 1: Setup local development of Hasura with Docker
Follow the guide [here](/graphql/core/getting-started/docker-simple.mdx) to get up and running with Hasura GraphQL engine and Postgres as Docker containers in your local system. Make sure that the ENV variable for database connection in your local setup is same as that in your Cloud project. Also add any other ENV variables that you might have set on the Cloud project.
### Step 2: Install Hasura CLI
Follow the instructions in [install_hasura_cli](/graphql/core/hasura-cli/install-hasura-cli.mdx)
### Step 3: Initialize a Hasura CLI project locally
```bash
hasura init <project-name>
```
### Step 4: Initialize the migration files
This will get your database schema from the cloud project to your local setup
```bash
hasura migrate create init --from-server --endpoint <hasura-cloud-project-url> --admin-secret <admin-secret> --database-name <database-name>
# note down the version
# mark the migration as applied on the cloud project
hasura migrate apply --endpoint <hasura-cloud-project-url> --admin-secret <admin-secret> --version <version-number> --skip-execution
```
It is important to mark the migration as applied on the Cloud project to ensure that the schema that is already created on Hasura Cloud project is not attempted to be recreated again, which would end in an error state.
### Step 5: Export metadata
```bash
hasura metadata export --endpoint <hasura-project-url> --admin-secret <admin-secret>
```
We have successfully synced our state from Cloud to the Hasura CLI local dev environment.
Next, we apply all these changes to our local Hasura with Docker setup.
### Step 6: Apply metadata and migrations to your local Hasura instance
```bash
hasura metadata apply
hasura migrate apply --all-databases
hasura metadata reload
```
By default the metadata and migrations are applied to `http://localhost:8080` which is the endpoint specified in the `config.yaml` file of your CLI project. If you want to apply the metadata and migrations to any other endpoint, you could go ahead and change the endpoint in the `config.yaml` file or use the `--endpoint` flag along with the commands above.
And you're all set now! Go ahead and setup version control for your project for further ease of integration.
## Moving from local development to Hasura Cloud
If you have been using the OSS version of Hasura GraphQL engine locally using Docker and want to move to a Hasura Cloud project, start by creating a project at <https://cloud.hasura.io/signup>
Once the project is created, launch console and connect your database. Make sure that the name of the database is same as that in your local setup. Do refer this [Getting Started guide](/graphql/cloud/getting-started/index.mdx) for a step-by-step guide.
Also ensure the database is connected using the same ENV var in your local setup and the Cloud project. You might have drop and create a new ENV var containing the database URL on your Cloud project if required.
Also add any other ENV vars that you might have set on your local project.
### Setting up a Git repo for your Hasura project
In order to easily apply your local changes to your new Cloud project, we'll use the Hasura [GitHub deployment](/graphql/cloud/projects/github-integration.mdx) feature. But before we do that, we need to setup metadata & migrations of your local setup that you can apply to your Cloud project. For a lowdown on Hasura metadata & migrations refer the guide [here](/graphql/core/migrations/index.mdx)
### Step 1: Install Hasura CLI
Follow the instructions in [install_hasura_cli](/graphql/core/hasura-cli/install-hasura-cli.mdx)
### Step 2: Setup a project directory
```bash
hasura init <project-name> --endpoint <local-project-endpoint>
```
Your local project endpoint might be `http://localhost:8080` (based on how it was setup initially). This creates a project directory with `migrations` and `metadata` directories and a `config.yaml` file.
### Step 3: Initialize the migration files
This will get your database schema from your local setup into the project folder.
```bash
hasura migrate create init --from-server --admin-secret <admin-secret> --database-name <database-name>
# note down the version
# mark the migration as already applied on the local server
hasura migrate apply --admin-secret <admin-secret> --version <version-number> --skip-execution
```
### Step 4: Initialize Hasura metadata
```bash
hasura metadata export
```
This command will export the current Hasura metadata as a bunch of YAML files in the `metadata` directory.
### Step 5: Setup version control & Git Deploy
```bash
# in the project directory
git init
git add .
git commit -m "initialize metadata and migrations"
```
Push these changes to GitHub repo of your choice.
Now we're all set to see the magic of our GitHub integration to deploy the metadata and migrations to your Cloud project by following the steps [here](/graphql/cloud/projects/github-integration.mdx)!

View File

@ -0,0 +1,310 @@
---
description: GitHub Integration
keywords:
- hasura
- docs
- project
- github
- deployment
- git
sidebar_label: GitHub deployment
sidebar_position: 11
---
import Thumbnail from "@site/src/components/Thumbnail";
# GitHub Deployment
## Introduction
GitHub integration is intended to improve the CI/CD experience on Hasura
Cloud. With GitHub integration, you can link a GitHub repository and a
branch to a Hasura Cloud project and automatically deploy metadata and
migrations in a given directory to the linked project.
Check out our [Starter
Kit](https://github.com/hasura/github-integration-starter) to see a few
example workflows.
:::info Under preview
This feature is currently available for preview. Enhancements to it will
continue to be made over the coming days. To try it out you can ask for
early access to the feature from the Hasura Cloud dashboard.
Please do share any feedback you may have regarding any improvements or
extra capabilities that you would like to see in this feature by raising
an issue/discussion on our [GitHub repo](https://github.com/hasura/graphql-engine).
:::
## Deployment modes
### Automatic Deployment Mode
With the `Automatic deployment mode`, Hasura Cloud automatically
triggers a deployment for every commit pushed to the GitHub repository
from the given branch and directory.
<Thumbnail
src="/img/graphql/cloud/projects/automatic-commit-deployment.png"
alt="Automatic GitHub deployment"
width="900px"
/>
The Automatic deployment mode also has the `Deploy Now` button which
allows the user to retry deploying the latest commit.
### Manual Deployment Mode
With `Manual deployment mode`, Hasura Cloud does not automatically
deploy the commits pushed to the configured branch. The deployment of
the latest commit in that branch can be triggered manually by clicking
the `Deploy Now` button.
<Thumbnail
src="/img/graphql/cloud/projects/manual-commit-deployment.png"
alt="Manual GitHub deployment"
width="900px"
/>
## Initial setup
### Link GitHub account to a Hasura Cloud project
To link a GitHub account, click on the `Sign in with GitHub` button in
the Git Deployment section of the project details.
<Thumbnail
src="/img/graphql/cloud/projects/github-link-account.png"
alt="Link GitHub Account"
width="900px"
/>
When you link a new GitHub account, Hasura Cloud installs the Hasura
Cloud GitHub App on your GitHub account. While authenticating, you can
choose to grant access to all repositories or to specific repositories
only.
<Thumbnail
src="/img/graphql/cloud/projects/github-grant-access.png"
alt="GitHub grant access"
width="500px"
/>
The permissions requested by Hasura Cloud can be viewed in the GitHub
app settings once you install the app.
Once linked, the GitHub account with the granted scope becomes available
to all the admins on the project as the session is used to manage the
GitHub integration from the UI.
### Integrate GitHub repo with a Hasura Cloud project
Specify the GitHub repository, branch and the hasura-project directory
in the form as shown below.
<Thumbnail
src="/img/graphql/cloud/projects/setup-github-integration.png"
alt="Setup GitHub Integration"
width="900px"
/>
If the repository that you're looking for doesn't show up in the
repository list, click `Configure Hasura Cloud on GitHub` to grant
access to the required repository.
Clicking on the `Setup Git Deployment` button integrates the specified
GitHub repository, branch and directory with the Hasura Cloud project.
The details for the integration can be viewed in the `Git Deployment`
section of project details.
<Thumbnail
src="/img/graphql/cloud/projects/github-integration-details.png"
alt="Setup GitHub Integration"
width="900px"
/>
## Edit GitHub Integration
Click on the `Edit Deployment` button in the GitHub Deployment section
to edit the GitHub repository/branch/directory/deployment mode for the
GitHub integration.
<Thumbnail
src="/img/graphql/cloud/projects/edit-github-integration.png"
alt="Setup GitHub Integration"
width="900px"
/>
## Deployment Log
User can view the deployed commits and their deployment status in the
`Deployment Log` section of Git Deployment.
<Thumbnail
src="/img/graphql/cloud/projects/deployment-log.png"
alt="GitHub deployment log"
width="900px"
/>
## Deployment Process
Once a commit deployment is triggered, the progress for a commit can be
tracked by clicking on the `View Logs` button in the Deployment Log
section.
Refer to the following task wise breakdown of the deployment job to
understand what the job will be doing.
Check the troubleshooting section below and do reach out to support if
you observe any issues with the deployment process or run into any other
problems post the deployment.
### Deployment sub-tasks
The following is a task wise breakdown of the commit deployment job.
<Thumbnail
src="/img/graphql/cloud/projects/github-deployment-status.png"
alt="GitHub deployment Progress"
width="500px"
/>
Each task in the deployment has realtime logs and can be viewed by
clicking on the `Logs` option for each successful/failed step.
#### Step 1: Fetching Metadata / Migrations
The metadata and migrations are fetched from the GitHub repository and
validated.
#### Step 2: Applying Metadata
The metadata in the GitHub repository is applied to the server.
#### Step 3: Applying Migrations
The migrations in the GitHub repository are applied to your data
sources.
#### Step 4: Finalizing Update
The metadata on the server is reloaded and project health is verified
before finalizing the update.
## Things to check before running your first deployment {#github-integration-pre-checks}
You need to ensure the your Cloud project has been appropriately set up
to execute the deployment.
- Ensure all the required Hasura config related and any other custom
ENV vars that might be used in the metadata are added to your Cloud
project as well.
- Ensure that you have connected the required database(s) with the
right name and connection params as you have in the metadata to the
Cloud project.
## Troubleshooting Failures {#github-integration-troubleshooting}
If a deployment fails, depending on the kind of error, you can fix it by
retrying the deployment by either updating your metadata and migrations
with a fix and pushing a commit to deploy again or by just redeploying
the failed commit after making any required fixes to your project.
The following are some troubleshooting steps to fix some possible errors
in the deployment sub-tasks:
### Error parsing metadata
- Nothing has been modified on your project yet so there will be no
service impact.
- Typically happens due to some issue with the metadata directory
structure or the format of the metadata files.
- Check the reported error message and fix the issues in the metadata.
See [metadata format](/graphql/core/migrations/reference/metadata-format.mdx).
- Push the fix to GitHub to redeploy.
### Error parsing migrations
- Nothing has been modified on your project yet so there will be no
service impact.
- Typically happens due to some issue with the migration directory
structure or the format of the migration files.
- Check the reported error message and fix the issues in the
migrations. See [migrations format](/graphql/core/migrations/reference/migration-file-format.mdx).
- Push the fix to GitHub to redeploy.
### Error applying metadata
- Nothing has been modified on your project yet so there will be no
service impact.
- Typically happens due to some invalid metadata (e.g. due to type
mismatches, missing required keys, etc.) trying to be applied.
- Check the reported error message and fix the issues in the metadata.
See [metadata format](/graphql/core/migrations/reference/metadata-format.mdx).
- Push the fix to GitHub to redeploy.
### Error applying migrations
- As your metadata has already been applied but applying your
migrations have failed, your project might be in an unhealthy state.
If your migrations and metadata had only incremental changes, i.e.
no existing objects were modified, you likely wont have any service
impact because existing parts of your metadata are likely to be
still valid and your existing functionality will be working as it
were.
- Look at the underlying database error. Make the appropriate fix
depending on the error and redeploy.
- Some common errors:
- <em>source with name “default” is inconsistent</em>
In this situation, most likely either the target project doesn't
have the required database connected or the ENV VARS or the
database name used to connect the database is not matching in
your source and target projects.
To fix this, use the same ENV VARS and connect the database with
the same name in both your projects.
- `“relation '<some-object>' already exists”`
In such situations when you get errors of tables or other
objects already existing, this might be because the migration
might have been already applied on the database and the project
was not yet aware of it.
To fix this, use the Hasura CLI command
`hasura migrate apply --skip-execution --version <migration_version> --endpoint "<cloud_project_endpoint>"`
to mark the migration as already applied on the project. Then
redeploy the failed commit to continue with further steps.
### Inconsistent metadata after finalizing update
- It is possible your project might be in an unhealthy state depending
on which metadata objects are inconsistent and what migrations were
applied. If your metadata and migrations had only incremental
changes, i.e. no existing objects were modified, you likely wont
have any service impact because existing parts of your metadata are
likely to be still valid and your existing functionality will be
working as it were.
- Check the logs under `Applying Migrations` and `Finalizing Update`.
- In the situation that the applied metadata applied was indeed
incorrect, fix the metadata and push a new commit to redeploy.
- If objects depending on upstream services are inconsistent, e.g.
remote schemas, the upstream service might be unavailable or
inconsistent. In this case please fix them and redeploy the commit.
- If database objects are inconsistent with errors such as <em>Inconsistent object: no such table/view exists in
source: `<table-name>`</em>, it could be because:
- a migration might have been skipped as the project believes its
already been applied though its not the case. To fix it, mark
the migration as unapplied using the following Hasura CLI
command
`hasura migrate delete --version <migration_version> --server --database-name <database-name> --endpoint <cloud_project_endpoint>`
and redeploy the commit.
- a migration to create the database objects might be missing
completely. To fix this create a new migration for creation of
the missing objects and push a new commit to redeploy.
- A rollback can be done to the previous functioning state of metadata
by reverting your metadata changes on your branch and then pushing
to redeploy.

View File

@ -0,0 +1,122 @@
---
description: Automatically sync database URL of a Heroku Postgres into a Hasura Cloud project
keywords:
- hasura
- docs
- project
- team
- heroku
- database url
- sync
sidebar_position: 12
---
import Thumbnail from "@site/src/components/Thumbnail";
# Heroku database integration
## Introduction
Hasura Cloud makes it easy for you to use Heroku Postgres as a
datasource in your Hasura Cloud projects. It makes sure that the
`DATABASE_URL` environment variable of your Heroku App stays in sync
with a given environment variable of your Hasura Cloud project. This
means that whenever the database credentials of your Heroku Postgres are
rotated, this integration ensures that the linked environment variable
in your Hasura Cloud project also gets updated.
## Connecting an existing Heroku database {#cloud-connect-existing-heroku-db}
You can connect your Heroku database to your Hasura project by following these steps:
1. Go to your Hasura Cloud dashboard and head to the settings section of the desired project
2. Go to `Integrations` tab and click on the Heroku integration under `Databases`
<Thumbnail src="/img/graphql/cloud/projects/heroku-integration.png" alt="Heroku Integration" width="1100px" />
3. Login into Heroku, enter an env var name of your choice (say `PG_DATABASE_URL`) and connect the desired database from the list of databases
After a couple of seconds the env var will be updated with your connected database url and you can see it in the `Env Vars` tab of your project.
4. Now you can go ahead to your project console's `Data` tab and connect the database through the env var that you created.
<Thumbnail src="/img/graphql/cloud/projects/heroku-db-connect.png" alt="Heroku DB Connect" width="600px" />
This completes your integration setup, you can now go ahead, track tables and try out Hasura's GraphQL APIs.
:::info Note
Deleting the Heroku integration from your `Integrations` section does
not delete the associated env var, it only stops the database url sync.
Should you want to remove the env var also, it is recommended to remove
the connected database from your console and then deleting the
associated env var to prevent metadata inconsistency.
:::
## Creating a new Heroku database
1. Go to your project console's `Data` tab and click `Data Manager` on top left corner of the page.
2. Click the `Connect Database` button and choose the `Create Heroku Database` tab.
<Thumbnail src="/img/graphql/cloud/projects/console-heroku-db-create.png" alt="Heroku DB Create" width="700px" />
3. Click the `Heroku` button to login and create a database.
This creates a Heroku app, installs Heroku Postgres in it and sets the
Postgres connection URI in `PG_DATABASE_URL_*` env var of your Hasura
Cloud project. It also adds a datasource in Hasura that refers to the
created Postgres database using the env var.
## Heroku database URL sync
If you use Hasura Cloud's Heroku integration, it keeps your project's Heroku database URL i.e. the associated env var in sync with the Postgres URL from a Heroku app.
This is especially helpful in cases when the database credentials of Heroku Postgres are rotated automatically by Heroku.
:::info Note
The database sync automatically gets disconnected if you transfer the ownership of your project to another account. The new project owner can restart the sync with the Heroku account that they have connected their Hasura Cloud account to.
:::
### Enable Heroku database URL sync
If you create a project with a Heroku trial database using the Hasura console, your project has the Heroku database URL sync enabled by default, which means, Hasura Cloud keeps the database URL of your project in sync with the related Heroku Postgres.
If you have already connected your Heroku database to your Hasura Cloud project and would like to enable database URL sync on it,
you can remove and re-add the database url env var with the Heroku integration as shown [above](#cloud-connect-existing-heroku-db)
### Opt out of Heroku database URL sync
If your project has Heroku database URL sync enabled, you can opt out using the following methods:
#### Option 1:
1. Go to the `Env vars` tab of your project and click on the env var that is involved in the Heroku database URL sync.
2. Click on `Opt out of the sync` button next to Heroku note.
<Thumbnail src="/img/graphql/cloud/projects/heroku-db-sync-enabled-new.png" alt="Enabled DB Sync" width="1100px" />
#### Option 2:
You can also opt out of Heroku database URL sync by deleting the integration from project integrations page.
<Thumbnail src="/img/graphql/cloud/projects/heroku-delete-integration.png" alt="Delete Heroku Integration" width="1100px" />
## How it works?
Heroku database URL sync is useful because Postgres credentials of Heroku Postgres are sometimes rotated thus making the old database URL invalid. Hasura Cloud listens to the changes in the database URL of your app and keeps the project updated. This is done using:
1. [Heroku Releases](https://devcenter.heroku.com/articles/releases): Whenever a config variable of a Heroku app changes, a new `release` is made for that app.
2. [Heroku Webhooks](https://devcenter.heroku.com/articles/app-webhooks): Heroku allows us to get notifications about these releases on a webhook.
Whenever Postgres credentials of a Heroku app are rotated:
1. The `DATABASE_URL` config variable of the Heroku app gets updated with the new credentials.
2. The config variable change triggers a new release, which notifies Hasura Cloud's webhook.
3. When Hasura Cloud is notified about the new release, it fetches the newest database URL from Heroku and updates the connected env var of your project with it.
4. This way, your project is always configured with the correct database URL.

View File

@ -0,0 +1,72 @@
---
description: Managing teams in Hasura Cloud
keywords:
- hasura
- docs
- cloud
- teams
slug: index
---
import Thumbnail from "@site/src/components/Thumbnail";
# Projects & collaborators
## Introduction
The `Projects` page shows a list of your projects.
<Thumbnail
src="/img/graphql/cloud/projects/projects-list.png"
alt="Projects list"
width="1200px"
/>
For each project, you can do the one of the following actions:
<Thumbnail
src="/img/graphql/cloud/projects/project-actions.png"
alt="Project actions"
width="860px"
/>
- Click `Launch Console` to open the Hasura console in your browser. The `Monitoring` tab lets you use the Pro features that Hasura Cloud has set up for you.
<Thumbnail
src="/img/graphql/cloud/metrics/monitoring-tab-overview.png"
alt="Hasura Console: Monitoring tab"
width="900px"
/>
- Click the gear icon to manage your project
<Thumbnail
src="/img/graphql/cloud/projects/project-details.png"
alt="General tab"
width="900px"
/>
:::info Note
Please see the [API reference](/graphql/cloud/api-reference.mdx) to create and manage Hasura Cloud projects programmatically.
:::
## Dig deeper
- [Creating projects](/graphql/cloud/projects/create.mdx)
- [Project Details](/graphql/cloud/projects/details.mdx)
- [Project Collaborators](/graphql/cloud/projects/collaborators.mdx)
- [Transfer Ownership](/graphql/cloud/projects/ownership.mdx)
- [Project Env vars](/graphql/cloud/projects/env-vars.mdx)
- [Project Domains](/graphql/cloud/projects/domains.mdx)
- [Securing projects](/graphql/cloud/projects/secure.mdx)
- [Switching pricing plans](/graphql/cloud/projects/pricing.mdx)
- [Deployment regions](/graphql/cloud/projects/regions.mdx)
- [Managing development environments](/graphql/cloud/projects/environments.mdx)
- [GitHub Deployment](/graphql/cloud/projects/github-integration.mdx)
- [Heroku database integration](/graphql/cloud/projects/heroku-url-sync.mdx)
- [Vercel Integration](/graphql/cloud/projects/vercel-integration.mdx)
- [Maintenance mode](/graphql/cloud/projects/maintenance-mode.mdx)
- [Deleting projects](/graphql/cloud/projects/delete.mdx)
- [Updating v1.3 projects to v2.0](/graphql/cloud/projects/move-project-v2.mdx)

View File

@ -0,0 +1,65 @@
---
description: Cloud maintenance mode
keywords:
- hasura
- docs
- project
- maintenance
- maintenance mode
sidebar_position: 14
---
import Thumbnail from "@site/src/components/Thumbnail";
# Maintenance mode
## Introduction
When updates are being rolled out to your Hasura Cloud project which
demand no interruptions to your instance's configuration, maintenance
mode is activated for your project.
:::info Note
Currently, cloud maintenance mode will only be activated for your
project while you are updating it to Hasura GraphQL Engine `v2.0`.
:::
:::info Note
This is not to be confused with environment variable
`HASURA_GRAPHQL_ENABLE_MAINTENANCE_MODE`. The two are different as the
env var enables the server maintenance mode which disables metadata APIs
(writes) on the project while the cloud maintenance mode does not. See
below for actions disabled by the cloud maintenance mode.
:::
## Check if maintenance mode is activated
Navigate to your project's settings page, you should see a top banner
mentioning if your project is under maintenance.
<Thumbnail
src="/img/graphql/cloud/projects/maintenance-mode.png"
alt="Project with maintenance mode activated"
/>
If you don't see such a banner, your project is not under maintenance
mode.
## Disabled actions when maintenance mode is activated
All actions that update your project's configurations are not allowed
when maintenance mode is activated. The following actions are
disallowed:
- [Switching pricing plans](/graphql/cloud/projects/pricing.mdx)
- [Adding, updating and deleting an environment variable](/graphql/cloud/projects/env-vars.mdx)
- [Changing project region](/graphql/cloud/projects/regions.mdx)
- [Enabling and disabling Heroku database URL sync](/graphql/cloud/projects/heroku-url-sync.mdx)
- [Deleting project](/graphql/cloud/projects/delete.mdx)
If you are trying to apply these changes when maintenance mode is
activated, you will encounter an error.

View File

@ -0,0 +1,95 @@
---
description: Moving existing project to a new project
keywords:
- hasura
- docs
- project
- move
- transfer
- downgrade
- transfer region
sidebar_position: 17
---
# Transfer existing Hasura Cloud project to a new project
## Introduction
To transfer a project you will have to create a new Hasura project and
configure it with the same Hasura metadata and other configuration as in
the previous project.
The following is a guide to achieve this.
## Step 1: Export metadata from existing project
See [exporting metadata](/graphql/core/migrations/manage-metadata.mdx) to get a copy of the
current Hasura metadata on your project.
Do ensure no further changes are made to the Hasura metadata post this.
## Step 2: Create a new Cloud project with the same configuration
See `Step 1` of [creating projects](/graphql/cloud/projects/create.mdx) to create a new
Hasura Cloud project.
After project creation, update the Hasura Cloud configuration of the new
project with the same configuration as the earlier project. i.e. add the
same ENV vars, custom domains, collaborators, billing, etc.
## Step 3: Apply the exported metadata to the new project
See [applying metadata](/graphql/core/migrations/manage-metadata.mdx) to apply the earlier
exported metadata to the new project.
The new project should now be generating the same GraphQL API as the
earlier project.
## Step 4: Delete the earlier project
See [deleting projects](/graphql/cloud/projects/delete.mdx) to delete the earlier project.
## Optional steps
- If you are using Hasura migrations on your project, please mark all
existing migrations as applied on the new project using the
following Hasura CLI command:
```bash
hasura migrate apply --skip-execution --endpoint <new-project-endpoint> --admin-secret <new-project-admin-secret> --all-databases
```
- You can [rename](/graphql/cloud/projects/details.mdx#rename-project) your new project to the same name
as the earlier project if you wish.
- If you haven't renamed your new project or set up a
[custom domain](/graphql/cloud/projects/domains.mdx) for your project, you might
want to update any clients consuming the GraphQL API to point to the
new project's GraphQL endpoint.
## Zero-downtime transfer
To achieve a zero-downtime transfer, you will need to have a
[custom domain](/graphql/cloud/projects/domains.mdx) attached to your Cloud project.
Once the new project is set up identically as the old one, you can
update the DNS entries for your custom domain to the new project to have
a seamless transfer of traffic to the new project.
If you simply want to avoid updating your clients with the new project's
API endpoint, you can simply [rename](/graphql/cloud/projects/details.mdx#rename-project) your new project
with the same name as the earlier project. This will cause a short
downtime of your API after you delete your old project until you rename
the new one.
## Caveats
You will lose the following data from your earlier project in the
process:
- all existing scheduled events
- all existing async actions
- past invocation logs of cron triggers
If you would like these to be transferred to the new project as well
please get in touch with support regarding this before deleting the old
project.

View File

@ -0,0 +1,68 @@
---
description: Moving project to v2
keywords:
- hasura
- docs
- project
- upgrade
- move
- v2
sidebar_position: 18
---
# Manually moving Hasura Cloud v1.3 projects to Hasura v2.0
## Introduction
Hasura Cloud now creates new projects with Hasura `v2.0` by default. Due
to some underlying architectural changes in `v2.0`, existing projects
have not yet been upgraded to `v2.0`.
In the meanwhile it is possible to manually "move" your project to use
Hasura `v2.0`. You will lose any scheduled events and the history of
your processed events and async actions in the process though.
Do check the
[changelog](https://github.com/hasura/graphql-engine/releases) first to
see what changes and features have been introduced.
## Move existing v1.3 project to a v2.0 project
As it is not possible to actually upgrade your `v1.3` project to `v2.0`,
you will have to essentially create a new Hasura project with `v2.0` and
connect it with your database with the same Hasura metadata as in the
previous project.
### Step 1: Export metadata from existing project
See [exporting metadata](/graphql/core/migrations/manage-metadata.mdx) to get a copy of the
current Hasura metadata on your project.
Do ensure no further changes are made to the Hasura metadata post this.
### Step 2: Create a v2.0 Cloud project
See `Step 1` of [creating projects](/graphql/cloud/projects/create.mdx) to create a new
Hasura Cloud `v2.0` project.
### Step 3: Connect your database with the name **default** to the new project
See `Step 2` of [creating projects](/graphql/cloud/projects/create.mdx) to connect your
existing database to the new project. Please ensure you set the database
name as `default`.
:::info Note
After connecting a database to a `v2.0` project it will not be usable
with a `v1.3` project. Hence it is recommended to stop your `v1.3`
project before doing this.
:::
### Step 4: Apply the exported metadata to the new project
See [applying metadata](/graphql/core/migrations/manage-metadata.mdx) to apply the earlier
exported metadata to the new project.
Your GraphQL API should now be regenerated as in the earlier `v1.3`
project.

View File

@ -0,0 +1,266 @@
---
description: Updating v1 Cloud project to v2
keywords:
- hasura
- docs
- project
- upgrade
- update
- v2
sidebar_label: Updating v1.3 projects to v2.0
toc_max_heading_level: 5
sidebar_position: 16
---
import Thumbnail from "@site/src/components/Thumbnail";
# Updating Hasura Cloud v1.3 projects to Hasura v2.0
## Introduction
Hasura Cloud now creates new projects with Hasura `v2.0` by default. Due
to some behaviour and underlying architectural changes in `v2.0`,
existing projects have not been auto-updated to `v2.0`. You can update
your older `v1.3` projects to `v2.0` by following this guide.
(*You can find the older guide to do this process manually*
[here](/graphql/cloud/projects/move-project-v2-manual.mdx))
:::info Note
In case you happen to have a large number of past cron and event trigger
logs in your database, this might slow down the update to v2 and might
even cause DB errors in certain scenarios.
**It is highly recommended to clean up past cron and event trigger logs
data from the database before attempting the update if you have a lot of
historical data.**
You can take a dump of this data before cleaning up if you wish to keep
the log history.
:::
## What has changed?
Check the [core updating to v2.0 guide](/graphql/core/guides/upgrade-hasura-v2.mdx) and the
[release notes](https://github.com/hasura/graphql-engine/releases) to
see what new concepts, features and behaviour changes have been
introduced in Hasura `v2.0`.
Note that Hasura v2 Cloud projects' metadata is now stored in metadata
DBs managed by Hasura Cloud. Hence the new
`HASURA_GRAPHQL_METADATA_DATABASE_URL` env var is not configurable on
Hasura Cloud and is managed by Hasura Cloud itself.
See the section on [hasura_v1_v2_compatibility](/graphql/core/guides/upgrade-hasura-v2.mdx#hasura-v1-v2-compatibility) to use a Hasura v2 Cloud
project like a Hasura v1 Cloud project.
## Estimated time needed for update
Depending on the size of your project the update process should
typically take around **5-10 minutes** to be completed.
## Project availability during update
During the update process Hasura Cloud will need to place your project
in a "Maintenance mode" till the process is complete.
When **Cloud maintenance mode** is enabled, all Hasura Cloud project
actions such as updating env vars, transferring ownership, etc. will be
disabled.
When **Server maintenance mode** is enabled, all actions updating the
project metadata such as tracking tables, adding relationships, etc.
will be disabled.
Hence it is recommended to update your project at a time convenient to
all project collaborators.
Apart from the brief moments needed to enable/disable the server
maintenance mode, **your GraphQL API will continue to function during
this period.**
## Post-update steps
- As with most major updates, we would recommend you to monitor and
ensure all functionalities of your project are working as expected
post the update and the update did not cause any unexpected changes.
Do get in touch with us in case you notice anything unexpected.
- You can choose to unset the
`HASURA_GRAPHQL_V1_BOOLEAN_NULL_COLLAPSE` env var that was added to
your project during the update to preserve a `v1.3` behaviour that
was modified in `v2.0`. [See details](/graphql/core/guides/upgrade-hasura-v2.mdx#hasura-v2-null-where-change).
We recommend moving to the new behaviour by unsetting the env var
after verifying your project is not impacted by the change.
- Check the [Post update steps](/graphql/core/guides/upgrade-hasura-v2.mdx#hasura-v1-to-v2-post-update-steps)
section of the core updating to v2.0 guide for other changes you
should make post your project update.
## Update process
:::info Update option might not be currently enabled for all users
If you do not see the option to update your project as mentioned below, please reach out to support.
:::
To start the update, you should see a button called `Update` next to
your project on the Project list page as shown below:
<Thumbnail
src="/img/graphql/cloud/projects/update-project.png"
alt="Update project"
width="700px"
/>
Clicking on this button will trigger an update job that will perform a
few tasks to update your current `v1.3` project to `v2.0`.
Refer to the following task wise breakdown of the update job to
understand what the job will be doing and to check your project end
state in case of any failures.
Do reach out to support if you observe any issues with the update
process or run into any other problems post the v2.0 update.
### Update job sub-tasks
The following is a task wise breakdown of the update to v2.0 job.
Each task in the update job has a **rollback strategy** in case any
failures occur. If the rollback steps of any task fail, the project
might be in an unhealthy state in which case please get in touch with
support immediately for assistance.
#### Step 1: Initializing
##### Step 1.1: Validating
###### Sub-tasks:
- Enable cloud maintenance mode
- Ensure infrastructure for update is available
###### On Failure:
- Disable cloud maintenance mode
- **Project stays in v1.3**
##### Step 1.2: Enabling maintenance mode
###### Sub-tasks:
- Set `HASURA_GRAPHQL_ENABLE_MAINTENANCE_MODE` env var to enable
server maintenance mode
- Set `HASURA_GRAPHQL_V1_BOOLEAN_NULL_COLLAPSE` env var to `true` to
maintain `v1.3` behaviour for `null` values in `where` filters.
[(Know more)](/graphql/core/guides/upgrade-hasura-v2.mdx#hasura-v2-behaviour-changes)
###### On Failure:
- Unset `HASURA_GRAPHQL_V1_BOOLEAN_NULL_COLLAPSE` env var
- Unset `HASURA_GRAPHQL_ENABLE_MAINTENANCE_MODE` env var to disable
server maintenance mode
- Disable cloud maintenance mode
- **Project stays in v1.3**
#### Step 2: Updating project
##### Step 2.1: Migrating project metadata
###### Sub-tasks:
- Take a backup of server metadata from user database & move metadata
to cloud metadata database
###### On Failure:
- Unset `HASURA_GRAPHQL_V1_BOOLEAN_NULL_COLLAPSE` env var
- Unset `HASURA_GRAPHQL_ENABLE_MAINTENANCE_MODE` env var to disable
server maintenance mode
- Disable cloud maintenance mode
- **Project stays in v1.3**
##### Step 2.2: Creating v2.0 instance
###### Sub-tasks:
- Create `v2.0` instance
- Start routing requests to `v2.0` instance
###### On Failure:
- Start routing requests back to `v1.3` instance
- Unset `HASURA_GRAPHQL_ENABLE_MAINTENANCE_MODE` env var to disable
server maintenance mode
- Disable cloud maintenance mode
- **Project stays in v1.3**
##### Step 2.3: Migrating pending events, async actions data
###### Sub-tasks:
- Send signal to shutdown `v1.3` instance
- Wait for `v1.3` to gracefully shutdown after completing processing
of any in-flight events
- Migrate pending events, async actions data to cloud metadata
database
###### On Failure:
- Restart `v1.3` instance
- Start routing requests back to `v1.3` instance
- Unset `HASURA_GRAPHQL_ENABLE_MAINTENANCE_MODE` env var to disable
server maintenance mode
- Disable cloud maintenance mode
- **Project stays in v1.3**
##### Step 2.4: Migrating processed events, async actions data {#v2-update-migrate-invocation-logs}
###### Sub-tasks:
- Migrate invocation logs of processed events, async actions to cloud
metadata database
###### On Failure:
- **No action taken. Job continues to next task**
- Invocation logs of already processed events, async actions are not
migrated. Contact support to assist with a manual migration of the
logs if needed
#### Step 3: Validating update
##### Step 3.1: Disabling maintenance mode {#v2-update-disable-maintenance-mode}
###### Sub-tasks:
- Unset `HASURA_GRAPHQL_ENABLE_MAINTENANCE_MODE` env var to disable
server maintenance mode
- Disable cloud maintenance mode
###### On Failure:
- **No action taken. Job continues to next task**
- Server maintenance mode can be disabled manually by setting
`HASURA_GRAPHQL_ENABLE_MAINTENANCE_MODE` env var to `false`
- Contact support if your project is in an unexpected state
##### Step 3.2: Check metadata consistency {#v2-update-check-consistency}
###### Sub-tasks:
- Check if metadata is consistent
###### On Failure:
- **No action taken. Job continues to next task**
- Check your project metadata status on the console *(Settings (⚙) ->
Metadata status)* and attempt reloading metadata if there is an
unexpected inconsistency reported. Contact support if the
inconsistency doesn't go away on metadata reload.
#### 4. Project update complete
Project update to `v2.0` is completed.

View File

@ -0,0 +1,83 @@
---
description: Transferring Ownership on Hasura Cloud
keywords:
- hasura
- docs
- project
- team
- ownership transfer
sidebar_label: Transfer ownership
sidebar_position: 4
---
import Thumbnail from "@site/src/components/Thumbnail";
# Project ownership transfer
## Introduction
You can transfer ownership of your project to another user. After the
ownership is transferred successfully, the original owner will lose all
access to the project.
:::info Note
If the project is on the `Standard` (pay-as-you-go) tier, the new owner
will pay for the entire data usage for the month in which the ownership
is transferred.
:::
## Send an ownership transfer invitation
Go to the project settings page and scroll to the bottom. Enter the
email of the user you want to transfer the project ownership to.
<Thumbnail
src="/img/graphql/cloud/projects/transfer-ownership.png"
alt="Transfer Project Ownership"
width="1146px"
/>
## Revoke an ownership transfer invitation
To revoke the ownership transfer invitation, click on the `Revoke`
button right next to the email of the invitee.
<Thumbnail
src="/img/graphql/cloud/projects/remove-ownership.png"
alt="Remove transfer ownership invite"
width="1146px"
/>
## Resend an ownership transfer invitation
To resend the ownership transfer invitation, click on the resend symbol
right next to the email of the invitee.
<Thumbnail
src="/img/graphql/cloud/projects/resent-ownership.png"
alt="Resend transfer ownership invite"
width="1146px"
/>
## Invitations
You can see the projects that you have been invited to become the owner
of, on the project listing page.
<Thumbnail
src="/img/graphql/cloud/projects/project-ownership-invitation.png"
alt="Projects invited to own"
width="1146px"
/>
You can accept an invitation by clicking on the `Accept` button.
:::info Note
If the project is on the `Standard` (pay-as-you-go) tier, the new owner
must have an active card associated with their Hasura Cloud account to
accept the invitation.
:::

View File

@ -0,0 +1,87 @@
---
description: Hasura Cloud pricing
keywords:
- hasura
- docs
- cloud
- pricing
sidebar_position: 8
---
import Thumbnail from "@site/src/components/Thumbnail";
# Switching pricing plans
## Introduction
Hasura has different pricing plans that you can choose from based on
your requirements. This page explains how to switch between these plans.
## Pricing plans
There are three different pricing plans that you can chose from:
- Free
- Standard (Pay-as-you-go)
- Enterprise
:::info Note
For details and a full list of features for each of these plans, check
out our [pricing page](https://hasura.io/pricing/).
:::
## View current pricing plans for projects
By clicking on the `Projects` tab, you can see all your projects and
what plan they are currently on:
<Thumbnail
src="/img/graphql/cloud/projects/project-pricing-plans.png"
alt="Billing overview"
width="1200px"
/>
## Switching pricing plans
### Switch from **Free** to **Standard** tier
Once the `Free` tier data limit is exhausted, the project becomes
inactive. In order to keep it active, you can switch to the `Standard`
plan.
Go to `Projects` and click on the project you'd like to change.
Now click on the `Usage tab`. To upgrade to the `Standard` plan, click
on the `Upgrade` button:
<Thumbnail
src="/img/graphql/cloud/projects/upgrade-to-paid-plan.png"
alt="Upgrade to the Standard plan"
width="1200px"
/>
Your project is now running on the `Standard` plan.
### Switch from **Standard** to **Free** tier
Go to `Projects` and click on the project you'd like to change.
Under the `General` tab, find the `Pricing tier` section and click on the edit icon on the right:
<Thumbnail
src="/img/graphql/cloud/projects/switch-to-free-plan.png"
alt="Switch from Standard to Free tier"
width="1200px"
/>
You'll be charged as per the `Standard` plan until the end of the day.
From the next day onwards, the project will be on the `Free` tier. If
the `Free` tier limit is exhausted, the project might become inactive.
### Switch to and from **Enterprise** tier
In order to upgrade to the `Enterprise` plan or to switch back to
another plan, please [contact our sales
team](https://hasura.io/contact-us/?type=hasuraenterprise).

View File

@ -0,0 +1,113 @@
---
description: Project deployment regions
keywords:
- hasura
- docs
- cloud
- regions
- project
- project regions
sidebar_position: 9
---
import Thumbnail from "@site/src/components/Thumbnail";
# Deployment regions
## Introduction
You can deploy Hasura Cloud projects in one of the supported regions
(more regions are coming soon). A project's region of deployment can be
selected while creating the project and it can be changed later from the
project details.
## Selecting the region while creating a project
Click on the `New Project` button on the project-list page. You can
select the project's region of deployment from the `Select a region`
dropdown.
<Thumbnail
src="/img/graphql/cloud/projects/regions-while-creation.png"
alt="select regions while project creation"
/>
## Changing region of an existing project
Go the the project details by clicking on the settings icon on your
project card in the project list.
<Thumbnail
src="/img/graphql/cloud/getting-started/project-manage.png"
alt="select regions while project creation"
width="900px"
/>
The `Region` field displays the project's current region of deployment.
For switching the region, click on the edit icon in the `Region` field.
<Thumbnail
src="/img/graphql/cloud/projects/region-edit-before.png"
alt="select regions while project creation"
/>
Choose a region of your choice and hit `Save`.
<Thumbnail
src="/img/graphql/cloud/projects/region-edit-after.png"
alt="save regions change"
/>
There might be a short downtime while your project is being moved to a
different region. If your database allows connections only from specific
IP addresses, make sure you add the Hasura Cloud IP of this new region
to the list of allowed IP addresses.
<Thumbnail
src="/img/graphql/cloud/projects/region-edit-hasura-cloud-ip.png"
alt="change region confirm box"
/>
:::info Note
Support for deploying a project in multiple regions is coming soon.
:::
:::info Temporary limitation for v2.0 projects
Due to an underlying architecture change, it is currently not possible
to change regions of already created `v2.0` projects. **Support for this
will be added in the very near future.**
In the meanwhile, as a workaround, you can "move" your project to a new
region by creating a new Hasura project in the region you wish and
connect it with your database with the same Hasura metadata as in the
previous project.
**Step 1: Export metadata from existing project**
See [exporting metadata](/graphql/core/migrations/manage-metadata.mdx#exporting-metadata) to get a copy of the
current Hasura metadata on your project.
Do ensure no further changes are made to the Hasura metadata post this.
**Step 2: Create a v2.0 Cloud project in your region**
See `Step 1` of [creating projects](/graphql/cloud/projects/create.mdx) to create a new
Hasura Cloud `v2.0` project in the region you wish.
**Step 3: Connect your database with the same name to the new project**
See `Step 2` of [creating projects](/graphql/cloud/projects/create.mdx) to connect your
existing database to the new project. Please ensure you set the same
database name as in the current project.
**Step 4: Apply the exported metadata to the new project**
See [applying metadata](/graphql/core/migrations/manage-metadata.mdx#applying-metadata) to apply the earlier
exported metadata to the new project.
Your GraphQL API should now be regenerated as in the earlier project.
:::

View File

@ -0,0 +1,66 @@
---
description: Securing projects on Hasura Cloud
keywords:
- hasura
- docs
- project
sidebar_position: 7
---
import Thumbnail from "@site/src/components/Thumbnail";
# Securing projects
## Introduction
To make sure that your GraphQL endpoint is not publicly accessible, a
randomly generated admin secret key is added by default to your project
at the time of project creation.
## Updating the admin secret
### Step 1: Go to settings
On the project overview, click on the settings icon on the top right of
the relevant project.
<Thumbnail
src="/img/graphql/cloud/projects/secure-settings.png"
alt="Go to settings"
width="865px"
/>
### Step 2: Navigate to env vars
On the `Env vars` tab, you will see the `HASURA_GRAPHQL_ADMIN_SECRET`
env var.
<Thumbnail
src="/img/graphql/cloud/projects/secure-admin-envvar.png"
alt="Navigate to env vars"
width="1100px"
/>
### Step 3: Update admin secret
Click on the `HASURA_GRAPHQL_ADMIN_SECRET` env var to update the value.
<Thumbnail
src="/img/graphql/cloud/projects/secure-update-envvar.png"
alt="Set admin secret"
width="1100px"
/>
## Accessing Hasura
When you launch the console from the Hasura Cloud dashboard, you'll be
authenticated as an admin. If you want to make API calls from outside
the console, you need to pass the admin secret as the <em>x-hasura-admin-secret</em> request header.
:::info Note
The admin secret should be treated like a password i.e. it should be
kept secret and shouldn't be passed from frontend clients. Refer
[this](/graphql/core/auth/authentication/index.mdx) to set up user authentication.
:::

View File

@ -0,0 +1,242 @@
---
description: Hasura Cloud Vercel Integration
keywords:
- hasura
- cloud
- docs
- vercel
- integration
sidebar_position: 13
---
import Thumbnail from "@site/src/components/Thumbnail";
# Vercel Integration
## Introduction
You can connect your front-end [Vercel](https://vercel.com/dashboard)
applications with a [Hasura Cloud](https://cloud.hasura.io/) project.
This integration does the following:
- Creates a new Hasura Cloud project which can serve as a unified
back-end for one or more front-end applications i.e. Vercel Projects
depending on the scope of the integration.
- Configures necessary project settings i.e setting environment variables and exposing them on the client side.
(Check the [list](#vercel-environment-variables) of all environment variables set).
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/hasura-vercel.png"
alt="Hasura Vercel Integration"
width="1146px"
/>
## Creating an Integration
You can configure the [official Hasura integration](https://vercel.com/integrations/hasura-v1) with your Vercel account.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/hasura-vercel-integration.png"
alt="Hasura Official Integration page"
width="1146px"
/>
### Step 0: Prerequisites
This integration requires you to have a Vercel account along with existing Vercel applications.
### Step 1: Initiate Integration
- Navigate to the [official Hasura integration](https://vercel.com/integrations/hasura-v1) page and click on `Add Integration`.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/add-integration-button.png"
alt="Add Integration Button"
width="1146px"
/>
### Step 2: Select Vercel account
- Select the account (personal or team) you want to install the integration on and click `Continue`.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/vercel-account-scope.png"
alt="Vercel Account Scope"
width="400px"
/>
### Step 3: Select Integration Scope
- Select the integration scope.
| Scope | Description |
|-------------------|----------------------------------------------------|
| All Projects | Configures all Vercel applications in the account. |
| Specific Projects | Configures only a subset of applications. |
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/selected-projects.png"
alt="Vercel selected projects"
width="400px"
/>
- Click on `Add Integration` and a new window should pop up for the further steps specific to Hasura Cloud.
### Step 4: Configure Hasura Cloud
- You'll be directed towards a Hasura Cloud signup or login page. This is skipped if you are already logged-in to Hasura Cloud.
- Once you are logged in, a Hasura Cloud project is created for the integration and the required
[environment variables](#vercel-environment-variables) are set for each Vercel project in the scope.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/setup-progress.png"
alt="Setup Progress"
width="600px"
/>
- Click on the first link to navigate to your Hasura Cloud project Console to configure your GraphQL API and connect to a database.
Check out the section on [database setup](/graphql/cloud/projects/create.mdx#cloud-projects-db-setup) on how to do this.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/visit-console.png"
alt="Visit Console Button"
width="600px"
/>
- Click on `Install Integration` to install your integration.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/install-integration.png"
alt="Finish Setup Button"
width="600px"
/>
:::info Note
Your integration will only be successfully configured upon clicking the
`Install Integration` button.
:::
### Step 5: Check finished setup
- The Integration is now complete. You'll be redirected to the Vercel Dashboard.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/integration-complete.png"
alt="Integration Complete"
width="1146px"
/>
- Click on `Configure` to navigate to Cloud Dashboard to see the latest project we created for you. This will be a project with the tag `Vercel` on it.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/vercel-tag-project.png"
alt="Integration Complete"
width="1146px"
/>
- To change the scope of you integration, you can click on `Manage Access` to add/remove vercel applications from the integration.
Check out the [Adding and removing projects from the Scope of Integration](#vercel-change-scope) section for more details.
## Environment variables {#vercel-environment-variables}
- List of Hasura Cloud environment variables configured by the integration for each Vercel application in the scope of the integration:
| Title | Description |
|-------------------------------------|-------------------------------------------------------------------|
| HASURA_PROJECT_ENDPOINT | GraphQL API endpoint of the Hasura Cloud project. |
| NEXT_PUBLIC_HASURA_PROJECT_ENDPOINT | GraphQL API endpoint to be exposed on the Next.js browser client. |
| HASURA_ADMIN_SECRET | Admin secret key to access your GraphQL API. |
- You can check the environment variables configured by the integration for you in the respective Vercel Project's settings
on Vercel dashboard. These are set up for `Development`, `Preview` and `Production` environments.
Check the [Vercel docs](https://vercel.com/docs/concepts/projects/environment-variables) for environment variables for further reference.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/environment-variables.png"
alt="Environment variables"
width="1146px"
/>
:::info Note
- If a [custom domain](/graphql/cloud/projects/domains.mdx) is added to the Hasura Cloud project, you'll have to set this custom value to
`HASURA_PROJECT_ENDPOINT` and `NEXT_HASURA_PROJECT_ENDPOINT` manually in the respective Vercel project's settings.
- Similarly if the Hasura Cloud project's admin secret is changed, you will have to edit the `HASURA_ADMIN_SECRET` manually in the respective Vercel project's settings.
:::
## Adding and removing projects from the Scope of Integration {#vercel-change-scope}
Once the integration is installed, you can change the scope of the
integration.
- Navigate to the installed integration page and click on `Manage Access`. This will show you the current status of the integration,
i.e the projects that are currently configured.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/manage-access-button.png"
alt="Manage Access Button"
width="1146px"
/>
- If the integration is installed for `All Projects`, you can change the scope to `Specific Projects` and select the projects from the
dropdown you want to keep the integration on. If installed for `Specific Projects`, you can add individual projects from the
dropdown or remove them from the list.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/manage-access-projects.png"
alt="Manage Access For Projects"
width="400px"
/>
- Click on `Save` to save the changes.
:::info Note
Hasura Cloud project's environment variables will be automatically set
for the added projects and will be removed for the removed projects.
:::
## Removing an Integration
- To remove the configured integration, navigate to the `Integrations` sections in Vercel Dashboard and spot the Hasura integration in the list.
Click on `Manage` to navigate to the integration page.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/integration-tab.png"
alt="Vercel Integration Tab"
width="1146px"
/>
- Scroll down to the bottom of the page and click on `Remove Integration`. Vercel will remove the integration along with
the set environment variables from the applications.
<Thumbnail
src="/img/graphql/cloud/integrations/vercel/remove-integration.png"
alt="Remove Vercel Integration"
width="1146px"
/>
Your Hasura Cloud project will not be affected.
## Support
File a support ticket by navigating to the [Help & Support](https://cloud.hasura.io/support/create-ticket) tab on the
Hasura Cloud dashboard if you face any issues.

View File

@ -0,0 +1,131 @@
---
description: Hasura Cloud Query Tags
keywords:
- hasura
- docs
- cloud
- query-tags
- monitoring
sidebar_position: 9
---
# Query Tags
## Introduction
Query Tags are SQL comments which are made up of `(key=value)` pairs that are appended to the SQL statements generated by Hasura for GraphQL operations. This enables the ability to get some application context in the database logs and also use native database monitoring tools (_e.g. pganalyze_) for better performance analysis.
Example:
When the following query is sent to Hasura
```graphql
query GetChild {
child {
name
}
}
```
Hasura attaches query tags (_unless disabled_) to the generated SQL statement it sends to the database.
```sql
SELECT name FROM child /* request_id=487c2ed5-08a4-429a-b0e0-4666a82e3cc6, field_name=child, operation_name=GetChild */
```
## Formats of Query Tags
The format of the Query Tags describes how the <em>(Key,Value)</em> pairs are constructed. Currently we support two formats of Query Tags:
1. Standard (`standard`)
2. SQLCommenter (`sqlcommenter`)
### Standard
This format makes a collection of <em>key=value</em> pairs and separates each pair by a comma `,` . **This is the default format for Query Tags**
For eg:
```sql
SELECT name FROM child /* request_id=487c2ed5-08a4-429a-b0e0-4666a82e3cc6, field_name=child, parameterized_query_hash=b2a71ce23928ca7f0021f9060e5d590e9f9bb00f, operation_name=GetChild */
```
### SQLCommenter
The specification for this format is defined at <https://google.github.io/sqlcommenter/spec/>
For eg:
```sql
SELECT name FROM child /* field_name='child', operation_name='GetChild', parameterized_query_hash='b2a71ce23928ca7f0021f9060e5d590e9f9bb00f' , request_id='487c2ed5-08a4-429a-b0e0-4666a82e3cc6' */
```
## Information in Query Tags
The following information is present in query tags for the GraphQL operations.
### Query and Mutation
1. Request ID (`request_id`)
2. Operation Name (`operation_name`)
3. (Root) field name (alias if provided) (`field_name`)
4. Parameterized Query Hash (`parameterized_query_hash`)
### Subscriptions
1. (Root) field name (alias if provided) (`field_name`)
2. Parameterized Query Hash (`parameterized_query_hash`)
## Metadata Specification
```yaml
sources:
name: # Name of the source
configuration:
query_tags: # Optional Field
disabled: # Optional Field | Type: Bool | Values: true or false
format: # Optinal Field | Values: standard or sqlcommenter
```
:::info
Note The default format for the Query Tags is `Standard` and it is enabled by default for all sources.
:::
In the above metadata spec:
1. The <em>query_tags</em> field is optional. If the <em>query_tags</em> field is not present for a source, then query tags is enabled for the source and the format used is <em>standard</em>.
2. To disable query tags for any source, set the value of <em>disabled</em> field to <em>true</em>.
3. To override the default format (<em>Standard</em>) for query tags, use the <em>format</em> field.
## Example Metadata Specification
```yaml
sources:
- name: test_db
configuration:
query_tags:
disabled: true
- name: hasura_db_herokou
configuration:
query_tags:
format: sqlcommenter
- name: hasura_db_2
configuration:
query_tags:
format: standard
disabled: true
```
## Metadata API To Set Query Tags
```yaml
type: "set_query_tags"
args:
source_name: # Name of the source | Required
disabled: # Optional Field | Type: Bool | Values: true or false
format: # Optional Field | Values: standard or sqlcommenter
```

View File

@ -0,0 +1,203 @@
---
description: Hasura Cloud read replicas
keywords:
- hasura
- docs
- cloud
- read replicas
- connections
- pool
sidebar_position: 6
---
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
import Thumbnail from "@site/src/components/Thumbnail";
# Read replicas
Hasura Cloud can load balance queries and subscriptions across *read replicas* while sending all mutations and metadata API calls to the primary.
## Adding read replica URLs
### Postgres
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Head to `Data -> Manage -> <db-name> -> Edit`
<Thumbnail
src="/img/graphql/cloud/read-replicas/connect-db-with-replica.png"
alt="Connect database with read replica"
width="1000px"
/>
</TabItem>
<TabItem value="cli" label="CLI">
You can add *read replicas* for a database by adding their config to the `/metadata/databases/database.yaml` file:
```yaml {11-17}
- name: <db-name>
kind: postgres
configuration:
connection_info:
database_url:
from_env: <DATABASE_URL_ENV>
pool_settings:
idle_timeout: 180
max_connections: 50
retries: 1
read_replicas:
- database_url:
from_env: <DATABASE_REPLICA_URL_ENV>
pool_settings:
idle_timeout: 180
max_connections: 50
retries: 1
```
Apply the metadata by running:
```yaml
hasura metadata apply
```
</TabItem>
<TabItem value="api" label="API">
You can add *read replicas* for a database using the [pg_add_source](/graphql/core/api-reference/metadata-api/source.mdx#metadata-pg-add-source) metadata API.
```http {16-27}
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type":"pg_add_source",
"args":{
"name":"<db_name>",
"replace_configuration":true,
"configuration":{
"connection_info":{
"database_url":{
"from_env":"<DATABASE_URL_ENV>"
}
},
"read_replicas":[
{
"database_url":{
"from_env":"<DATABASE_REPLICA_URL_ENV>"
},
"pool_settings":{
"retries":1,
"idle_timeout":180,
"max_connections":50
}
}
]
}
}
}
```
</TabItem>
</Tabs>
:::info For existing v1.3 projects
If you have configured your Postgres instances with replicas; then the replica URLs can be added to Hasura using the following environment variable in your project ENV Vars tab:
```bash
HASURA_GRAPHQL_READ_REPLICA_URLS=postgres://user:password@replica-host:5432/db
```
In the case of multiple replicas, you can add the URLs of each replica as comma-separated values.
Additional environment variables for *read replicas* specifically:
`HASURA_GRAPHQL_CONNECTIONS_PER_READ_REPLICA`
`HASURA_GRAPHQL_STRIPES_PER_READ_REPLICA`
:::
### MS SQL Server
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Support will be added soon
</TabItem>
<TabItem value="cli" label="CLI">
You can add *read replicas* for a database by adding their config to the `/metadata/databases/database.yaml` file:
```yaml {10-15}
- name: <db-name>
kind: mssql
configuration:
connection_info:
connection_string:
from_env: <DATABASE_URL_ENV>
pool_settings:
idle_timeout: 180
max_connections: 50
read_replicas:
- connection_string:
from_env: <DATABASE_REPLICA_URL_ENV>
pool_settings:
idle_timeout: 25,
max_connections: 100
```
Apply the metadata by running:
```yaml
hasura metadata apply
```
</TabItem>
<TabItem value="api" label="API">
You can add *read replicas* for a database using the [mssql_add_source](/graphql/core/api-reference/metadata-api/source.mdx#mssql-add-source) metadata API.
```http {19-29}
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type":"mssql_add_source",
"args":{
"name":"<db_name>",
"replace_configuration":true,
"configuration":{
"connection_info":{
"connection_string":{
"from_env":"<DATABASE_URL_ENV>"
},
"pool_settings":{
"max_connections":50,
"idle_timeout":180
},
"read_replicas":[
{
"connection_string":{
"from_env":"<DATABASE_REPLICA_URL_ENV>"
},
"pool_settings":{
"idle_timeout":180,
"max_connections":50
}
}
]
}
}
}
}
```
</TabItem>
</Tabs>

View File

@ -0,0 +1,101 @@
---
description: Hasura Cloud regression tests
keywords:
- hasura
- docs
- cloud
- reliability
- regression
- migration
sidebar_position: 5
---
import Thumbnail from "@site/src/components/Thumbnail";
# Regression tests
## Introduction
Hasura Cloud includes a comprehensive test bench that lets you seamlessly compile a test suite on each project, executable on any GraphQL Engine instance (ex: staging, prod).
Here's a reference development workflow that is enabled by Hasura Cloud:
1. Build your database schema and configure Hasura as required by your frontend apps or public GraphQL API.
2. Deploy changes to production after testing them.
3. Create a regression suite on production.
4. Iterate on your GraphQL schema to support new features or edits.
- Test changes in your dev instance against the production instances regression test suite. Fix any issues highlighted by the tests or plan to communicate regressions to affected stakeholders.
5. Run all changes through a CI/CD pipeline
- Run Regression tests programmatically for all changes in the team
6. Promote changes to prod
<Thumbnail
src="/img/graphql/cloud/reliability/regression-testing-diagram.png"
alt="Regression testing process diagram"
/>
## Manage test suites
Each Hasura Cloud project can be configured with a separate test suite. Ideally, you want to create a regression test suite on an project which has received requests with operations youd like to continue supporting or ensure are not “broken” - production or a shared QA project which receives operations in your app or, if you have a public GraphQL API, those from your consumers.
<Thumbnail
src="/img/graphql/cloud/reliability/regression-tests-suites.png"
alt="Manage regression test suites"
/>
## Quick-create tests
Add important operations to your test suite with one click by adding them from your project's operation history:
<Thumbnail
src="/img/graphql/cloud/reliability/regression-tests-add-operations.png"
alt="Add tests to regression test suites"
/>
## Run test suites
A good development workflow would require that tests be run 1) early in the dev process, and 2) automatically with changes, to ensure changes to the schema don't break functionality.
A test suite configured on a Hasura Cloud project can be run on the same instance or any other Hasura Cloud project registered to your team, including local ones. This is how we recommend that you incorporate regression tests into your GraphQL engine workflows:
### Run regression tests manually
Lets say youre a developer iterating on a feature and, as part of your work, need to modify your Postgres schema or the Hasura configuration. It is likely that you are doing so by running the console via the Hasura CLI to generate migrations that you can version control. Before committing your changes in git, you should run tests to get an early warning for potential regressions. Your team may want to designate the test suite from your production instance (or a suitable alternative) as the default suite to be used for this, and you can choose to run this test suite on your local or development instance.
<Thumbnail
src="/img/graphql/cloud/reliability/regressions-run-prod-tests-on-dev.png"
alt="Run regression tests"
/>
For example, if the column title (in a typical authors and articles schema) has been modified as part of a feature iteration. Assuming the operation from the previous example is part of the test suite on production, heres how the feedback on this change looks like:
<Thumbnail
src="/img/graphql/cloud/reliability/regression-tests-results.png"
alt="Regression test results"
/>
As you can see, one of the tests fails because it expects a field, title, to be part of the type articles - which is something our proposed change just modified and removed support for.
### Run regression tests in CI/CD flow
<Thumbnail
src="/img/graphql/cloud/reliability/regression-tests-run-cli.png"
alt="Run regression tests via CLI"
/>
This command will fetch the entire test suite from Hasura Pro and run the tests against given endpoint using the admin secret and report the result on the terminal. The test run and the results will also be available on the Hasura Console.
You can use the Hasura Pro CLI to programmatically trigger execution of a test suite in your automated testing setup, typically in CI scripts.
In order to communicate with Hasuras APIs, the CLI needs to be configured with an API access token (which you can create via your Hasura Cloud settings). If you want to set the token up on a non-interactive environment, like a CI pipeline, you can obtain a token and then add to `~/.hasura/pro_config.yaml` with the following format:
```bash
pat: <token>
```
## View test suite results
<Thumbnail
src="/img/graphql/cloud/reliability/regression-tests-past-runs.png"
alt="Regression tests past results"
/>

View File

@ -0,0 +1,104 @@
---
description: Query response caching in Hasura Cloud
keywords:
- hasura
- docs
- cloud
- response
- caching
sidebar_position: 7
---
# Query response caching
## Introduction
Hasura Cloud provides support for caching query responses, in order to improve performance for queries which are executed frequently.
This includes actions and queries against remote schemas.
Cached responses are stored in for a period of time in a LRU (least-recently used) cache, and removed from the cache as needed based on usage.
A query's response can be cached only if the following conditions hold:
- The query does **not** make use of ``remote schemas`` that has ``forward_client_headers`` (see [RemoteSchemaDef](/graphql/core/api-reference/syntax-defs.mdx#remoteschemadef)) set to ``true``.
- The query **isn't** an `Action` that has `forward_client_headers` (see [ActionDefinition](/graphql/core/api-reference/syntax-defs.mdx#actiondefinition)) set to `true`.
- The response JSON is **under** 100KB in size
:::tip Support
Query response caching is available for Hasura Cloud projects on the `Free` tier and above.
:::
## Enable caching
In order to enable caching for a query response, or to return an existing response from the cache (if one exists), simply add the `@cached` directive to your query:
```graphql
query MyCachedQuery @cached {
users {
id
name
}
}
```
If the response was cached successfully, the HTTP response will include a `Cache-Control` header, whose value (`max-age={SECONDS}`) indicates the maximum number of seconds for the returned response to remain in the cache.
## Controlling cache lifetime
The maximum lifetime of an entry in the cache can be controlled using the `ttl` argument to the `@cached` query directive. The value is an integer number of seconds:
```graphql
query MyCachedQuery @cached(ttl: 120) {
users {
id
name
}
}
```
By default, a response will be cached with a maximum lifetime of 60 seconds. The maximum allowed value is 300 seconds (5 minutes).
## Forcing the cache to refresh
The cache entry can be forced to refresh, regardless of the maximum lifetime using the `refresh` argument to `@cached`. The value is a boolean:
```graphql
query MyCachedQuery @cached(refresh: true) {
users {
id
name
}
}
```
## Rate Limiting
Cache writes are rate limited, with a rate depending on your plan. The rate limit is based on the total number of bytes written to the cache in a sliding window. If you exceed the rate limit, the HTTP response will indicate this with a warning header: "Warning: 199 - cache-store-capacity-exceeded".
## Session variables
Queries using session variables are able to be cached.
Please note:
- A session variable will only influence the cache key for a query if it referenced by the execution plan. In practice this means that session variables are only factored into cache keys if they are referenced in the permissions for a query. See <https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/permission/>
## Response headers
When you enable caching for a query, the following headers should be returned in the HTTP response:
- `X-Hasura-Query-Cache-Key` - Key for cached query response, unique to this query
- `X-Hasura-Query-Family-Cache-Key` - Key for the family of queries (ignores variable values)
- `Cache-Control` - Value: `max-age={SECONDS}` - Seconds until cache expires for query
These can be used by your application as you see fit, as well as by the cache clearing endpoints.
## Clearing items from the cache
A set of endpoints exist to clear items from the cache for the current project:
- `POST /pro/cache/clear` -- Clears all
- `POST /pro/cache/clear?key={HASH}` -- Clears key hash
- `POST /pro/cache/clear?family={FAMILY}` -- Clears items that match query family (ignoring variables)

View File

@ -0,0 +1,4 @@
{
"label": "API Security",
"position": 4
}

View File

@ -0,0 +1,36 @@
---
description: Hasura Cloud allow lists
keywords:
- hasura
- docs
- cloud
- security
- allow
sidebar_position: 1
---
import Thumbnail from "@site/src/components/Thumbnail";
# Allow lists
## Introduction
You can specify a list of safe operations (GraphQL queries, mutations or subscriptions) for your project. This list restricts your project's GraphQL Engine to execute only queries that are present in the list.
## Manage the allow list
The manager view offers inspection, export, or removal of operations in the allow list:
<Thumbnail
src="/img/graphql/cloud/security/pro-tabs-allowlist.png"
alt="Hasura Cloud Console allow list tab"
/>
## Quick-create allowed operations
This Pro feature lets you add to the allow list with one click from the record of past operations. (With Core, allow lists must be [managed manually](/graphql/core/deployment/allow-list.mdx#allow-list)).
<Thumbnail
src="/img/graphql/cloud/security/allowlist-add-new-op.png"
alt="Hasura Cloud Console create new allowed operation"
/>

View File

@ -0,0 +1,182 @@
---
description: Hasura Cloud API limits
keywords:
- hasura
- docs
- cloud
- security
- limits
sidebar_position: 2
---
import Thumbnail from "@site/src/components/Thumbnail";
# API limits
## Introduction
Limiting the depth and/or rate of API requests can help prevent API performance issues caused by malicious or poorly implemented queries.
## API limit types
API limits are defined by **role** (e.g. anonymous, user) and can restrict request rate, depth, or both. Unique request parameters can include IP address or session variables (_x-hasura-user-id_, _x-hasura-org-id_, etc.)
### Rate limits
Restricts number of GraphQL operations per minute. This uses a sliding window approach. This means whenever Hasura Pro receives a request, it will count the rate of that client starting from the current time to last one minute.
By default, the rate-limit happens on the `role_name` i.e the value provided in `X-HASURA-ROLE`. But you can also combine additional unique parameters for more granularity.
The Unique Parameters that are provided are:
1. IP Address
2. Session Variables
You can choose any one of the above parameters to rate limit the requests.
**Note**: If you set a `Unique Parameter` then the combination of both the `role_name` and the `Unique Parameter` will be used to rate-limit requests.
Example:
If you rate-limit using the `role_name` and set the unique parameter for the rate-limit as `IP Address`, then rate-limit will be applied depending on both those parameteres. i.e If the requests come from a different role but same IP address will **NOT** be rate limited
### Depth limits
Restricts a GraphQL operation based on its depth, preventing deeply nested queries.
### Node limits
Restricts a GraphQL operation based on the number of nodes. This helps in limiting the number of different pieces of related data to be fetched.
A node is defined as a field with a selection set.
For example, in the below query the number of nodes is 3 and they are `author`, `articles` and `homepage_entries`.
```graphql
{
author {
name
articles {
id
title
}
}
homepage_entries {
article_id
}
}
```
### Time limits
Restricts the time that a GraphQL operation is allowed to take. The duration is specified in seconds.
Any upstream database queries are also cancelled for supported sources. Currently, cancellation only works for Postgres sources.
## Manage API limits
API limits can have a _global_ or _per role_ configuration. If an incoming request does not contain a valid role then the global limit is applied.
<Thumbnail
src="/img/graphql/cloud/security/pro-tab-apilimits.png"
alt="Hasura Cloud Console api limit tab"
/>
:::info Admin & IntrospectionQuery exemptions
All API limits are **not** applied for the admin role, and depth limits are **NOT** applied to introspection queries.
:::
## Metadata Specification
Hasura provides two metadata API's to manage API limits
### Setting API Limits
You can configure api limits using the `set_api_limits` API.
```yaml
type: set_api_limits
args:
disabled: # Optional Field (Either True or False, The value is False by default)
depth_limit: # Optional API Limit
global: # Mandatory Field
per_role: # Optional Field
<role_name>: <limit value> # Eg: user: 5
node_limit: # Optional API Limit
global: # Mandatory Field
per_role: # Optional Field
<role_name>: <limit value> # Eg: user: 5
rate_limit: # Optional API Limit
global: # Mandatory Field
unique_params: # Optional Field, Can either be IP Address or Session variables
max_reqs_per_min: # Mandatory Field
per_role: # Optional Field
<role_name>:
max_reqs_per_min: # Mandatory Field
unique_params: # Optional Field
time_limit: # Optional API Limit
global: # Mandatory Field
per_role: # Optional Field
<role_name>: <limit value> # Eg: user: 5
```
In the above metadata spec:
1. The API Limits are `Enabled` by default, i.e the default value of `disabled` is `False`
2. When `disabled` is `False` and none of the API Limits are set then no API limits are applied.
3. The `global` field in all the API Limits is mandatory, and is used as the default API limit if no `per_role` option is set for the user.
4. The `per_role` can be used to override the `global` API Limit value
5. For `rate_limit` if no `unique_params` are provided then, the requests will be rate-limited on the `role_name` i.e the `X-HASURA-ROLE` that is used to issue the request
Example Metadata Spec:
```yaml
type: set_api_limits
args:
disabled: false
depth_limit:
global: 5
per_role:
user: 7
node_limit:
global: 3
per_role:
user: 10
rate_limit:
global:
unique_params: IP
max_reqs_per_min: 10
per_role:
anonymous:
max_reqs_per_min: 10
unique_params: "ip"
user:
unique_params:
- x-hasura-user-id
- x-hasura-team-id
max_reqs_per_min: 20
time_limit:
global: 10
per_role:
user: 5
```
### Removing API Limits
You can remove **all** the api limits that have been set using `remove_api_limit` API.
```yaml
type: remove_api_limits
args: {}
```

View File

@ -0,0 +1,31 @@
---
description: Hasura Cloud disable GraphQL introspection
keywords:
- hasura
- docs
- cloud
- security
- introspection
- disable
- GraphQL
sidebar_position: 3
---
import Thumbnail from "@site/src/components/Thumbnail";
# Disable GraphQL introspection
## Introduction
The GraphQL engine by default enables [GraphQL Schema Introspection](https://spec.graphql.org/June2018/#sec-Schema-Introspection) which gives full information about the schema and may not be desired in production.
To avoid this, you can disable GraphQL introspection on a per-role basis.
## Disabling GraphQL introspection for a role
Introspection can be disabled for a role as shown below:
<Thumbnail
src="/img/graphql/cloud/security/disable-introspection.png"
alt="Hasura Cloud Console Schema Introspection tab"
/>

View File

@ -0,0 +1,28 @@
---
description: Hasura Cloud API Security
keywords:
- hasura
- docs
- cloud
- security
- API security
- secure
slug: index
sidebar_label: API security
---
import Thumbnail from "@site/src/components/Thumbnail";
# API Security
## Introduction
All API security-related features can be found under the `Security` tab in the API explorer page of Hasura console.
<Thumbnail src="/img/graphql/cloud/security/security.png" alt="Security" />
## Features
- [Allow Lists](/graphql/cloud/security/allow-lists.mdx)
- [API Limits](/graphql/cloud/security/api-limits.mdx)
- [Disable GraphQL Introspection](/graphql/cloud/security/disable-graphql-introspection.mdx)

View File

@ -0,0 +1,49 @@
---
description: Hasura Cloud multiple JWT Secrets
keywords:
- hasura
- docs
- cloud
- security
- allow
- multiple
- JWT
- secrets
sidebar_position: 5
---
# Multiple JWT Secrets
## Introduction
You can configure Hasura with a list of JWT Secrets so that you can integrate with different JWT issuers.
This is useful when you have different authentication providers using the same Hasura infrastructure.
## How to use multiple jwt secrets
Multiple JWT secrets can be provided in the env var `HASURA_GRAPHQL_JWT_SECRETS` which takes a JSON array of JWT secret objects.
Bearer Tokens are authenticated against the secret with a matching or absent <em>issuer</em>.
The authentication is resolved as follows:
1. Raw token values matched with configurations by looking in locations configured in HASURA_GRAPHQL_JWT_SECRETS under the "header" field (Authorization Header if missing).
2. Tokens are filtered to ensure that the <em>issuer</em> field matches, or that the issuer is absent either from the configuration, or the token.
3. If no candidate tokens are found then the unauthorized flow is performed (depends on `HASURA_GRAPHQL_UNAUTHORIZED_ROLE`).
4. If multiple candidate tokens are found then an error is raised as the desired token is ambiguous.
5. If one candidate token is found then it is verified against the corresponding configured secret.
:::info Note
Authentication resolution is identical when using `HASURA_GRAPHQL_JWT_SECRET` or a single `HASURA_GRAPHQL_JWT_SECRETS` configuration.
:::
:::info Note
If both `HASURA_GRAPHQL_JWT_SECRET` and `HASURA_GRAPHQL_JWT_SECRETS` are set, then `HASURA_GRAPHQL_JWT_SECRETS` will be used.
:::

View File

@ -0,0 +1,41 @@
---
description: Hasura Cloud multiple admin secrets
keywords:
- hasura
- docs
- cloud
- security
- allow
- rotating
- multiple
- admin
- secrets
sidebar_position: 4
---
# Rotating Admin Secrets
## Introduction
You can specify a list of admin secrets which can be used to implement security mechanisms like rotating admin secrets.
## How to use multiple admin secrets
Multiple admin secrets can be provided in the env var `HASURA_GRAPHQL_ADMIN_SECRETS` which takes a JSON array of admin secrets (strings).
When you launch the console from the Hasura Cloud dashboard, you can use any secret from the admin secrets list to authenticate yourself as an admin.
If you want to make API calls from outside the console, you need to pass any one of the admin secrets as the `x-hasura-admin-secret` request header.
:::info Note
If both `HASURA_GRAPHQL_ADMIN_SECRET` and `HASURA_GRAPHQL_ADMIN_SECRETS` are set, then only `HASURA_GRAPH_ADMIN_SECRETS` will be used.
:::
## How to rotate an admin secret
To implement a secret rotation mechanism, the following can be done:
1. Add a new secret to the list of admin secrets (and perform a rolling deploy)
2. Update applications/services using the old admin secret to use the new secret
3. Remove the old secret from the admin secret list (and perform a rolling deploy)

View File

@ -0,0 +1,94 @@
---
description: Distributed tracing with Hasura Cloud
keywords:
- hasura
- docs
- cloud
- tracing
sidebar_position: 8
---
import Thumbnail from "@site/src/components/Thumbnail";
# Distributed tracing
## Introduction
Hasura Cloud has support for *distributed tracing*, a technique for
debugging Hasura in production in the context of the services it works
with. These services might include your own Postgres database, any
remote schemas, event trigger webhook providers, action providers or
authentication hooks. Distributed tracing attempts to give a unified
view into the performance characteristics of all of these components of
your architecture.
## Visualizing traces
The Hasura Pro console makes it possible to view Hasura's own tracing
data, by opening the details view for an operation in the Operations
tab:
<Thumbnail
src="/img/graphql/cloud/tracing/tracing-operations-timing.png"
alt="View timing data in the Operations tab"
/>
Given that other system components will report their own tracing data to
your APM system, and not to Hasura, it is not possible to give a
complete picture of a trace, but since Hasura sits in a central position
in the architecture of many systems, it can often give a reasonably
comprehensive view of the provenance of data in your system.
For example, Hasura can report interactions with Postgres, remote
schemas, event trigger webhooks and action handlers.
## APM system integration
Hasura will report trace information to your APM or *application
performance monitoring* system, where it can be correlated with similar
sources of data from other components of your service architecture.
If you are considering integrating Hasura with your APM system, please
get in touch so that we can help to coordinate that effort.
## Trace propagation
At the boundaries between different services, tracing information needs
to be shared in order for trace fragments from different systems to be
correlated with each other in the APM system. This is called *trace
propagation*.
There are several subtly-incompatible proposals for trace propagation,
which can make it difficult to arrange for any two services to work
together.
### Propagation to web services
For propagation during a call to a web service over HTTP, Hasura
currently implements the [B3 propagation
specification](https://github.com/openzipkin/b3-propagation). This means
that we send trace information in various HTTP headers, which should be
read and handled by any compatible web services.
If you are unsure how to implement B3 propagation in your own web
service, the simplest thing to do is to read these headers and pass them
along to any HTTP services you call which also support B3 propagation,
including Hasura itself.
In particular, if an event trigger webhook or action handler propagates
these B3 headers back to Hasura, we will be able to trace the entire
interaction.
### Propagation via Postgres
There is no standard method for trace propagation via Postgres
transactions. For example, event triggers can be invoked by mutations,
and so their traces should be correlated.
For this reason, we have adopted our method of propagating a trace
context in Postgres transactions.
The trace context will be serialized during mutations as a
transaction-local variable, `hasura.tracecontext`. This value has the
Postgres type `json`, and it can be read in trigger functions and
propagated to any downstream services.

View File

@ -0,0 +1,4 @@
{
"label": "Hasura GraphQL Engine",
"position": 1
}

View File

@ -0,0 +1,4 @@
{
"label": "Actions",
"position": 3
}

View File

@ -0,0 +1,144 @@
.. meta::
:description: Hasura action examples
:keywords: hasura, docs, actions, examples
.. _action_examples:
Action examples
===============
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
Introduction
------------
This page provides reference examples of typical action use cases.
..
Relationships
-------------
Object relationship from an action
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Let's say we have the following two tables in our schema:
.. code-block:: sql
authors (id int, name text, is_active boolean, rating int, address_id)
addresses (id int, street text, zip text, city text)
Now we have an action ``updateAddress`` that looks as follows:
.. thumbnail:: /img/graphql/core/actions/update-address-action-definition.png
:alt: Update address action
:width: 65%
We can now add an object relationship from the ``updateAddress`` action to the ``authors`` table in our schema.
We call it ``updatedAddressAuthor``.
.. thumbnail:: /img/graphql/core/actions/action-object-relationship.png
:alt: Object relationship from action
:width: 65%
It's now possible to return the author from the ``updateAddress`` action through the newly created relationship:
.. graphiql::
:view_only:
:query:
mutation {
updateAddress(address:
{
id: 1
street: "New York Avenue"
zip: "98000"
city: "New Orleans"
}
) {
id
updatedAddressAuthor {
name
}
}
}
:response:
{
"data": {
"updateAddress": {
"id": 1,
"updatedAddressAuthor": {
"name": "J.K. Rowling"
}
}
}
}
Array relationship from an action
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Let's say we have the following two tables in our schema:
.. code-block:: sql
authors (id int, name text, is_active boolean, rating int)
articles (id int, title text, content text, author_id int)
Now we have an action ``updateAuthor`` that looks as follows:
.. thumbnail:: /img/graphql/core/actions/update-author-action-definition.png
:alt: Update author action
:width: 65%
We can now add an array relationship from the ``updateAuthor`` action to the ``articles`` table in our schema.
We call it ``updatedAuthorArticles``.
.. thumbnail:: /img/graphql/core/actions/action-array-relationship.png
:alt: Array relationship from action
:width: 65%
It's now possible to return articles from the ``updateAuthor`` action through the newly created relationship:
.. graphiql::
:view_only:
:query:
mutation {
updateAuthor(author:
{
id: 442,
name: "Joanne K. Rowling",
is_active: true,
rating: 10
}
) {
id
updatedAuthorArticles {
title
}
}
}
:response:
{
"data": {
"updateAuthor": {
"id": 442,
"updatedAuthorArticles": [
{
"title": "Harry Potter and the Philosopher's Stone"
},
{
"title": "Harry Potter and the Chamber of Secrets"
}
]
}
}
}
.. admonition:: Additional Resources
Introduction to Hasura Actions - `View Recording <https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=>`__.

View File

@ -0,0 +1,327 @@
---
sidebar_label: Action handlers
sidebar_position: 3
description: Action handlers for Hasura actions
keywords:
- hasura
- docs
- actions
- handlers
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import Thumbnail from "@site/src/components/Thumbnail";
# Action handlers
## Introduction
Actions need to be backed by custom business logic. This business logic
can be defined in a handler which is an HTTP webhook.
## HTTP handler
When the action is executed i.e. when the query or the mutation is
called, Hasura makes a `POST` request to the handler with the action
arguments and the session variables.
The request payload is of the format:
```json
{
"action": {
"name": "<action-name>"
},
"input": {
"arg1": "<value>",
"arg2": "<value>"
},
"session_variables": {
"x-hasura-user-id": "<session-user-id>",
"x-hasura-role": "<session-user-role>"
},
"request_query": "<request-query>"
}
```
:::info Note
All `session_variables` in the request payload have lowercase keys.
:::
## Returning a success response
To return a success response, you must send back a response payload of
action's response type. The HTTP status code must be `2xx` for a
successful response.
## Returning an error response
To return an error response, you must send back an error object. An
error object looks like:
```json
{
"message": "<mandatory-error-message>",
"extensions": "<optional-json-object>"
}
```
where `extensions` is an optional JSON value.
If present, `extensions` should be a JSON object, which may have a
status code field `code`, along with other data you may want to add to
your errors:
```json
{
"code": "<optional-error-code>",
"optionalField1": "<custom-data-here>"
}
```
The HTTP status code must be `4xx` in order to indicate an error
response.
For backwards compatibility with previous versions of Hasura, the `code`
field may also be supplied at the root of the error object, i.e. at
`$.code`. This will be deprecated in a future release, and providing
`code` within `extensions` is preferred.
## Example
For example, consider the following mutation.
```graphql
extend type Mutation {
UserLogin (username: String!, password: String!): UserInfo
}
type UserInfo {
accessToken: String!
userId: Int!
}
```
Let's say, the following mutation is executed:
```graphql
mutation {
UserLogin (username: "jake", password: "secretpassword") {
accessToken
userId
}
}
```
Hasura will call the handler with the following payload:
```json
{
"action": {
"name": "UserLogin"
},
"input": {
"username": "jake",
"password": "secretpassword"
},
"session_variables": {
"x-hasura-user-id": "423",
"x-hasura-role": "user"
},
"request_query": "mutation {\n UserLogin (username: \"jake\", password: \"secretpassword\") {\n accessToken\n userId\n }\n}\n"
}
```
To return a success response, you must send the response of the action's
output type (in this case, `UserInfo`) with a status code `2xx`. So a
sample response would be:
```json
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVC",
"userId": 423
}
```
To throw an error, you must send a response of the following type while
setting the status code as `4xx`.
```json
{
"message": "invalid credentials"
}
```
## Restrict access to your action handler {#securing-action-handlers}
You might want to restrict access to your action handler in order to
ensure that it can only get called by your Hasura instance and not by
third parties.
### Adding an action secret
One possible way of restricting access to an action handler is by adding
a header to the action that is automatically sent with each request to
the webhook, and then adding a check against that in your action
handler.
- [Step 1: Configure your Hasura instance](/graphql/core/actions/action-handlers.mdx#configure-your-hasura-instance)
- [Step 2: Add a header to your action](/graphql/core/actions/action-handlers.mdx#add-a-header-to-your-action)
- [Step 3: Verify the secret in your action handler](/graphql/core/actions/action-handlers.mdx#verify-the-secret-in-your-action-handler)
:::info Note
Adding an action secret is a simple way of restricting access to an
action handler and will suffice in most use cases. However, if you have
more profound security requirements, you might want to choose advanced
security solutions tailored to your needs.
:::
#### Step 1: Configure your Hasura instance {#configure-your-hasura-instance}
In your Hasura server, add the action secret as an environment variable,
say `ACTION_SECRET_ENV`.
#### Step 2: Add a header to your action {#add-a-header-to-your-action}
For your action, add a header that will act as an action secret.
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Head to the `Actions -> [action-name]` tab in the console and scroll
down to `Headers`. You can now configure an action secret by adding a
header:
<Thumbnail
src="/img/graphql/core/actions/action-secret-header.png"
alt="Console action secret"
width="700px"
/>
Then hit `Save`.
</TabItem>
<TabItem value="cli" label="CLI">
Go to `metadata/actions.yaml` in the Hasura project directory.
Update the definition of your action by adding the action secret as a
header:
```yaml {7-9}
- actions
- name: actionName
definition:
kind: synchronous
handler: http://localhost:3000
forward_client_headers: true
headers:
- name: ACTION_SECRET
value_from_env: ACTION_SECRET_ENV
```
Save the changes and run `hasura metadata apply` to set the headers.
</TabItem>
<TabItem value="api" label="API">
Headers can be set when [creating](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action) or
[updating](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-update-action) an action via the metadata API.
```http {12-17}
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "create_action",
"args": {
"name": "addNumbers",
"definition": {
"kind": "synchronous",
"type": "query",
"headers": [
{
"name": "ACTION_SECRET",
"value_from_env": "ACTION_SECRET_ENV"
}
],
"arguments": [
{
"name": "numbers",
"type": "[Int]!"
}
],
"output_type": "AddResult",
"handler": "https://hasura-actions-demo.glitch.me/addNumbers"
}
}
}
```
</TabItem>
</Tabs>
:::info Note
Before creating an action via the [create_action metadata API](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action), all custom types
need to be defined via the [set_custom_types](/graphql/core/api-reference/metadata-api/custom-types.mdx#metadata-set-custom-types) metadata API.
:::
This secret is only known by Hasura and is passed to your endpoint with
every call, thus making sure only Hasura can successfully authenticate
with the action handler.
:::info Note
The name for the action secret is not defined by Hasura and can be
chosen freely.
:::
#### Step 3: Verify the secret in your action handler {#verify-the-secret-in-your-action-handler}
First, load the action secret as an environment variable in your action
handler by adding it to your `.env` file (this file might be a different
one depending on your framework).
Second, you need to write some code in your action handler to check that
the action secret passed as a header equals to the one you stored as an
environment variable.
The following is an example of a simple authorization middleware with
Express which can be included before the request handler logic:
```javascript
// use authorization for all routes
app.use(authorizationMiddleware);
// authorize action call
function authorizationMiddleware(req, res, next){
if (correctSecretProvided(req)) next();
else res.sendStatus(403);
}
// check if the secret sent in the header equals to the secret stored as an env variable
function correctSecretProvided(req) {
const requiredSecret = process.env.ACTION_SECRET_ENV;
const providedSecret = req.headers['ACTION_SECRET'];
return requiredSecret === providedSecret;
}
// Request handler
app.post('/actionHandler', async (req, res) => {
// handler logic
});
```
:::info Additional Resources
Introduction to Hasura Actions - [View
Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,82 @@
---
sidebar_label: Actions permissions
sidebar_position: 7
description: Permissions for Hasura actions
keywords:
- hasura
- docs
- actions
- permissions
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import Thumbnail from "@site/src/components/Thumbnail";
# Actions permissions
## Introduction
As with the other fields in the GraphQL schema, users need to be given
access to an action.
## Set action permissions
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Head to the `Actions -> [action-name] -> Permissions` tab in the
console.
<Thumbnail
src="/img/graphql/core/actions/actions-permissions.png"
alt="Console action permission"
/>
Hit `Save` to give the role permission to access the action.
</TabItem>
<TabItem value="cli" label="CLI">
Go to `metadata/actions.yaml` in the Hasura project directory.
Update the definition of the `insertAuthor` action as:
```yaml {6-8}
- actions
- name: insertAuthor
definition:
kind: synchronous
handler: '{{ACTIONS_BASE_URL}}/insertAuthor'
permissions:
- role: user
- role: publisher
```
Save the changes and run `hasura metadata apply` to set the permissions.
</TabItem>
<TabItem value="api" label="API">
Action permissions can be set by using the [create_action_permission](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action-permission) metadata API:
```http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "create_action_permission",
"args": {
"action": "insertAuthor",
"role": "user"
}
}
```
</TabItem>
</Tabs>
:::info Additional Resources
Introduction to Hasura Actions - [View Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,175 @@
---
sidebar_label: Actions relationships
sidebar_position: 8
description: Manage Hasura actions relationships
keywords:
- hasura
- docs
- actions
- relationships
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import Thumbnail from "@site/src/components/Thumbnail";
# Actions relationships
## Introduction
Actions are a way to extend your GraphQL schema with custom queries or
mutations. It is quite a typical case that an action's response is
actually related to existing objects in the schema and the action needs
to be connected with the rest of the graph.
For example, a custom `insertAuthor` action will be related to the
`author` object in the schema. Hence, we would want to be able to get
information about the `author` from the graph as a response of the
`insertAuthor` mutation.
## Using action output type's relationships
Actions can be connected to the rest of the graph by setting up
relationships on its return output type.
This allows complex responses to be returned as an action's response
traversing the graph via the output type's relationships.
**For example**, given the action:
```graphql
type Mutation {
updateAuthor (
id: Int!
name: String!
): UpdateAuthorOutput
}
type UpdateAuthorOutput {
author_id : Int!
}
```
We can create an object relationship called `updatedAuthor` between the
`UpdateAuthorOutput` object type and the `author` table using the
`UpdateAuthorOutput.author_id` and `author.id` fields.
The object type will now be modified as:
```graphql {3}
type UpdateAuthorOutput {
author_id : Int!
updatedAuthor: author
}
```
Now we can make a mutation request with a complex response such as:
```graphql
mutation updateAuthorAndGetArticles($id: Int, $name: String) {
updateAuthor(id: $id, name: $name) {
author_id
updatedAuthor {
id
name
articles {
id
title
}
}
}
}
```
See more details at [custom object type relationships](/graphql/core/actions/types.mdx)
### Creating relationships for custom object types
You can create relationships for custom output types by:
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Head to the `Actions -> [action-name] -> Relationships` tab in the
console for the action returning the output type.
Set the output type relationship as shown below:
<Thumbnail
src="/img/graphql/core/actions/actions-relationship.png"
alt="Console action relationship"
/>
Hit `Save` to create the relationship.
</TabItem>
<TabItem value="cli" label="CLI">
Go to `metadata/actions.yaml` in the Hasura project directory.
Update the definition of the `UpdateAuthorOutput` object type as:
```yaml {4-11}
- custom_types
- objects
- name: UpdateAuthorOutput
relationships:
- name: updatedAuthor
type: object
remote_table:
schema: public
name: author
field_mapping:
author_id: id
```
Save the changes and run `hasura metadata apply` to create the relationship.
</TabItem>
<TabItem value="api" label="API">
Action relationships can be added while defining custom types via the
[set_custom_types](/graphql/core/api-reference/metadata-api/custom-types.mdx#metadata-set-custom-types) metadata API:
```http {20-29}
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "set_custom_types",
"args": {
"scalars": [],
"enums": [],
"input_objects": [],
"objects": [
{
"name": "UpdateAuthorOutput",
"fields": [
{
"name": "author_id",
"type": "Int!"
}
],
"relationships": [
{
"name": "updatedAuthor",
"type": "object",
"remote_table": "author",
"field_mapping": {
"author_id": "id"
}
}
]
}
]
}
}
```
</TabItem>
</Tabs>
:::info Additional Resources
Introduction to Hasura Actions - [View Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,67 @@
---
sidebar_label: Async actions
sidebar_position: 4
description: Async actions
keywords:
- hasura
- docs
- actions
- async actions
---
# Async actions
Sometimes you may not want to wait for an action to complete before
sending a response back to the client (say if the business logic takes a
long time). In such cases you can create an **asynchronous** action,
which returns an `action_id` immediately to the client before contacting
the handler.
If you mark an action as **asynchronous**, Hasura also generates a
`query` and a `subscription` field for the action so that you can
query/subscribe to its status.
:::info Note
Only actions of type `mutation` can be async. Actions of type query are
always executed synchronously.
:::
For example, let's say `place_order` is an asynchronous action
```graphql
mutation placeOrderRequest($order_input: place_order_input!) {
place_order(input: $order_input)
}
```
Executing this mutation will return a response like:
```json
{
"data": {
"place_order": "23b1c256-7aff-4b95-95bd-68220d9f93f2"
}
}
```
The returned `uuid` is the `action id` of the async action. To get the
actual response of the action, you can `query` or `subscribe` to the
action using this `action id`.
```graphql
subscription getPlaceOrderResponse {
place_order (id: "23b1c256-7aff-4b95-95bd-68220d9f93f2") {
output
errors
}
}
```
:::info Additional Resources
Introduction to Hasura Actions - [View
Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,4 @@
{
"label": "Codegen",
"position": 5
}

View File

@ -0,0 +1,128 @@
---
description: Codegen for Hasura actions
keywords:
- hasura
- docs
- actions
- codegen
slug: index
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import Thumbnail from "@site/src/components/Thumbnail";
# Actions codegen
## Introduction
Actions need HTTP handlers to run the business logic. It might be
inconvenient to write the complete handler code for every action.
Luckily, GraphQL's type system allows us to auto-generate the
boilerplate code for actions.
:::info Note
Hasura currently has codegen set up for a few frameworks. The list of
supported frameworks should grow with contributions from the community.
:::
## Generating handler code for your action {#actions-codegen-execute}
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Head to the `Actions -> [action-name] -> Codegen` tab in the console
You can select the framework of your choice to get the corresponding
handler boilerplate code.
<Thumbnail
src="/img/graphql/core/actions/console-codegen-tab.png"
alt="Console codegen tab"
/>
</TabItem>
<TabItem value="cli" label="CLI">
**Configuration**
Before being able to codegen for actions, you have to configure your CLI.
Run:
```bash
hasura actions use-codegen
```
1. Choose which framework you want to codegen for:
<Thumbnail
src="/img/graphql/core/actions/cli-framework-prompt.png"
alt="CLI Framework Prompt"
/>
2. Choose if you also wish to clone a starter kit for the chosen framework:
<Thumbnail
src="/img/graphql/core/actions/cli-starter-kit-prompt.png"
alt="CLI Starter Kit Prompt"
/>
3. Choose a path where you want to output the auto-generated code files
<Thumbnail
src="/img/graphql/core/actions/cli-output-dir-prompt.png"
alt="CLI Starter Kit Prompt"
/>
This command will update your `config.yaml` with the codegen config as
per your preferences. You can also set these values manually in
`config.yaml`.
For example:
```yaml {8-10}
version: "2"
endpoint: http://localhost:8080
metadata_directory: metadata
migrations_directory: migrations
actions:
handler_webhook_baseurl: http://localhost:3000
kind: synchronous
codegen:
framework: nodejs-express
output_dir: ./nodejs-express/src/handlers/
```
**Codegen**
To finally get auto-generated code for an action, run:
```bash
hasura actions codegen <action-name>
```
The codegen files will be generated at the `output_dir` path from
`config.yaml`.
</TabItem>
</Tabs>
## Codegen for your framework
As of now, Hasura provides codegen for a few frameworks
(`nodejs-express`, `typescript-zeit`, `python-flask` and many more). You
can see the full list in the `Codegen` tab on the console after you've
[created an action](/graphql/core/actions/create.mdx).
We will continue adding more examples to the documentation.
- [Python & Flask](/graphql/core/actions/codegen/python-flask.mdx)
### Building your own codegen
If you wish to build a code generator for your framework [read the contrib guide](https://github.com/hasura/codegen-assets/blob/master/builder-kit/README.md).
:::info Additional Resources
Introduction to Hasura Actions - [View Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,616 @@
---
sidebar_label: Python & Flask
sidebar_position: 1
description: Codegen for Hasura actions in Python & Flask
keywords:
- hasura
- docs
- actions
- codegen
- guide
- python
- flask
---
import GraphiQLIDE from '@site/src/components/GraphiQLIDE';
import Thumbnail from "@site/src/components/Thumbnail";
# GraphQL API with Python & Flask: JWT authentication
## Introduction
This page describes how to use Hasura actions and codegen to build a Python & Flask API for JWT authentication.
## Step 1: Create action definition & custom types
We will assume a `user` table with the fields `email` and `password`.
We create two [actions](/graphql/core/actions/create.mdx), each with its own set of [custom types](/graphql/core/actions/types.mdx):
1. `Signup`: returns a `CreateUserOutput`
```graphql
type Mutation {
Signup (email: String! password: String!): CreateUserOutput
}
type CreateUserOutput {
id : Int!
email : String!
password : String!
}
```
2. `Login`: returns a `JsonWebToken`
```graphql
type Mutation {
Login (email: String! password: String!): JsonWebToken
}
type JsonWebToken {
token : String!
}
```
Example: creating the `Signup` action
<Thumbnail
src="/img/graphql/core/actions/python-flask-signup-types.png"
alt="Python Flask signup types"
width="1000px"
className="no-shadow"
/>
## Step 2: Action handler implementation for signup
In the `Codegen` tab, a scaffold gets generated from the GraphQL types you defined.
Next, implement the business logic for `Signup`. Your action will do the following:
- Receive the action arguments `email` and `password` on `request`,
and pass those values to `SignupArgs.from_request()`.
- Convert the plaintext password input into a hashed secure password
with Argon2.
- Send a mutation to Hasura to save the newly created user with the
hashed password.
- Return the created user object to signal success or else error.
To implement the Argon2 password hashing, you can use [argon2-cffi][].
Next, use a [requests][] library for making requests to Hasura for mutations/queries.
[argon2-cffi]: https://github.com/hynek/argon2-cffi
[requests]: https://github.com/psf/requests
Here is how your `requirements.txt` file should look: ::
flask
argon2-cffi
requests
pyjwt
Next up is the implementation.
### Signup handler & password hashing
For password hashing, the `argon2` API is minimal and straightforward:
an instance of a password hasher is created with `PasswordHasher()`,
which has methods `.hash(password)`, `.verify(hashed_password, password)`,
and `.check_needs_rehash(hashed_password)`.
In your signup handler, first convert the action input password to a secure hash:
```python
from argon2 import PasswordHasher
Password = PasswordHasher()
@app.route("/signup", methods=["POST"])
def signup_handler():
args = AuthArgs.from_request(request.get_json())
hashed_password = Password.hash(args.password)
```
### GraphQL request client
Next, since you have the user's email and hashed password, you need to send a request to Hasura to save them in the database.
For this, you need a request client implementation:
```python
from requests import request
@dataclass
class Client:
url: str
headers: dict
def run_query(self, query: str, variables: dict, extract=False):
request = requests.post(
self.url,
headers=self.headers,
json={"query": query, "variables": variables},
)
assert request.ok, f"Failed with code {request.status_code}"
return request.json()
create_user = lambda self, email, password: self.run_query(
"""
mutation CreateUser($email: String!, $password: String!) {
insert_user_one(object: {email: $email, password: $password}) {
id
email
password
}
}
""",
{"email": email, "password": password},
)
```
Create a utility class for handling your Hasura operations. It takes an URL and headers object as initialization options and exposes a method `.run_query()` for performing GraphQL requests.
Create the query function for saving your user in the `Signup` action as a class method as well.
You can instantiate the `Client` like this:
```python
HASURA_URL = "http://graphql-engine:8080/v1/graphql"
HASURA_HEADERS = {"X-Hasura-Admin-Secret": "your-secret"}
client = Client(url=HASURA_URL, headers=HASURA_HEADERS)
```
Now, in your `Signup` action handler, you need to call `client.create_user()` with the input email and the hashed password value to save them, then return the result:
```python
@app.route("/signup", methods=["POST"])
def signup_handler():
args = AuthArgs.from_request(request.get_json())
hashed_password = Password.hash(args.password)
user_response = client.create_user(args.email, hashed_password)
if user_response.get("errors"):
return {"message": user_response["errors"][0]["message"]}, 400
else:
user = user_response["data"]["insert_user_one"]
return CreateUserOutput(**user).to_json()
```
To test this out, send an HTTP request to your Flask API at `/signup`
with an email and password:
```http
POST http://localhost:5000/signup HTTP/1.1
content-type: application/json
{
"input": {
"email": "user@test.com",
"password": "password123"
}
}
```
You should get a successful response like this:
```http
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 129
Server: Werkzeug/1.0.1 Python/3.8.2
Date: Sun, 10 May 2020 19:58:23 GMT
{
"id": 1,
"email": "user@test.com",
"password": "$argon2id$v=19$m=102400,t=2,p=8$fSmC349hY74QoGRTD0w$OYQYd/PP9kYsy9gRnDF1oQ"
}
```
Now your `Signup` action is functional!
And finally, create the `Login` handler to perform a password comparison, and then return a signed JWT if successful.
## Step 3: Action handler implementation for login
The first thing you need is a new request method on your `Client` class to find a user by email so that you can look them up to compare the password.
Under `create_user`, create the following new method:
```python
find_user_by_email = lambda self, email: self.run_query(
"""
query UserByEmail($email: String!) {
user(where: {email: {_eq: $email}}, limit: 1) {
id
email
password
}
}
""",
{"email": email},
)
```
Then in your login handler, call `Password.verify()` to compare the input password against the hashed password saved in the database.
If the password matches, you create a JWT from the user credentials and return it.
You should also determine whether the password needs to be updated and re-hashed by Argon2 if the hashing parameters have changed and are no longer valid.
If so, you should re-hash and then save the updated password in the database through an update mutation to Hasura, `client.update_password()`.
```python
@app.route("/login", methods=["POST"])
def login_handler():
args = LoginArgs.from_request(request.get_json())
user_response = client.find_user_by_email(args.email)
user = user_response["data"]["user"][0]
try:
Password.verify(user.get("password"), args.password)
rehash_and_save_password_if_needed(user, args.password)
return JsonWebToken(generate_token(user)).to_json()
except VerifyMismatchError:
return { "message": "Invalid credentials" }, 401
```
Here is what the implementation of `generate_token()` and
`rehash_and_save_password_if_needed()` could look like:
```python
import os
import jwt
# Try to get the secret from ENV, else fallback to provided string
HASURA_JWT_SECRET = os.getenv("HASURA_GRAPHQL_JWT_SECRET", "a-very-secret-secret")
# ROLE LOGIC FOR DEMO PURPOSES ONLY
# NOT AT ALL SUITABLE FOR A REAL APP
def generate_token(user) -> str:
"""
Generates a JWT compliant with the Hasura spec, given a User object with field "id"
"""
user_roles = ["user"]
admin_roles = ["user", "admin"]
is_admin = user["email"] == "admin@site.com"
payload = {
"https://hasura.io/jwt/claims": {
"x-hasura-allowed-roles": admin_roles if is_admin else user_roles,
"x-hasura-default-role": "admin" if is_admin else "user",
"x-hasura-user-id": user["id"],
}
}
token = jwt.encode(payload, HASURA_JWT_SECRET, "HS256")
return token.decode("utf-8")
def rehash_and_save_password_if_needed(user, plaintext_password):
"""
Whenever your Argon2 parameters or argon2-cffis defaults!
change, you should rehash your passwords at the next opportunity.
The common approach is to do that whenever a user logs in, since
that should be the only time when you have access to the cleartext password.
Therefore its best practice to check and if necessary rehash
passwords after each successful authentication.
"""
if Password.check_needs_rehash(user["password"]):
client.update_password(user["id"], Password.hash(plaintext_password))
```
And finally, `client.update_password()`:
```python
update_password = lambda self, id, password: self.run_query(
"""
mutation UpdatePassword($id: Int!, $password: String!) {
update_user_by_pk(pk_columns: {id: $id}, _set: {password: $password}) {
password
}
}
""",
{"id": id, "password": password},
)
```
## Step 4: Testing out the handler routes
Call the `/signup` endpoint with `email` and `password`:
```http
POST http://localhost:5000/signup HTTP/1.1
content-type: application/json
{
"input": {
"email": "user@test.com",
"password": "password123"
}
}
```
Action handler response:
```http
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 256
Server: Werkzeug/1.0.1 Python/3.8.2
Date: Sun, 10 May 2020 19:59:36 GMT
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.z9ey1lw9p89gUkAmWEa7Qbpa1R71TgfkjZnEunGJ1ig"
}
```
Decode the JWT token to access the Hasura claims:
```bash
$ decode_jwt 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.z9ey1lw9p89gUkAmWEa7Qbpa1R71TgfkjZnEunGJ1ig'
{
"https://hasura.io/jwt/claims": {
"x-hasura-allowed-roles": ["user"],
"x-hasura-default-role": "user",
"x-hasura-user-id": 1
}
}
```
## Step 5: Calling the finished actions
Try out your defined actions from the GraphQL API.
Call the `Signup` action:
<GraphiQLIDE
query={`mutation Signup {
signup(email: "newuser@test.com", password: "a-password") {
id
email
password
}
}`}
response={`{
"data": {
"Signup": {
"id": 2,
"email": "newuser@test.com",
"password": "$argon2id$v=19$m=102400,t=2,p=8$fSmC349hY74QoGRTD0w$OYQYd/PP9kYsy9gRnDF1oQ"
}
}
}`}
/>
Call the `Signup` action with a duplicate:
<GraphiQLIDE
query={`mutation SignupDuplicate {
signup(email: "newuser@test.com", password: "a-password") {
id
email
password
}
}`}
response={`{
"errors": [
{
"extensions": {
"path": "$",
"code": "unexpected"
},
"message": "Uniqueness violation. Duplicate key value violates unique constraint \"user_email_key\""
}
]
}
`}
/>
Call the `Login` action with valid credentials:
<GraphiQLIDE
query={`query Login {
Login(email: "newuser@test.com", password: "a-password") {
token
}
}`}
response={`{
"data": {
"Login": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.z9ey1lw9p89gUkAmWEa7Qbpa1R71TgfkjZnEunGJ1ig"
}
}
}
`}
/>
Call the `Login` action with invalid credentials:
<GraphiQLIDE
query={`query IncorrectLogin {
Login(email: "newuser@test.com", password: "bad-password") {
token
}
}`}
response={`{
"errors": [
{
"extensions": {
"path": "$",
"code": "unexpected"
},
"message": "Invalid credentials"
}
]
}
`}
/>
## Complete app code
```python
import os
import jwt
import json
import logging
import requests
from flask import Flask, request, jsonify
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from typing import Optional
from dataclasses import dataclass, asdict
HASURA_URL = "http://graphql-engine:8080/v1/graphql"
HASURA_HEADERS = {"X-Hasura-Admin-Secret": "your-secret"}
HASURA_JWT_SECRET = os.getenv("HASURA_GRAPHQL_JWT_SECRET", "a-very-secret-secret")
################
# GRAPHQL CLIENT
################
@dataclass
class Client:
url: str
headers: dict
def run_query(self, query: str, variables: dict, extract=False):
request = requests.post(
self.url,
headers=self.headers,
json={"query": query, "variables": variables},
)
assert request.ok, f"Failed with code {request.status_code}"
return request.json()
find_user_by_email = lambda self, email: self.run_query(
"""
query UserByEmail($email: String!) {
user(where: {email: {_eq: $email}}, limit: 1) {
id
email
password
}
}
""",
{"email": email},
)
create_user = lambda self, email, password: self.run_query(
"""
mutation CreateUser($email: String!, $password: String!) {
insert_user_one(object: {email: $email, password: $password}) {
id
email
password
}
}
""",
{"email": email, "password": password},
)
update_password = lambda self, id, password: self.run_query(
"""
mutation UpdatePassword($id: Int!, $password: String!) {
update_user_by_pk(pk_columns: {id: $id}, _set: {password: $password}) {
password
}
}
""",
{"id": id, "password": password},
)
#######
# UTILS
#######
Password = PasswordHasher()
client = Client(url=HASURA_URL, headers=HASURA_HEADERS)
# ROLE LOGIC FOR DEMO PURPOSES ONLY
# NOT AT ALL SUITABLE FOR A REAL APP
def generate_token(user) -> str:
"""
Generates a JWT compliant with the Hasura spec, given a User object with field "id"
"""
user_roles = ["user"]
admin_roles = ["user", "admin"]
is_admin = user["email"] == "admin@site.com"
payload = {
"https://hasura.io/jwt/claims": {
"x-hasura-allowed-roles": admin_roles if is_admin else user_roles,
"x-hasura-default-role": "admin" if is_admin else "user",
"x-hasura-user-id": user["id"],
}
}
token = jwt.encode(payload, HASURA_JWT_SECRET, "HS256")
return token.decode("utf-8")
def rehash_and_save_password_if_needed(user, plaintext_password):
if Password.check_needs_rehash(user["password"]):
client.update_password(user["id"], Password.hash(plaintext_password))
#############
# DATA MODELS
#############
@dataclass
class RequestMixin:
@classmethod
def from_request(cls, request):
"""
Helper method to convert an HTTP request to Dataclass Instance
"""
values = request.get("input")
return cls(**values)
def to_json(self):
return json.dumps(asdict(self))
@dataclass
class CreateUserOutput(RequestMixin):
id: int
email: str
password: str
@dataclass
class JsonWebToken(RequestMixin):
token: str
@dataclass
class AuthArgs(RequestMixin):
email: str
password: str
##############
# MAIN SERVICE
##############
app = Flask(__name__)
@app.route("/signup", methods=["POST"])
def signup_handler():
args = AuthArgs.from_request(request.get_json())
hashed_password = Password.hash(args.password)
user_response = client.create_user(args.email, hashed_password)
if user_response.get("errors"):
return {"message": user_response["errors"][0]["message"]}, 400
else:
user = user_response["data"]["insert_user_one"]
return CreateUserOutput(**user).to_json()
@app.route("/login", methods=["POST"])
def login_handler():
args = AuthArgs.from_request(request.get_json())
user_response = client.find_user_by_email(args.email)
user = user_response["data"]["user"][0]
try:
Password.verify(user.get("password"), args.password)
rehash_and_save_password_if_needed(user, args.password)
return JsonWebToken(generate_token(user)).to_json()
except VerifyMismatchError:
return {"message": "Invalid credentials"}, 401
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0")
```
:::info Additional Resources
Introduction to Hasura Actions - [View Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,580 @@
---
sidebar_label: Creating actions
sidebar_position: 1
description: Creating Hasura actions
keywords:
- hasura
- docs
- actions
- create
---
import TOCInline from '@theme/TOCInline';
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import Thumbnail from "@site/src/components/Thumbnail";
import GraphiQLIDE from '@site/src/components/GraphiQLIDE';
# Creating Actions
## Introduction
An action is a GraphQL query or mutation. You have to define the GraphQL
type of the arguments that the query or mutation accepts and the GraphQL
type of its response.
To create an action, you have to:
1. Define the query or mutation
2. Define the required types
3. Create a handler
Let's look at **examples** for mutation and query type actions.
## Setup
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
There is no setup required for defining actions via the console.
</TabItem>
<TabItem value="cli" label="CLI">
[Install](/graphql/core/hasura-cli/install-hasura-cli.mdx) or [update to](/graphql/core/hasura-cli/hasura_update-cli.mdx) the latest version of Hasura CLI.
You can either get started with an existing project or create a new project.
**For a new project**
```bash
hasura init
```
This will create a new project. You can set up your GraphQL engine endpoint (and admin secret if it exists) in the `config.yaml`.
Run `hasura metadata export` so that you get server's metadata into the `metadata/` directory.
**For existing projects**
Actions are supported only in the v2 config of the CLI. Check the `config.yaml` of your Hasura project for the `version` key.
If you see `version: 1` (or do not see a version key), upgrade to version 2 by running:
```bash
hasura scripts update-config-v2
```
Run `hasura metadata export` so that you get server's metadata into the `metadata/` directory.
</TabItem>
<TabItem value="api" label="API">
There is no setup required for defining actions via the [actions metadata API](/graphql/core/api-reference/metadata-api/actions.mdx).
</TabItem>
</Tabs>
## Mutation type action
Let's start with a mutation that accepts a username and password, and
returns an access token. We'll call this mutation `login`.
<TOCInline toc={toc} filterTOC={(tocTree) => tocTree[2].children} />
### Step 1: Define your mutation and associated types
Start with defining the mutation and the required types. These types
will reflect in the GraphQL schema.
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Go to the `Actions` tab on the console and click on `Create`. This will
take you to a page like this:
<Thumbnail
src="/img/graphql/core/actions/mutation-action-create.png"
alt="Console action create"
width="800px"
/>
Define the action as follows in the `Action Definition` editor.
```graphql
type Mutation {
login (username: String!, password: String!): LoginResponse
}
```
In the above action, we called the returning object type to be
`LoginResponse`. Define it in the `New types definition` as:
```graphql
type LoginResponse {
accessToken: String!
}
```
</TabItem>
<TabItem value="cli" label="CLI">
To create an action, run
```bash
hasura actions create login
```
This will open up an editor with `metadata/actions.graphql`. You can
enter the action's mutation definition and the required types in this
file. For your `login` mutation, replace the content of this file with
the following and save:
```graphql
type Mutation {
login (username: String!, password: String!): LoginResponse
}
type LoginResponse {
accessToken: String!
}
```
</TabItem>
<TabItem value="api" label="API">
It is essential that the custom types used in the action are defined *beforehand* via the [set_custom_types](/graphql/core/api-reference/metadata-api/custom-types.mdx#metadata-set-custom-types) metadata API:
```http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "set_custom_types",
"args": {
"scalars": [],
"enums": [],
"input_objects": [],
"objects": [
{
"name": "LoginResponse",
"fields": [
{
"name": "accessToken",
"type": "String!"
}
]
}
]
}
}
```
Once the custom types are defined, we can create an action via the [create_action metadata API](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action):
```http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "create_action",
"args": {
"name": "Login",
"definition": {
"kind": "synchronous",
"type": "mutation",
"arguments": [
{
"name": "username",
"type": "String!"
},
{
"name": "password",
"type": "String!"
}
],
"output_type": "LoginResponse",
"handler": "https://hasura-actions-demo.glitch.me/login"
}
}
}
```
</TabItem>
</Tabs>
The above definition means:
- This action will be available in your GraphQL schema as a mutation called `login`.
- It accepts two arguments called `username` and `password` of type `String!`.
- It returns an output type called `LoginResponse`.
- `LoginResponse` is a simple object type with a field called `accessToken` of type `String!`.
### Step 2: Create the action handler
A handler is an HTTP webhook where you can perform the custom logic for the action.
In this case, we will just return an access token, but typically you would want to run all the business logic that the action demands.
NodeJS/Express code for this handler would look something like:
```javascript
const handler = (req, resp) => {
// You can access their arguments input at req.body.input
const { username, password } = req.body.input;
// perform your custom business logic
// check if the username and password are valid and login the user
// return the response
return resp.json({
accessToken: "Ew8jkGCNDGAo7p35RV72e0Lk3RGJoJKB"
})
};
```
You can deploy this code somewhere and get the URI. For getting started
quickly, we also have this handler ready at
`https://hasura-actions-demo.glitch.me/login`.
**Set the handler**
Now, set the handler for the action:
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Set the value of the `handler` field to the above endpoint.
</TabItem>
<TabItem value="cli" label="CLI">
Go to `metadata/actions.yaml`. You must see a handler like `http://localhost:3000` or `http://host.docker.internal:3000` under the
action named `login`. This is a default value taken from `config.yaml`.
Update the `handler` to the above endpoint.
</TabItem>
<TabItem value="api" label="API">
The action handler must be set when creating an action via the [create_action metadata API](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action).
It can be updated later by using the [update_action metadata API](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-update-action).
</TabItem>
</Tabs>
<br />
:::info URL templating
To manage handler endpoints across environments it is possible to
template the endpoints using ENV variables.
e.g. `https://my-handler-endpoint/addNumbers` can be templated to
`{{ACTION_BASE_ENDPOINT}}/addNumbers` where `ACTION_BASE_ENDPOINT` is an
ENV variable whose value is set to `https://my-handler-endpoint`
:::
:::info Note
If you are running Hasura using Docker, ensure that the Hasura Docker container can reach the handler endpoint. See [this page](/graphql/core/guides/docker-networking.mdx) for Docker networking.
:::
### Step 3: Finish action creation
Finally, to save the action:
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Hit `Create`.
</TabItem>
<TabItem value="cli" label="CLI">
Run `hasura metadata apply`.
</TabItem>
<TabItem value="api" label="API">
An action will be created when sending a request to the [create_action metadata API](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action).
</TabItem>
</Tabs>
### Step 4: Try it out
In the Hasura console, head to the `GraphiQL` tab and try out the new action.
<GraphiQLIDE
query={
`mutation {
login (username: "jondoe", password: "mysecretpassword") {
accessToken
}
}`}
response={
`{
"data": {
"login": {
"accessToken": "Ew8jkGCNDGAo7p35RV72e0Lk3RGJoJKB"
}
}
}`}
/>
And that's it. You have extended your Hasura schema with a new mutation.
## Query type action
Let's start with a basic query that accepts a list of numbers and returns their sum. We'll call this query `addNumbers`.
<TOCInline toc={toc} filterTOC={(tocTree) => tocTree[3].children} />
### Step 1: Define your query and associated types
Start with defining the query and the required types. These types will reflect in the GraphQL schema.
<Tabs className="api_tabs">
<TabItem value="console" label="Console">
Go to the `Actions` tab on the console and click on `Create`. This will take you to a page like this:
<Thumbnail
src="/img/graphql/core/actions/query-action-create.png"
alt="Console action create"
width="800px"
/>
Define the action as follows in the `Action Definition` editor.
```graphql
type Query {
addNumbers (numbers: [Int]): AddResult
}
```
In the above action, we called the returning object type to be `AddResult`. Define it in the `New types definition` as:
```graphql
type AddResult {
sum: Int
}
```
</TabItem>
<TabItem value="cli" label="CLI">
To create an action, run
```bash
hasura actions create addNumbers
```
This will open up an editor with `metadata/actions.graphql`. You can enter the action's query definition and the required types in this file.
For your `addNumbers` query, replace the content of this file with the following and save:
```graphql
type Query {
addNumbers (numbers: [Int]): AddResult
}
type AddResult {
sum: Int
}
```
</TabItem>
<TabItem value="api" label="API">
It is essential that the custom types used in the action are defined *beforehand* via the [set_custom_types](/graphql/core/api-reference/metadata-api/custom-types.mdx#metadata-set-custom-types) metadata API:
```http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "set_custom_types",
"args": {
"scalars": [],
"enums": [],
"input_objects": [],
"objects": [
{
"name": "AddResult",
"fields": [
{
"name": "sum",
"type": "Int!"
}
]
}
]
}
}
```
Once the custom types are defined, we can create an action via the [create_action metadata API](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action):
```http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type":"create_action",
"args": {
"name":"addNumbers",
"definition": {
"kind":"synchronous",
"type": "query",
"arguments":[
{
"name":"numbers",
"type":"[Int]!"
}
],
"output_type":"AddResult",
"handler":"https://hasura-actions-demo.glitch.me/addNumbers"
}
}
}
```
</TabItem>
</Tabs>
The above definition means:
- This action will be available in your GraphQL schema as a query called `addNumbers`
- It accepts an argument called `numbers` which is a list of integers.
- It returns an output type called `AddResult`.
- `AddResult` is a simple object type with a field called `sum` of type integer.
### Step 2: Create the action handler
A handler is an HTTP webhook where you can perform the custom logic for the action.
In this case, it is the addition of the numbers. NodeJS/Express code for this handler would look something like:
```javascript
const handler = (req, resp) => {
// You can access their arguments input at req.body.input
const { numbers } = req.body.input;
// perform your custom business logic
// return an error or response
try {
return resp.json({
sum: numbers.reduce((s, n) => s + n, 0)
});
} catch(e) {
console.error(e)
return resp.status(500).json({
message: 'unexpected'
})
}
};
```
You can deploy this code somewhere and get the URI. For getting started quickly, we also have this handler ready at `https://hasura-actions-demo.glitch.me/addNumbers`.
**Set the handler**
Now, set the handler for the action:
<Tabs className="api_tabs">
<TabItem value="console" label="Console">
Set the value of the `handler` field to the above endpoint.
</TabItem>
<TabItem value="cli" label="CLI">
Go to `metadata/actions.yaml`. You must see a handler like `http://localhost:3000` or `http://host.docker.internal:3000` under the
action named `addNumbers`. This is a default value taken from `config.yaml`.
Update the `handler` to the above endpoint.
</TabItem>
<TabItem value="api" label="API">
The action handler must be set when creating an action via the Once the custom types are defined, we can create an action via the [create_action metadata API](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action).
It can be updated later by using the [update_action metadata API](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-update-action).
</TabItem>
</Tabs>
:::info URL templating
To manage handler endpoints across environments it is possible to template the endpoints using ENV variables.
e.g. `https://my-handler-endpoint/addNumbers` can be templated to `{{ACTION_BASE_ENDPOINT}}/addNumbers` where `ACTION_BASE_ENDPOINT` is an ENV variable whose value is set to `https://my-handler-endpoint`
:::
### Step 3: Finish action creation
Finally, to save the action:
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Hit `Create`.
</TabItem>
<TabItem value="cli" label="CLI">
Run `hasura metadata apply`.
</TabItem>
<TabItem value="api" label="API">
An action will be created when sending a request to the [create_action metadata API](/graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action).
</TabItem>
</Tabs>
### Step 4: Try it out
In the Hasura console, head to the `GraphiQL` tab and try out the new
action.
<GraphiQLIDE
query={
`query {
addNumbers(numbers: [1, 2, 3, 4]) {
sum
}
}`}
response={
`{
"data": {
"addNumbers": {
"sum": 10
}
}
}`}
/>
And that's it. You have extended your Hasura schema with a new query.
:::info Additional Resources
Introduction to Hasura Actions - [View Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,102 @@
---
sidebar_label: Debugging actions
sidebar_position: 10
description: Debugging Hasura actions
keywords:
- hasura
- docs
- actions
- debug
- debugging
---
import GraphiQLIDE from "@site/src/components/GraphiQLIDE";
# Debugging actions
While you're developing actions for your application, to debug faster
you may want to see the exact details of the webhook call for the action
as well.
To do so, start the server in [debugging mode](/graphql/core/deployment/graphql-engine-flags/config-examples.mdx#dev-mode). In the case
of errors, the GraphQL response will contain debugging information of
the webhook calls in the `extensions.internal` field.
If you are using action transforms, then you will also see the
`transformed_request` inside the `request` field.
**For example**:
<GraphiQLIDE
query={`mutation {
create_user(email: "foo@bar.com", name: "Foo"){
id
user {
name
email
}
}
}`}
response={`{
"errors": [
{
"message": "got scalar String for the action webhook response, expecting UserId",
"extensions": {
"code": "unexpected",
"path": "$",
"internal": {
"error": "got scalar String for the action webhook response, expecting UserId",
"response": {
"status": 200,
"headers": [
{
"value": "application/json",
"name": "Content-Type"
}
],
"body": "[incorrect response]"
},
"request": {
"url": "http://127.0.0.1:5593/scalar-response",
"headers": [],
"body": {
"action": {
"name": "create_user"
},
"session_variables": {
"x-hasura-role": "admin"
},
"input": {
"email": "foo@boo.com",
"name": "Foo"
},
"request_query": "mutation {\\n create_user(email: \\"foo@bar.com\\", name: \\"Foo\\"){\\n id\\n user {\\n name\\n email\\n }\\n }\\n }\\n"
},
"transformed_request": {
"query_string": "",
"body": "[transformed body]",
"url": "http://127.0.0.1:3000/abcd",
"headers": [
[
"Content-Type",
"application/json"
]
],
"method": "PATCH",
"response_timeout": "30000000"
},
}
}
}
}
]
}
`}
/>
:::info Additional Resources
Introduction to Hasura Actions - [View
Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,216 @@
---
sidebar_label: Deriving actions
sidebar_position: 6
description: Deriving Hasura actions
keywords:
- hasura
- docs
- actions
- derive
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import Thumbnail from "@site/src/components/Thumbnail";
# Deriving actions
## Introduction
It is a typical requirement to run some custom business logic before
actually executing a mutation / query, for example, to perform
validations or to enrich some data from an external source. Actions can
be used to achieve this.
To help with creation of such actions, Hasura lets you derive an action
from an existing query or mutation by:
- Auto-generating the GraphQL types defining the action
- Generating the handler code to delegate the action back to the
original query or mutation after executing some business logic
## Generate derived action GraphQL types
Hasura can generate the relevant GraphQL types required to define an
action given a GraphQL operation.
For example, let's say we would like to derive an action from the
mutation:
```graphql
mutation insertAuthor {
insert_author_one(
object: {
name: "Some name"
}) {
id
name
}
}
```
As the derived action will need to accept some arguments, we can convert
the above mutation to use variables instead which can then become
arguments to our derived action.
```graphql
mutation insertAuthor($name: String) {
insert_author_one(
object: {
name: $name
}) {
id
name
}
}
```
Now that we have a mutation with arguments being accepted as variables,
we can derive our action:
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Head to the `GraphiQL` tab of the console and paste / generate your
query in the GraphiQL window.
Next hit the `Derive action` button as shown below:
<Thumbnail
src="/img/graphql/core/actions/actions-derive-button.png"
alt="Console derive action button"
/>
This will redirect you to the `Add a new action` page with the action
definition auto filled.
<Thumbnail
src="/img/graphql/core/actions/actions-derive-types.png"
alt="Console derived action types"
/>
</TabItem>
<TabItem value="cli" label="CLI">
To create the derived action, run:
```bash
hasura actions create insertAuthor --derive-from 'mutation insertAuthor($name: String) {
insert_author_one(
object: {
name: $name
}) {
id
name
}
}'
```
This will open up an editor with `metadata/actions.graphql` with the
following action types auto filled.
```graphql
type Mutation {
insertAuthor (
name: String
): InsertAuthorOutput
}
type InsertAuthorOutput {
id : Int!
name : String!
}
```
:::info Note
The action name will be picked up from the argument of the command and
not the mutation string.
:::
</TabItem>
</Tabs>
:::info Note
- The derived output type will be derived from the actual output type
of the original query or mutation and not the selection-set of the
given query or mutation string.
- As currently custom object types can only have scalar / enum fields
any object type fields in the original output type will be dropped
in the derived output type.
:::
## Generate handler code for a derived action
For a derived action, Hasura can generate the relevant handler code to
delegate the action back to the original operation.
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Head to the `Actions -> [action-name] -> Codegen` tab in the console
You can select the framework of your choice to get the corresponding
handler boilerplate code.
<Thumbnail
src="/img/graphql/core/actions/actions-derive-codegen.png"
alt="Console derived action codegen"
/>
:::info Note
The information about derived actions are stored locally on the browser
and hence it is currently only possible to generate the delegation code
from the browser where the action was created.
:::
</TabItem>
<TabItem value="cli" label="CLI">
You will have to set up codegen in the CLI first to do this as explained
in [Generating handler code for your action](/graphql/core/actions/codegen/index.mdx#actions-codegen-execute)
After saving the GraphQL types generated by the actions create command
in the previous section, the CLI will prompt you if you would like to
generate the corresponding codegen files. Hit <em>y</em> to generate the codegen files with the
delegation logic.
The CLI does not persist information about derived actions. Hence if you
wish to generate the delegation code, you might want to pass the query
or mutation string while running the codegen command:
```bash
hasura actions codegen <action-name> --derive-from '<query/mutation string>'
```
</TabItem>
</Tabs>
## Hiding the original mutation in the API
Once a mutation is derived, you might want to hide it from your public
GraphQL API but still want to use it from your action handler.
To achieve this you can mark the mutation as `backend_only` so that it
can be accessed only via "trusted sources". See
[Backend only](/graphql/core/auth/authorization/permission-rules.mdx#backend-only-permissions) for more details
:::info Note
Setting `backend-only` is currently available for insert mutations only.
:::
:::info Additional Resources
Introduction to Hasura Actions - [View Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,185 @@
---
description: Hasura actions
keywords:
- hasura
- docs
- actions
slug: index
---
import Thumbnail from "@site/src/components/Thumbnail";
# Actions
## What are actions?
Actions are a way to extend Hasura's schema with custom business logic
using custom queries and mutations. Actions can be added to Hasura to
handle various use cases such as data validation, data enrichment from
external sources and any other complex business logic.
<Thumbnail
src="/img/graphql/core/actions/actions-arch.png"
alt="Actions high level architecture"
className="no-shadow"
/>
:::tip Supported from
Actions are supported in Hasura GraphQL engine versions `v1.2.0` and above.
Actions are supported for **Postgres versions 10 and above**.
:::
## Action description
An action consists of the following parts:
1. `Type`: The type of the action (`query` or `mutation`)
2. `Definition`: The definition of the query or mutation
3. `Handler`: The logic to be run when the query or mutation is
executed
4. `Kind`: Sync or async. In case of a query action, there is no `Kind`
associated with it. A query action is always sync
### Type
Actions can be of two types:
- **Query action**: An action of type `query` extends the query root
of the Hasura schema. This means that you can execute this action
through a GraphQL query. Query actions must be used where you want
to fetch data from a data source without changing anything on the
data source.
- **Mutation action**: An action of type `mutation` extends the
mutation root of the Hasura schema. This means that you can execute
this action through a GraphQL mutation. Mutation actions must be
used when you want to mutate the state of a data source and fetch
some data.
### Definition
The action definition consists of the following:
- `Action Name`: The action will be available as a query or mutation
in the GraphQL schema named as the action name
- `Arguments`: Arguments are used to pass dynamic values along with
the query/mutation.
- `Response type`: The GraphQL type of the response that the query or
mutation will return. Actions can only return object types or scalar types currently.
For instance, consider this action definition:
```graphql
extend type Mutation {
userLogin(username: String!, password: String!): UserInfo
}
```
In case the action response is a scalar (eg. Int), the action can also be defined as:
```graphql
type Mutation {
userLogin(username: String!, password: String!): Int!
}
```
In this definition, we are extending the mutation root with an action
called `userLogin`.
- `userLogin` is the action name
- `username` and `password` are the arguments that accept non-nullable
string values.
- `UserInfo` is the response type of the action
**Custom Types**
In case the action returns an object type, you will have to define your custom types like so:
```graphql
type UserInfo {
accessToken: String!
userId: Int!
}
```
Read more about [custom types](/graphql/core/actions/types.mdx).
### Handler
Once you define the action types, you also have to specify the logic to
run when the action is executed. This can be done in an HTTP webhook,
also called the action handler. It could be a REST endpoint or a
serverless function.
Learn more about [writing an action handler](/graphql/core/actions/action-handlers.mdx).
### Kind
**Mutation actions** are of two kinds:
- **Synchronous**: Sync actions return a response to the client after
receiving a response from the handler.
- **Asynchronous**: [Async actions](/graphql/core/actions/async-actions.mdx) return an
`action id` as response to the client before receiving a response
from the handler and allow the client to subscribe to the actual
response using the `action id`.
**Query actions** don't have a kind, they always behave like sync
mutation actions.
## How it works?
- Hasura receives the action GraphQL query or mutation and converts
this request into an event payload.
- The event is captured, persisted and then delivered to the action
handler with the appropriate retry/delivery guarantees.
- The action handler runs and returns a response that is captured as
an event and again persisted to the event store.
- The action response is returned to the client synchronously or
asynchronously based on the kind.
## Actions vs. remote schemas
Both actions and remote schemas can be used to extend Hasura with
business logic. However, they have slightly different use cases.
**Actions**
Actions can be used when we want to call a REST endpoint from Hasura as
a resolver for some custom types. They are especially useful for setting
up serverless functions as resolvers.
**Remote schemas**
If you have an existing GraphQL API or if you're comfortable building a
GraphQL server yourself, you can use [remote schemas](/graphql/core/remote-schemas/index.mdx)
to add custom types and resolvers.
## Learn more
- [Creating actions](/graphql/core/actions/create.mdx)
- [Custom types](/graphql/core/actions/types.mdx)
- [Action handlers](/graphql/core/actions/action-handlers.mdx)
- [Async actions](/graphql/core/actions/async-actions.mdx)
- [Codegen](/graphql/core/actions/codegen/index.mdx)
- [Deriving actions](/graphql/core/actions/derive.mdx)
- [Actions permissions](/graphql/core/actions/action-permissions.mdx)
- [Actions relationships](/graphql/core/actions/action-relationships.mdx)
- [REST Connectors for actions](/graphql/core/actions/rest-connectors.mdx)
- [Debugging actions](/graphql/core/actions/debugging.mdx)
- [Cleaning up async action logs](/graphql/core/actions/logs-clean-up.mdx)
<!--
action-examples
-->
:::info Additional Resources
Introduction to Hasura Actions - [View Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,79 @@
---
sidebar_label: Cleaning up async action logs
sidebar_position: 11
description: Clean up async action logs
keywords:
- hasura
- docs
- actions
- clean up
- async actions
---
# Cleaning up async action logs
## Introduction
Hasura stores action logs of [async actions](/graphql/core/actions/async-actions.mdx) in a table
in **the "hdb_catalog" schema of the Hasura metadata database**.
As the table gets larger, you may want to prune it. You can use any of the following options to prune your logs depending on
your need.
:::caution Warning
- Deleting logs is irreversible, so be careful with these actions.
- Deleting logs while subscriptions for the response might still be
open may result into the loss of data and `null` values been
returned.
:::
## The table involved
There is a specific table for action logs that is managed by Hasura:
- `hdb_catalog.hdb_action_log`: This table stores all captured action logs.
## Option 1: Delete log of a particular action invocation
```sql
DELETE FROM hdb_catalog.hdb_action_log WHERE id = '<async-action-id>';
```
## Option 2: Delete all logs of a specific action
```sql
DELETE FROM hdb_catalog.hdb_action_log WHERE action_name = '<action-name>';
```
## Option 3: Delete all logs
```sql
DELETE FROM hdb_catalog.hdb_action_log;
```
## Clearing data before a particular time period
If you wish to keep recent data and only clear data before a particular time period
you can add the following time clause to your query's where clause:
```sql
-- units can be 'minutes', 'hours', 'days', 'months', 'years'
created_at < now() - interval '<x> <units>'
```
For example: to delete all logs older than 3 months:
```sql
DELETE FROM hdb_catalog.hdb_action_log WHERE created_at < NOW() - INTERVAL '3 months';
```
See the [Postgres date/time functions](https://www.postgresql.org/docs/current/functions-datetime.html) for more details.
:::info Additional Resources
Introduction to Hasura Actions - [View Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,645 @@
---
sidebar_label: REST Connectors for actions
sidebar_position: 9
description: REST connectors for actions
keywords:
- hasura
- docs
- action
- transforms
- rest connectors
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import TOCInline from "@theme/TOCInline";
import Thumbnail from "@site/src/components/Thumbnail";
# REST Connectors for actions
## Introduction
REST Connectors for actions are used to integrate existing REST APIs to the GraphQL API without needing any middleware
or modifications to the upstream code.
REST Connectors modify the default HTTP request made by an action to adapt to your webhook's expected format by adding suitable transforms.
:::tip Supported from
REST Connectors are supported in Hasura GraphQL Engine versions `v2.1.0` and above
:::
## Configuring REST Connectors
REST Connectors can be configured either when creating a new action or editing an existing one. See the transform options [here](#action-transform-types):
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Go to the `Actions` tab on the console and create or modify an action.
Scroll down to `Configure REST Connectors` section:
<Thumbnail
src="/img/graphql/core/actions/configure-rest-connectors.png"
alt="Configure REST connectors for actions"
width="800px"
/>
</TabItem>
<TabItem value="cli" label="CLI">
Update the `actions.yaml` file inside the `metadata` directory and add a [request_transform](RequestTransformation] field to the action:
```yaml {6-13}
- name: create_user
definition:
kind: synchronous
handler: https://action.my_app.com/create-user
timeout: 60
request_transform:
template_engine: Kriti
method: POST
content_type: application/json
url: '{{$base_url}}/create_user'
query_params:
id: '{{$session_variables[''x-hasura-user-id'']}}'
body: '{"username": {{$body.input.username}}}'
comment: Custom action to create user
```
Apply the metadata by running:
```bash
hasura metadata apply
```
</TabItem>
<TabItem value="api" label="API">
REST Connectors can be configured for actions using the [create_action][metadata-create-action] or
[update_action][metadata-update-action] metadata APIs by adding a
[request_transform][RequestTransformation] field to the args:
```http {24-33}
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type":"create_action",
"args":{
"name":"create_user",
"definition":{
"kind":"synchronous",
"arguments":[
{
"name":"username",
"type":"String!"
},
{
"name":"email",
"type":"String!"
}
],
"output_type":"User",
"handler":"https://action.my_app.com/create-user",
"timeout":60,
"request_transform": {
"template_engine": "Kriti",
"method": "POST",
"url": "{{$base_url}}/create_user",
"query_params": {
"id": "{{$session_variables['x-hasura-user-id']}}"
},
"content_type": "application/json",
"body": "{\"username\": {{$body.input.username}}}"
}
},
"comment": "Custom action to create user"
}
}
```
</TabItem>
</Tabs>
### Context Variables {#action-transform-context-variables}
You can use context variables in the transforms to achieve dynamic behavior for each request.
The context variables available in transforms are:
| Context variable | Value |
|--------------------|------------------------------------------|
| $body | Original body of action request |
| $base_url | Original configured webhook handler URL |
| $session_variables | Session variables |
#### Console sample context {#action-transforms-sample-context}
The console allows you to preview your transforms while configuring them. To avoid exposing sensitive information on the console UI the actual environment variables configured on the server are not
resolved while displaying the previews. Also any session variables used in the transform will not be available at the time of configuration.
Hence, the console allows you to provide mock env variables and session variables to verify your transforms. If you configure your transforms without providing the mock env/session variables
you might see a UI validation error in the preview sections.
**For example:** If your webhook handler is set as an env var as shown below then pass a mock value for that env var in the sample context:
<Thumbnail
src="/img/graphql/core/actions/transform-sample-context-0.png"
alt="Console action webhook handler"
width="650px"
/>
You can enter the mock env/session variables under `Configure REST Connectors > Sample Context`:
<Thumbnail
src="/img/graphql/core/actions/transform-sample-context-1.png"
alt="Add generic sample context"
width="800px"
/>
:::info Note
As the sample context is only used for previews, you can still configure the transforms on the console without setting any sample context.
:::
## Types of transforms {#action-transform-types}
REST Connectors allow you to add different transforms to the default HTTP request. You can also use [context variables](#action-transform-context-variables)
in the transforms to achieve dynamic behavior for each request.
You can transform your:
<TOCInline toc={toc} filterTOC={(tocTree) => tocTree[2].children} />
### Request Method
You can change the request method to adapt to your API's expected format.
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
In the `Configure REST Connectors` section, click on `Add Request Options Transform`:
<Thumbnail
src="/img/graphql/core/actions/transform-method.png"
alt="Change request method"
width="800px"
/>
</TabItem>
<TabItem value="cli" label="CLI">
Update the `actions.yaml` file inside the `metadata` directory and add a [request_transform][RequestTransformation] field to the action:
```yaml {8}
- name: create_user
definition:
kind: synchronous
handler: https://action.my_app.com/create-user
timeout: 60
request_transform:
template_engine: Kriti
method: POST
content_type: application/json
url: '{{$base_url}}/create_user'
query_params:
id: '{{$session_variables[''x-hasura-user-id'']}}'
body: '{"username": {{$body.input.username}}}'
comment: Custom action to create user
```
Apply the metadata by running:
```bash
hasura metadata apply
```
</TabItem>
<TabItem value="api" label="API">
REST Connectors can be configured for actions using the [create_action][metadata-create-action] or
[update_action][metadata-update-action] metadata APIs by adding a
[request_transform][RequestTransformation] field to the args:
```http {26}
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type":"create_action",
"args":{
"name":"create_user",
"definition":{
"kind":"synchronous",
"arguments":[
{
"name":"username",
"type":"String!"
},
{
"name":"email",
"type":"String!"
}
],
"output_type":"User",
"handler":"{{ACTION_BASE_URL}}",
"timeout":60,
"request_transform": {
"template_engine": "Kriti",
"method": "POST",
"url": "{{$base_url}}/create_user",
"query_params": {
"id": "{{$session_variables['x-hasura-user-id']}}"
},
"content_type": "application/json",
"body": "{\"username\": {{$body.input.username}}}"
}
},
"comment": "Custom action to create user"
}
}
```
</TabItem>
</Tabs>
### Request URL
The Request URL template allows you to configure the exact API endpoint to call.
You can use the [context variables](#action-transform-context-variables) to construct the final URL.
You can also provide query params to add to the URL.
You can use the [Kriti templating language](https://github.com/hasura/kriti-lang) to construct any string values here.
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
In the `Configure REST Connectors` section, click on `Add Request Options Transform`:
<Thumbnail
src="/img/graphql/core/actions/transform-url.png"
alt="Change request URL"
width="800px"
/>
The value of the final url should be reflected in the `Preview` section given all required [sample context](#action-transforms-sample-context) is set.
Hit `Save Action` to apply your changes.
</TabItem>
<TabItem value="cli" label="CLI">
Update the `actions.yaml` file inside the `metadata` directory and add a [request_transform][RequestTransformation] field to the action:
```yaml {10-12}
- name: create_user
definition:
kind: synchronous
handler: https://action.my_app.com/create-user
timeout: 60
request_transform:
template_engine: Kriti
method: POST
content_type: application/json
url: '{{$base_url}}/create_user'
query_params:
id: '{{$session_variables[''x-hasura-user-id'']}}'
body: '{"username": {{$body.input.username}}}'
comment: Custom action to create user
```
Apply the metadata by running:
```bash
hasura metadata apply
```
</TabItem>
<TabItem value="api" label="API">
REST Connectors can be configured for actions using the [create_action][metadata-create-action] or
[update_action][metadata-update-action] metadata APIs by adding a
[request_transform][RequestTransformation] field to the args:
```HTTP {27-30}
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type":"create_action",
"args":{
"name":"create_user",
"definition":{
"kind":"synchronous",
"arguments":[
{
"name":"username",
"type":"String!"
},
{
"name":"email",
"type":"String!"
}
],
"output_type":"User",
"handler":"{{ACTION_BASE_URL}}",
"timeout":60,
"request_transform": {
"template_engine": "Kriti",
"method": "POST",
"url": "{{$base_url}}/create_user",
"query_params": {
"id": "{{$session_variables['x-hasura-user-id']}}"
},
"content_type": "application/json",
"body": "{\"username\": {{$body.input.username}}}"
}
},
"comment": "Custom action to create user"
}
}
```
</TabItem>
</Tabs>
:::info escapeUri
Note that you must use the `escapeUri` function to urlencode templated values.
For example, if you have to use session variables in the URL and those may contain non-ASCII values,
then you should provide the template URL as `{{$base_url}}/{{escapeUri $session_variables['x-hasura-user-id']}}`
:::
### Request Content-Type
You can change the `Content-Type` of the request to either `application/json` or `x-www-form-urlencoded`. The default is `application/json`.
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Console support coming soon.
</TabItem>
<TabItem value="cli" label="CLI">
Update the `actions.yaml` file inside the `metadata` directory and add a [request_transform][RequestTransformation] field to the action:
```yaml {9}
- name: create_user
definition:
kind: synchronous
handler: https://action.my_app.com/create-user
timeout: 60
request_transform:
template_engine: Kriti
method: POST
content_type: application/json
url: '{{$base_url}}/create_user'
query_params:
id: '{{$session_variables[''x-hasura-user-id'']}}'
body: '{"username": {{$body.input.username}}}'
comment: Custom action to create user
```
Apply the metadata by running:
```bash
hasura metadata apply
```
</TabItem>
<TabItem value="api" label="API">
REST Connectors can be configured for actions using the [create_action][metadata-create-action] or
[update_action][metadata-update-action] metadata APIs by adding a
[request_transform][RequestTransformation] field to the args:
```http {31}
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type":"create_action",
"args":{
"name":"create_user",
"definition":{
"kind":"synchronous",
"arguments":[
{
"name":"username",
"type":"String!"
},
{
"name":"email",
"type":"String!"
}
],
"output_type":"User",
"handler":"{{ACTION_BASE_URL}}",
"timeout":60,
"request_transform": {
"template_engine": "Kriti",
"method": "POST",
"url": "{{$base_url}}/create_user",
"query_params": {
"id": "{{$session_variables['x-hasura-user-id']}}"
},
"content_type": "application/json",
"body": "{\"username\": {{$body.input.username}}}"
}
},
"comment": "Custom action to create user"
}
}
```
</TabItem>
</Tabs>
With `x-www-form-urlencoded`, the key-value pairs in `body` are transformed to `name={{$body.input.name}}&key2={{$body.input.email}}`.
### Request Body
You can generate a custom request body by configuring a template to transform the default payload to a custom payload.
The `body` field takes a template in the [Kriti templating language](https://github.com/hasura/kriti-lang) to evaluate the transform.
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
In the `Configure REST Connectors` section, click on `Add Payload Transform`:
A sample payload input auto-generated based on your schema is shown.
<Thumbnail
src="/img/graphql/core/actions/transform-body.png"
alt="Add payload transformation"
width="1100px"
/>
The transformed sample payload should be shown as the `Transformed Request Body` given all required [sample context](#action-transforms-sample-context) is set.
Hit `Save Action` to apply your changes.
</TabItem>
<TabItem value="cli" label="CLI">
Update the `actions.yaml` file inside the `metadata` directory and add a [request_transform][RequestTransformation] field to the action:
```yaml {13}
- name: create_user
definition:
kind: synchronous
handler: https://action.my_app.com/create-user
timeout: 60
request_transform:
template_engine: Kriti
method: POST
content_type: application/json
url: '{{$base_url}}/create_user'
query_params:
id: '{{$session_variables[''x-hasura-user-id'']}}'
body: '{"username": {{$body.input.username}}}'
comment: Custom action to create user
```
Apply the metadata by running:
```bash
hasura metadata apply
```
</TabItem>
<TabItem value="api" label="API">
REST Connectors can be configured for actions using the [create_action][metadata-create-action] or
[update_action][metadata-update-action] metadata APIs by adding a
[request_transform][RequestTransformation] field to the args:
```http {32}
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type":"create_action",
"args":{
"name":"create_user",
"definition":{
"kind":"synchronous",
"arguments":[
{
"name":"username",
"type":"String!"
},
{
"name":"email",
"type":"String!"
}
],
"output_type":"User",
"handler":"{{ACTION_BASE_URL}}",
"timeout":60,
"request_transform": {
"template_engine": "Kriti",
"method": "POST",
"url": "{{$base_url}}/create_user",
"query_params": {
"id": "{{$session_variables['x-hasura-user-id']}}"
},
"content_type": "application/json",
"body": "{\"username\": {{$body.input.username}}}"
}
},
"comment": "Custom action to create user"
}
}
```
</TabItem>
</Tabs>
## Example
Let's integrate Auth0's management API to update the profile of a user:
<Tabs className="api-tabs">
<TabItem value="console" label="Console">
Go to the `Actions` tab on the console and create or modify an action. Scroll down to `Configure REST Connectors` section:
Action definition:
<Thumbnail
src="/img/graphql/core/actions/example-transformation-0.png"
alt="Example rest connector for actions"
width="1100px"
/>
The transformation is given by:
<Thumbnail
src="/img/graphql/core/actions/example-transformation-1.png"
alt="Example rest connector for actions"
width="800px"
/>
<Thumbnail
src="/img/graphql/core/actions/example-transformation-2.png"
alt="Example rest connector for actions"
width="1000px"
/>
</TabItem>
<TabItem value="cli" label="CLI">
To be added
</TabItem>
<TabItem value="api" label="API">
Action definition:
```graphql
type Mutation {
updateProfile(picture_url : String!) : ProfileOutput
}
type ProfileOutput {
id: String!
user_metadata: String!
}
```
The transform is given by:
```json
{
"request_transform": {
"body": "{\"user_metadata\": {\"picture\": {{$body.input.picture_url}} } }",
"url": "{{$base_url}}/{{$session_variables['x-hasura-user-id']}}",
"method": "PATCH"
}
}
```
</TabItem>
</Tabs>
<!-- Shared Link Variables -->
[metadata-create-action]: /graphql/core/api-reference/metadata-api/actions.mdx#metadata-create-action
[metadata-update-action]: /graphql/core/api-reference/metadata-api/actions.mdx#metadata-update-action
[RequestTransformation]: /graphql/core/api-reference/syntax-defs.mdx#requesttransformation

View File

@ -0,0 +1,262 @@
---
sidebar_label: Custom types
sidebar_position: 2
description: Custom GraphQL types for Hasura actions
keywords:
- hasura
- docs
- actions
- custom types
# adding to avoid redirect as this was only index file under the directory
slug: types/index
---
# Custom GraphQL types
## Introduction
You can add custom GraphQL types in Hasura that you can utilise for
defining your actions.
:::caution Limitations
It is currently not possible to define `Interfaces` and `Union types` as
custom types
:::
## Object types
The most basic components of a GraphQL schema are object types, which
just represent a kind of object a GraphQL query can return, and what
fields it has. In the GraphQL SDL, we might represent it like this:
```graphql
type UserInfo {
accessToken: String!
userId: Int!
}
```
This is an object type called `UserInfo` that has two fields:
- `accessToken`: This field is of type `String!` (non-nullable
`String`)
- `userId`: This field is of type `Int!` (non-nullable `Int`)
From version `v2.2.0` onwards, Hasura GraphQL engine supports nested objects.
For example, you can define a type like the following:
```graphql
type UserInfo {
accessToken: String!
userId: Int!
user: UserObj!
}
type UserObj {
name: String!
favFood: String!
isAdmin: Boolean!
}
```
Recursive nested objects are also supported.
For example, you can use the following type:
```graphql
type UserObj {
name: String!
favFood: String!
isAdmin: Boolean!
friends: [UserObj]!
}
```
[See reference](https://graphql.org/learn/schema/#object-types-and-fields)
### Relationships
Custom object types can be connected to the rest of the graph by setting up
[action relationships](/graphql/core/databases/postgres/schema/remote-relationships/action-relationships.mdx) with tables/views.
**For example**, given the object type:
```graphql
type UserInfo {
accessToken: String!
userId: Int!
}
```
and tables:
```sql
user (id int, name text)
order (id int, user_id int, ...)
```
We can create:
- an **object relationship** called `loggedInUser` between the
`UserInfo` object type and the `user` table via the
`UserInfo.userId` and `user.id` fields.
- an **array relationship** called `userOrders` between the `UserInfo`
object type and the `order` table via the `UserInfo.userId` and
`order.user_id` fields.
The object type will now be modified as:
```graphql {4,5}
type UserInfo {
accessToken: String!
userId: Int!
loggedInUser: user
userOrders: [order]
}
```
:::info Note
Only fields with non-list scalar types (e.g. `Int`, `String`) can be
used to define relationships
:::
:::caution Limitations
Hasura has the following limitations for relationship in nested object
types:
1. For nested objects, relationships can only be defined for top-level
fields. For example, for the following type definition:
```graphql
type UserInfo {
accessToken: String!
userId: Int!
user: UserObj!
}
type UserObj {
name: String!
favFood: String!
isAdmin: Boolean!
}
```
relationships can only be defined using `accessToken` and `userID`,
you cannot use `name`, `favFood` or `isAdmin` fields in a
relationship definition.
2. For `async` actions, you cannot have nested object types and
relationships in the same action.
:::
## Input types
You can pass complex objects as arguments to queries and mutations. This
is particularly valuable in cases where you might want to pass in a
whole object to be created. In the GraphQL SDL, input types look exactly
the same as regular object types, but with the keyword input instead of
type:
```graphql
input LoginInfo {
username: String!
password: String!
}
```
A field of an input type could be a `scalar`, an `enum` or another input
type.
[See reference](https://graphql.org/learn/schema/#input-types)
## Scalar types
A GraphQL object type has a name and fields, but at some point those
fields have to resolve to some concrete data. That's where the scalar
types come in: they represent the leaves of the query.
### Inbuilt scalars
Hasura comes with some default GraphQL scalars that you can directly
start using while defining your actions:
- `Int`: A signed 32bit integer.
- `Float`: A signed double-precision floating-point value.
- `String`: A UTF8 character sequence.
- `Boolean`: true or false.
- `ID`: The ID scalar type represents a unique identifier, often used
to refetch an object or as the key for a cache. The ID type is
serialized in the same way as a String; however, defining it as an
ID signifies that it is not intended to be humanreadable.
[See reference](https://graphql.org/learn/schema/#scalar-types)
### Custom scalars
Hasura allows you to define custom scalars. For example, if you want to
define a scalar called `Date`, you can define it like.
```graphql
scalar Date
```
These scalars can be used as arguments of queries and mutations or as
fields of object types and input types.
:::info Postgres scalars
Postgres base types are implicitly made available as GraphQL scalars;
there is no need to declare them separately. For example, in the
definition
```graphql
type User {
id: uuid!
name: String!
location: geography
}
```
the `uuid` and `geography` types are assumed to refer to Postgres
scalars (assuming no other definition for them is provided).
:::
## Enum types
Enums are a special kind of scalar that is restricted to a particular
set of allowed values. This allows you to:
- Validate that any arguments of this type are one of the allowed
values
- Communicate through the type system that a field will always be one
of a finite set of values
Here's what an enum definition might look like in the GraphQL schema
language:
```graphql
enum Color {
RED
GREEN
BLUE
}
```
This means that wherever we use the type `Color` in our schema, we
expect it to be exactly one of RED, GREEN, or BLUE.
[See reference](https://graphql.org/learn/schema/#enumeration-types)
:::info Additional Resources
Introduction to Hasura Actions - [View Recording](https://hasura.io/events/webinar/hasura-actions/?pg=docs&plcmt=body&cta=view-recording&tech=).
:::

View File

@ -0,0 +1,4 @@
{
"label": "API Reference",
"position": 11
}

View File

@ -0,0 +1,69 @@
---
sidebar_label: Config API
sidebar_position: 10
description: Hasura config API reference
keywords:
- hasura
- docs
- config API
- API reference
---
# Config API Reference
## Introduction
The Config API is an admin only endpoint which gives info on the server configuration.
## Endpoint
All requests are `GET` requests to the `/v1alpha1/config` endpoint.
## API Spec
### Request
```http
GET /v1alpha1/config HTTP/1.1
X-Hasura-Role: admin
```
### Sample response
```http
HTTP/1.1 200 OK
Content-Type: application/json
{
"version": "v1.0.0-beta.3",
"is_function_permissions_inferred": true,
"is_remote_schema_permissions_enabled": false,
"is_admin_secret_set": true,
"is_auth_hook_set": false,
"is_jwt_set": true,
"jwt": {
"claims_namespace": "https://hasura.io/jwt/claims",
"claims_format": "json"
},
"is_allow_list_enabled": false,
"live_queries": {
"batch_size": 100,
"refetch_delay": 1
}
}
```
## Disabling Config API
The `enabled-apis` flag or the `HASURA_GRAPHQL_ENABLED_APIS` env var can
be used to enable/disable this API. By default, this API is enabled. To
disable it, you need to explicitly state that this API is not enabled.
i.e. remove it from the list of enabled APIs.
```bash
# enable only graphql & metadata apis, disable config
--enabled-apis="graphql,metadata"
HASURA_GRAPHQL_ENABLED_APIS="graphql,metadata"
```
See [GraphQL Engine server config reference](/graphql/core/deployment/graphql-engine-flags/reference.mdx) for info on setting the above flag/env var.

View File

@ -0,0 +1,177 @@
---
sidebar_label: Explain API
sidebar_position: 11
description: Hasura explain API reference
keywords:
- hasura
- docs
- explain API
- API reference
---
# Explain API Reference
## Introduction
The Explain API is an admin-only endpoint for analysing queries and
subscriptions. Given a query and authorization role, it returns
backend-specific execution plans.
## Endpoint
All requests are `POST` requests to the `/v1/graphql/explain` endpoint.
## API Spec
### Request
The request expects a JSON object with the following keys:
- `query`: the GraphQL query to be analysed
- `user` (optional): the `x-hasura-role` along with session variables
```http
POST /v1/graphql/explain HTTP/1.1
Content-Type: application/json
{
"query": "<query>",
"user": {
"x-hasura-role" : "...",
"x-hasura-session-var1" : "..."
}
}
```
#### Sample request
```http
POST /v1/graphql/explain HTTP/1.1
Content-Type: application/json
{
"query": {
"query": "query getUsers { user { name }}",
"operationName": "getUsers"
}
}
```
### Response
The response for a query is a list of plans, one for each field:
```none
[
{
"field": String -- "name of the field",
"sql": String -- "generated SQL for the operation",
"plan": [String] -- "the database's execution plan for the generated SQL"
}
]
```
The response for a subscription is a single plan, along with the
variables used to determine how the subscription will be multiplexed:
```none
{
"sql": String -- "generated SQL for the operation",
"plan": [String] -- "the database's execution plan for the generated SQL"
"variables": {
"synthetic": [String], -- "introduced variables for enabling additional query multiplexing (values)"
"query": Object -- "GraphQL query variables (names and values)"
"session": Object -- "session variables referenced by the query (names and values)"
}
}
```
#### Sample response for a query
PostgreSQL backend:
```json
[
{
"field": "user",
"sql": "SELECT coalesce(json_agg(\"root\" ), '[]' ) AS \"root\" FROM (SELECT row_to_json((SELECT \"_1_e\" FROM (SELECT \"_0_root.base\".\"name\" AS \"name\" ) AS \"_1_e\" ) ) AS \"root\" FROM (SELECT * FROM \"public\".\"user\" WHERE ('true') ) AS \"_0_root.base\" ) AS \"_2_root\" ",
"plan": [
"Aggregate (cost=40.00..40.01 rows=1 width=32)",
" -> Seq Scan on \"user\" (cost=0.00..22.00 rows=1200 width=32)",
" SubPlan 1",
" -> Result (cost=0.00..0.01 rows=1 width=32)"
]
}
]
```
Microsoft SQL Server backend:
```json
[
{
"field": "user",
"sql": "SELECT ISNULL((SELECT [t_user1].[name] AS [name]\nFROM [dbo].[user] AS [t_user1]\nFOR JSON PATH, INCLUDE_NULL_VALUES), '[]')",
"plan": [
"SELECT ISNULL((SELECT [t_user1].[name] AS [name]\nFROM [dbo].[user] AS [t_user1]\nFOR JSON PATH, INCLUDE_NULL_VALUES), '[]')",
" |--Compute Scalar(DEFINE:([Expr1003]=isnull([Expr1001],CONVERT_IMPLICIT(nvarchar(max),'[]',0))))",
" |--UDX(([t_user1].[name]))",
" |--Clustered Index Scan(OBJECT:([master].[dbo].[user].[PK__user__3213E83F04195C1B] AS [t_user1]))"
]
}
]
```
#### Sample response for a subscription
PostgreSQL backend:
```json
{
"sql": "SELECT \"_subs\".\"result_id\" , \"_fld_resp\".\"root\" AS \"result\" FROM UNNEST(($1)::uuid[], ($2)::json[]) AS \"_subs\"(\"result_id\", \"result_vars\") LEFT OUTER JOIN LATERAL (SELECT json_build_object('user', \"user\".\"root\" ) AS \"root\" FROM (SELECT coalesce(json_agg(\"root\" ), '[]' ) AS \"root\" FROM (SELECT row_to_json((SELECT \"_1_e\" FROM (SELECT \"_0_root.base\".\"name\" AS \"name\" ) AS \"_1_e\" ) ) AS \"root\" FROM (SELECT * FROM \"public\".\"user\" WHERE ('true') ) AS \"_0_root.base\" ) AS \"_2_root\" ) AS \"user\" ) AS \"_fld_resp\" ON ('true') ",
"plan": [
"Nested Loop Left Join (cost=40.01..42.28 rows=100 width=48)",
" -> Function Scan on _subs (cost=0.01..1.00 rows=100 width=16)",
" -> Materialize (cost=40.00..40.03 rows=1 width=32)",
" -> Subquery Scan on \"user\" (cost=40.00..40.02 rows=1 width=32)",
" -> Aggregate (cost=40.00..40.01 rows=1 width=32)",
" -> Seq Scan on \"user\" user_1 (cost=0.00..22.00 rows=1200 width=32)",
" SubPlan 1",
" -> Result (cost=0.00..0.01 rows=1 width=32)"
],
"variables": {
"synthetic": [],
"query": {},
"session": {}
}
}
```
Microsoft SQL Server backend:
```json
{
"sql": "SELECT ISNULL((SELECT [row].[result_id] AS [result_id],\n [result].[json] AS [result]\nFROM OPENJSON((N''+NCHAR(91)+''+NCHAR(91)+''+NCHAR(34)+'00000000-0000-0000-0000-000000000000'+NCHAR(34)+','+NCHAR(123)+''+NCHAR(34)+'synthetic'+NCHAR(34)+''+NCHAR(58)+''+NCHAR(91)+''+NCHAR(93)+','+NCHAR(34)+'query'+NCHAR(34)+''+NCHAR(58)+''+NCHAR(123)+''+NCHAR(125)+','+NCHAR(34)+'session'+NCHAR(34)+''+NCHAR(58)+''+NCHAR(123)+''+NCHAR(125)+''+NCHAR(125)+''+NCHAR(93)+''+NCHAR(93)+''))\n WITH ([result_id] UNIQUEIDENTIFIER '$[0]',\n [result_vars] NVARCHAR(MAX) '$[1]' AS JSON) AS [row]\nOUTER APPLY (SELECT ISNULL((SELECT (SELECT ISNULL((SELECT [t_user1].[name] AS [name]\n FROM [dbo].[user] AS [t_user1]\n FOR JSON PATH, INCLUDE_NULL_VALUES), '[]')) AS [user]\n FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER), '[]')) \nAS [result]([json])\nFOR JSON PATH, INCLUDE_NULL_VALUES), '[]')",
"plan": [
"SELECT ISNULL((SELECT [row].[result_id] AS [result_id],\n [result].[json] AS [result]\nFROM OPENJSON((N''+NCHAR(91)+''+NCHAR(91)+''+NCHAR(34)+'00000000-0000-0000-0000-000000000000'+NCHAR(34)+','+NCHAR(123)+''+NCHAR(34)+'synthetic'+NCHAR(34)+''+NCHAR(58)+''+NCHAR(91)+''+NCHAR(93)+','+NCHAR(34)+'query'+NCHAR(34)+''+NCHAR(58)+''+NCHAR(123)+''+NCHAR(125)+','+NCHAR(34)+'session'+NCHAR(34)+''+NCHAR(58)+''+NCHAR(123)+''+NCHAR(125)+''+NCHAR(125)+''+NCHAR(93)+''+NCHAR(93)+''))\n WITH ([result_id] UNIQUEIDENTIFIER '$[0]',\n [result_vars] NVARCHAR(MAX) '$[1]' AS JSON) AS [row]\nOUTER APPLY (SELECT ISNULL((SELECT (SELECT ISNULL((SELECT [t_user1].[name] AS [name]\n FROM [dbo].[user] AS [t_user1]\n FOR JSON PATH, INCLUDE_NULL_VALUES), '[]')) AS [user]\n FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER), '[]')) \nAS [result]([json])\nFOR JSON PATH, INCLUDE_NULL_VALUES), '[]')",
" |--Compute Scalar(DEFINE:([Expr1010]=isnull([Expr1008],CONVERT_IMPLICIT(nvarchar(max),'[]',0))))",
" |--UDX((OPENJSON_EXPLICIT.[result_id], [Expr1007]))",
" |--Nested Loops(Left Outer Join)",
" |--Table-valued function",
" |--Compute Scalar(DEFINE:([Expr1007]=isnull([Expr1005],CONVERT_IMPLICIT(nvarchar(max),'[]',0))))",
" |--UDX(([Expr1004]))",
" |--Compute Scalar(DEFINE:([Expr1004]=isnull([Expr1001],CONVERT_IMPLICIT(nvarchar(max),'[]',0))))",
" |--UDX(([t_user1].[name]))",
" |--Clustered Index Scan(OBJECT:([master].[dbo].[user].[PK__user__3213E83F9704D3EC] AS [t_user1]))"
],
"variables": {
"synthetic": [],
"query": {},
"session": {}
}
}
```
## Disabling Explain API
The Explain API is part of the [Metadata API](/graphql/core/api-reference/metadata-api/index.mdx) and can
only be disabled by disabling the same.

View File

@ -0,0 +1,4 @@
{
"label": "GraphQL API",
"position": 1
}

Some files were not shown because too many files have changed in this diff Show More