planetscale-api
v0.0.1
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *planetscale-api* API.
Readme
planetscale-api
Developer-friendly & type-safe Typescript SDK specifically catered to leverage planetscale-api API.
[!IMPORTANT] This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Summary
PlanetScale API:
Table of Contents
SDK Installation
[!TIP] To finish publishing your SDK to npm and others you must run your first generation action.
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add <UNSET>PNPM
pnpm add <UNSET>Bun
bun add <UNSET>Yarn
yarn add <UNSET>[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { Planetscale } from "planetscale-api";
const planetscale = new Planetscale({
apiKeyHeader: process.env["PLANETSCALE_API_KEY_HEADER"] ?? "",
});
async function run() {
const result = await planetscale.organizations.listOrganizations({});
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
| -------------- | ------ | ------- | ---------------------------- |
| apiKeyHeader | apiKey | API key | PLANETSCALE_API_KEY_HEADER |
To authenticate with the API the apiKeyHeader parameter must be set when initializing the SDK client instance. For example:
import { Planetscale } from "planetscale-api";
const planetscale = new Planetscale({
apiKeyHeader: process.env["PLANETSCALE_API_KEY_HEADER"] ?? "",
});
async function run() {
const result = await planetscale.organizations.listOrganizations({});
console.log(result);
}
run();
Available Resources and Operations
apiBranchBouncerResizes
- listBranchBouncerResizeRequests - Get bouncer resize requests
backups
- listBackups - List backups
- createBackup - Create a backup
- getBackup - Get a backup
- updateBackup - Update a backup
- deleteBackup - Delete a backup
bouncerResizes
- listBouncerResizeRequests - Get bouncer resize requests
- updateBouncerResizeRequest - Upsert a bouncer resize request
- cancelBouncerResizeRequest - Cancel a resize request
bouncers
- listBouncers - List bouncers
- createBouncer - Create a bouncer
- getBouncer - Get a bouncer
- deleteBouncer - Delete a bouncer
branchChanges
- listBranchChangeRequests - Get branch change requests
- updateBranchChangeRequest - Upsert a change request
- cancelBranchChangeRequest - Cancel a change request
clusterExtensions
- listExtensions - List cluster extensions
clusterParameters
- listParameters - List cluster parameters
databaseBranches
- listBranches - List branches
- createBranch - Create a branch
- getBranch - Get a branch
- deleteBranch - Delete a branch
- updateBranchClusterConfig - Change a branch cluster configuration
- demoteBranch - Demote a branch
- promoteBranch - Promote a branch
- enableSafeMigrations - Enable safe migrations for a branch
- disableSafeMigrations - Disable safe migrations for a branch
- getBranchSchema - Get a branch schema
- lintBranchSchema - Lint a branch schema
databaseBranchKeyspaces
- listKeyspaces - Get keyspaces
- createKeyspace - Create a keyspace
- getKeyspace - Get a keyspace
- updateKeyspace - Configure keyspace settings
- deleteKeyspace - Delete a keyspace
- getKeyspaceRolloutStatus - Get keyspace rollout status
databaseBranchPasswords
- listPasswords - List passwords
- createPassword - Create a password
- getPassword - Get a password
- updatePassword - Update a password
- deletePassword - Delete a password
- renewPassword - Renew a password
databasePostgresIPRestrictions
- listDatabasePostgresCidrs - List IP restriction entries
- createDatabasePostgresCidr - Create an IP restriction entry
- getDatabasePostgresCidr - Get an IP restriction entry
- updateDatabasePostgresCidr - Update an IP restriction entry
- deleteDatabasePostgresCidr - Delete an IP restriction entry
databases
- listDatabases - List databases
- createDatabase - Create a database
- getDatabaseThrottler - Get database throttler configurations
- updateDatabaseThrottler - Update database throttler configurations
- getDatabase - Get a database
- updateDatabaseSettings - Update database settings
- deleteDatabase - Delete a database
- listReadOnlyRegions - List read-only regions
- listDatabaseRegions - List database regions
deployRequests
- getDeployQueue - Get the deploy queue
- listDeployRequests - List deploy requests
- createDeployRequest - Create a deploy request
- getDeployRequest - Get a deploy request
- closeDeployRequest - Close a deploy request
- completeGatedDeployRequest - Complete a gated deploy request
- updateAutoApply - Update auto-apply for deploy request
- cancelDeployRequest - Cancel a queued deploy request
- completeErroredDeploy - Complete an errored deploy
- queueDeployRequest - Queue a deploy request
- getDeployment - Get a deployment
- listDeployOperations - List deploy operations
- completeRevert - Complete a revert
- listDeployRequestReviews - List deploy request reviews
- reviewDeployRequest - Review a deploy request
- skipRevertPeriod - Skip revert period
- getDeployRequestThrottler - Get deploy request throttler configurations
- updateDeployRequestThrottler - Update deploy request throttler configurations
invoices
- listInvoices - Get invoices
- getInvoice - Get an invoice
- getInvoiceLineItems - Get invoice line items
keyspaceVSchemas
- getKeyspaceVschema - Get the VSchema for the keyspace
- updateKeyspaceVschema - Update the VSchema for the keyspace
oAuthApplications
- listOauthApplications - List OAuth applications
- getOauthApplication - Get an OAuth application
- listOauthTokens - List OAuth tokens
- getOauthToken - Get an OAuth token
- deleteOauthToken - Delete an OAuth token
oAuthTokens
- createOauthToken - Create or renew an OAuth token
organizationMembers
- listOrganizationMembers - List organization members
- getOrganizationMembership - Get an organization member
- updateOrganizationMembership - Update organization member role
- removeOrganizationMember - Remove a member from an organization
organizations
- listOrganizations - List organizations
- getOrganization - Get an organization
- updateOrganization - Update an organization
- listAuditLogs - List audit logs
- listClusterSizeSkus - List available cluster sizes
- listRegionsForOrganization - List regions for an organization
organizationTeams
- listOrganizationTeams - List teams in an organization
- createOrganizationTeam - Create an organization team
- getOrganizationTeam - Get an organization team
- updateOrganizationTeam - Update an organization team
- deleteOrganizationTeam - Delete an organization team
queryInsightsReports
- listGeneratedQueryPatternsReports - List generated query patterns reports
- createQueryPatternsReport - Create a new query patterns report
- getQueryPatternsReportStatus - Show the status of a query patterns report
- deleteQueryPatternsReport - Delete a query patterns report
- getQueryPatternsReport - Download a finished query patterns report
regions
- listPublicRegions - List public regions
roles
- listRoles - List roles
- createRole - Create role credentials
- getRole - Get a role
- updateRole - Update role name
- deleteRole - Delete role credentials
- renewRole - Renew role expiration
users
- getCurrentUser - Get current user
webhooks
- listWebhooks - List webhooks
- createWebhook - Create a webhook
- getWebhook - Get a webhook
- updateWebhook - Update a webhook
- deleteWebhook - Delete a webhook
- testWebhook - Test a webhook
workflows
- listWorkflows - List workflows
- createWorkflow - Create a workflow
- getWorkflow - Get a workflow
- workflowCancel - Cancel a workflow
- workflowComplete - Complete a workflow
- workflowCutover - Cutover traffic
- workflowRetry - Retry a failed workflow
- workflowReverseCutover - Reverse traffic cutover
- workflowReverseTraffic - Reverse traffic
- workflowSwitchPrimaries - Switch primary traffic
- workflowSwitchReplicas - Switch replica traffic
- verifyWorkflow - Verify workflow data
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
apiBranchBouncerResizesListBranchBouncerResizeRequests- Get bouncer resize requestsbackupsCreateBackup- Create a backupbackupsDeleteBackup- Delete a backupbackupsGetBackup- Get a backupbackupsListBackups- List backupsbackupsUpdateBackup- Update a backupbouncerResizesCancelBouncerResizeRequest- Cancel a resize requestbouncerResizesListBouncerResizeRequests- Get bouncer resize requestsbouncerResizesUpdateBouncerResizeRequest- Upsert a bouncer resize requestbouncersCreateBouncer- Create a bouncerbouncersDeleteBouncer- Delete a bouncerbouncersGetBouncer- Get a bouncerbouncersListBouncers- List bouncersbranchChangesCancelBranchChangeRequest- Cancel a change requestbranchChangesListBranchChangeRequests- Get branch change requestsbranchChangesUpdateBranchChangeRequest- Upsert a change requestclusterExtensionsListExtensions- List cluster extensionsclusterParametersListParameters- List cluster parametersdatabaseBranchesCreateBranch- Create a branchdatabaseBranchesDeleteBranch- Delete a branchdatabaseBranchesDemoteBranch- Demote a branchdatabaseBranchesDisableSafeMigrations- Disable safe migrations for a branchdatabaseBranchesEnableSafeMigrations- Enable safe migrations for a branchdatabaseBranchesGetBranch- Get a branchdatabaseBranchesGetBranchSchema- Get a branch schemadatabaseBranchesLintBranchSchema- Lint a branch schemadatabaseBranchesListBranches- List branchesdatabaseBranchesPromoteBranch- Promote a branchdatabaseBranchesUpdateBranchClusterConfig- Change a branch cluster configurationdatabaseBranchKeyspacesCreateKeyspace- Create a keyspacedatabaseBranchKeyspacesDeleteKeyspace- Delete a keyspacedatabaseBranchKeyspacesGetKeyspace- Get a keyspacedatabaseBranchKeyspacesGetKeyspaceRolloutStatus- Get keyspace rollout statusdatabaseBranchKeyspacesListKeyspaces- Get keyspacesdatabaseBranchKeyspacesUpdateKeyspace- Configure keyspace settingsdatabaseBranchPasswordsCreatePassword- Create a passworddatabaseBranchPasswordsDeletePassword- Delete a passworddatabaseBranchPasswordsGetPassword- Get a passworddatabaseBranchPasswordsListPasswords- List passwordsdatabaseBranchPasswordsRenewPassword- Renew a passworddatabaseBranchPasswordsUpdatePassword- Update a passworddatabasePostgresIPRestrictionsCreateDatabasePostgresCidr- Create an IP restriction entrydatabasePostgresIPRestrictionsDeleteDatabasePostgresCidr- Delete an IP restriction entrydatabasePostgresIPRestrictionsGetDatabasePostgresCidr- Get an IP restriction entrydatabasePostgresIPRestrictionsListDatabasePostgresCidrs- List IP restriction entriesdatabasePostgresIPRestrictionsUpdateDatabasePostgresCidr- Update an IP restriction entrydatabasesCreateDatabase- Create a databasedatabasesDeleteDatabase- Delete a databasedatabasesGetDatabase- Get a databasedatabasesGetDatabaseThrottler- Get database throttler configurationsdatabasesListDatabaseRegions- List database regionsdatabasesListDatabases- List databasesdatabasesListReadOnlyRegions- List read-only regionsdatabasesUpdateDatabaseSettings- Update database settingsdatabasesUpdateDatabaseThrottler- Update database throttler configurationsdeployRequestsCancelDeployRequest- Cancel a queued deploy requestdeployRequestsCloseDeployRequest- Close a deploy requestdeployRequestsCompleteErroredDeploy- Complete an errored deploydeployRequestsCompleteGatedDeployRequest- Complete a gated deploy requestdeployRequestsCompleteRevert- Complete a revertdeployRequestsCreateDeployRequest- Create a deploy requestdeployRequestsGetDeployment- Get a deploymentdeployRequestsGetDeployQueue- Get the deploy queuedeployRequestsGetDeployRequest- Get a deploy requestdeployRequestsGetDeployRequestThrottler- Get deploy request throttler configurationsdeployRequestsListDeployOperations- List deploy operationsdeployRequestsListDeployRequestReviews- List deploy request reviewsdeployRequestsListDeployRequests- List deploy requestsdeployRequestsQueueDeployRequest- Queue a deploy requestdeployRequestsReviewDeployRequest- Review a deploy requestdeployRequestsSkipRevertPeriod- Skip revert perioddeployRequestsUpdateAutoApply- Update auto-apply for deploy requestdeployRequestsUpdateDeployRequestThrottler- Update deploy request throttler configurationsinvoicesGetInvoice- Get an invoiceinvoicesGetInvoiceLineItems- Get invoice line itemsinvoicesListInvoices- Get invoiceskeyspaceVSchemasGetKeyspaceVschema- Get the VSchema for the keyspacekeyspaceVSchemasUpdateKeyspaceVschema- Update the VSchema for the keyspaceoAuthApplicationsDeleteOauthToken- Delete an OAuth tokenoAuthApplicationsGetOauthApplication- Get an OAuth applicationoAuthApplicationsGetOauthToken- Get an OAuth tokenoAuthApplicationsListOauthApplications- List OAuth applicationsoAuthApplicationsListOauthTokens- List OAuth tokensoAuthTokensCreateOauthToken- Create or renew an OAuth tokenorganizationMembersGetOrganizationMembership- Get an organization memberorganizationMembersListOrganizationMembers- List organization membersorganizationMembersRemoveOrganizationMember- Remove a member from an organizationorganizationMembersUpdateOrganizationMembership- Update organization member roleorganizationsGetOrganization- Get an organizationorganizationsListAuditLogs- List audit logsorganizationsListClusterSizeSkus- List available cluster sizesorganizationsListOrganizations- List organizationsorganizationsListRegionsForOrganization- List regions for an organizationorganizationsUpdateOrganization- Update an organizationorganizationTeamsCreateOrganizationTeam- Create an organization teamorganizationTeamsDeleteOrganizationTeam- Delete an organization teamorganizationTeamsGetOrganizationTeam- Get an organization teamorganizationTeamsListOrganizationTeams- List teams in an organizationorganizationTeamsUpdateOrganizationTeam- Update an organization teamqueryInsightsReportsCreateQueryPatternsReport- Create a new query patterns reportqueryInsightsReportsDeleteQueryPatternsReport- Delete a query patterns reportqueryInsightsReportsGetQueryPatternsReport- Download a finished query patterns reportqueryInsightsReportsGetQueryPatternsReportStatus- Show the status of a query patterns reportqueryInsightsReportsListGeneratedQueryPatternsReports- List generated query patterns reportsregionsListPublicRegions- List public regionsrolesCreateRole- Create role credentialsrolesDeleteRole- Delete role credentialsrolesGetRole- Get a rolerolesListRoles- List rolesrolesRenewRole- Renew role expirationrolesUpdateRole- Update role nameusersGetCurrentUser- Get current userwebhooksCreateWebhook- Create a webhookwebhooksDeleteWebhook- Delete a webhookwebhooksGetWebhook- Get a webhookwebhooksListWebhooks- List webhookswebhooksTestWebhook- Test a webhookwebhooksUpdateWebhook- Update a webhookworkflowsCreateWorkflow- Create a workflowworkflowsGetWorkflow- Get a workflowworkflowsListWorkflows- List workflowsworkflowsVerifyWorkflow- Verify workflow dataworkflowsWorkflowCancel- Cancel a workflowworkflowsWorkflowComplete- Complete a workflowworkflowsWorkflowCutover- Cutover trafficworkflowsWorkflowRetry- Retry a failed workflowworkflowsWorkflowReverseCutover- Reverse traffic cutoverworkflowsWorkflowReverseTraffic- Reverse trafficworkflowsWorkflowSwitchPrimaries- Switch primary trafficworkflowsWorkflowSwitchReplicas- Switch replica traffic
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { Planetscale } from "planetscale-api";
const planetscale = new Planetscale({
apiKeyHeader: process.env["PLANETSCALE_API_KEY_HEADER"] ?? "",
});
async function run() {
const result = await planetscale.organizations.listOrganizations({}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Planetscale } from "planetscale-api";
const planetscale = new Planetscale({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
apiKeyHeader: process.env["PLANETSCALE_API_KEY_HEADER"] ?? "",
});
async function run() {
const result = await planetscale.organizations.listOrganizations({});
console.log(result);
}
run();
Error Handling
PlanetscaleError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | ------------------------------------------------------ |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
Example
import { Planetscale } from "planetscale-api";
import * as errors from "planetscale-api/models/errors";
const planetscale = new Planetscale({
apiKeyHeader: process.env["PLANETSCALE_API_KEY_HEADER"] ?? "",
});
async function run() {
try {
const result = await planetscale.organizations.listOrganizations({});
console.log(result);
} catch (error) {
if (error instanceof errors.PlanetscaleError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
}
}
}
run();
Error Classes
Primary error:
PlanetscaleError: The base class for HTTP error responses.
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from PlanetscaleError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { Planetscale } from "planetscale-api";
const planetscale = new Planetscale({
serverURL: "https://api.planetscale.com/v1",
apiKeyHeader: process.env["PLANETSCALE_API_KEY_HEADER"] ?? "",
});
async function run() {
const result = await planetscale.organizations.listOrganizations({});
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest" hook to to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:
import { Planetscale } from "planetscale-api";
import { HTTPClient } from "planetscale-api/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new Planetscale({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Planetscale } from "planetscale-api";
const sdk = new Planetscale({ debugLogger: console });You can also enable a default debug logger by setting an environment variable PLANETSCALE_DEBUG to true.
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
