Skip to content

graphlit/graphlit-portal-client-typescript

Repository files navigation

Graphlit Portal Client SDK

npm version License: MIT

The official TypeScript/JavaScript SDK for the Graphlit Platform Control Plane API - programmatically manage your infrastructure, projects, and organization.

🚀 What is the Graphlit Portal Client?

The Portal Client SDK enables infrastructure-as-code for Graphlit - automate project management, billing, and organization settings through a clean TypeScript/JavaScript API.

Use Cases:

  • DevOps Automation - Create/destroy projects in CI/CD pipelines
  • Multi-tenant Apps - Provision projects per customer
  • Infrastructure Management - Manage environments, billing, and quotas
  • Testing - Spin up ephemeral test projects
  • Monitoring - Query project status and usage

✨ Key Features

  • 🏗️ Project Management - Full CRUD operations for Graphlit projects
  • 💳 Subscription Control - Upgrade/downgrade project tiers programmatically
  • 🔐 API Key Auth - Secure organization-level access with API keys
  • 🌍 Multi-Environment - Switch between production and development APIs
  • 📘 Full TypeScript - Auto-generated types from GraphQL schema
  • 🔄 GraphQL Native - Built on Apollo Client for reliability

📋 Table of Contents

Quick Start

Get started in 2 minutes:

# Install the SDK
npm install graphlit-portal-client

# Set your credentials (from https://portal.graphlit.dev/api-keys)
export GRAPHLIT_API_KEY=glk_live_your_key_here
export GRAPHLIT_ORGANIZATION_ID=your_org_guid_here
import { GraphlitPortalClient } from "graphlit-portal-client";

// Initialize client (uses env vars automatically)
const client = new GraphlitPortalClient();

// Create a project (platform and region are automatically configured)
const project = await client.createProject({
  name: "My Production App",
  description: "Production environment",
});

console.log(`Created project: ${project.createProject?.name}`);
console.log(`Project ID: ${project.createProject?.id}`);
console.log(`Data API: ${project.createProject?.uri}`);

Installation

npm install graphlit-portal-client

Requirements:

  • Node.js 18.0 or higher
  • TypeScript 5.0 or higher (for TypeScript projects)

Getting API Keys

To use this SDK, you need an organization API key:

  1. Go to Graphlit Portal
  2. Navigate to your organization → API Keys
  3. Click Create API Key
  4. Give it a name (e.g., "CI/CD Pipeline", "Production Server")
  5. Copy the key immediately - it's shown only once!
  6. Store it securely (environment variables, secrets manager, etc.)

⚠️ Security Note: API keys have full access to your organization. Treat them like passwords:

  • Never commit them to version control
  • Use environment variables or secret management
  • Rotate keys periodically
  • Revoke immediately if compromised

Configuration

Option 1: Environment Variables (Recommended)

Create a .env file:

# Required
GRAPHLIT_API_KEY=glk_live_your_key_here
GRAPHLIT_ORGANIZATION_ID=your_org_guid_here
import { GraphlitPortalClient } from "graphlit-portal-client";

const client = new GraphlitPortalClient();
// Automatically uses environment variables

Option 2: Explicit Configuration

import { GraphlitPortalClient } from "graphlit-portal-client";

const client = new GraphlitPortalClient({
  apiKey: "glk_live_...",
  organizationId: "your-org-guid",
});

Option 3: Legacy Constructor (Backward Compatible)

const client = new GraphlitPortalClient(
  "glk_live_...", // apiKey
  "your-org-guid", // organizationId
  "https://portal.graphlit.io/api/v1/graphql", // portalUri (optional)
);

Basic Examples

Creating Your First Project

import { GraphlitPortalClient } from "graphlit-portal-client";

const client = new GraphlitPortalClient();

const project = await client.createProject({
  name: "Analytics Platform",
  description: "Customer analytics with AI",
});

console.log("Project created:", project.createProject);
console.log("Platform:", project.createProject?.platform); // Azure
console.log("Region:", project.createProject?.region); // southcentralus

Listing All Projects

// Query all projects
const results = await client.queryProjects();

results.projects?.results?.forEach((p) => {
  console.log(`${p.name} (${p.id})`);
  console.log(`  Platform: ${p.platform}`);
  console.log(`  Region: ${p.region}`);
  console.log(`  Data API: ${p.uri}`);
});

// With filtering
const filtered = await client.queryProjects({
  ids: ["project-id-1", "project-id-2"],
});

Getting Project Details

const project = await client.getProject("project-id");

console.log("Project:", project.project?.name);
console.log("Created:", project.project?.creationDate);
console.log("Platform:", project.project?.platform);
console.log("State:", project.project?.state);

// Check quota usage
if (project.project?.quota) {
  console.log("Credits:", project.project.quota.credits);
}

Updating a Project

await client.updateProject({
  id: "project-id",
  name: "Updated Project Name",
  description: "New description",
});

console.log("Project updated successfully");

Upgrading Project Subscription

// Upgrade to Enterprise tier
await client.updateProjectSubscription("project-id", "prod_enterprise_monthly");

console.log("Subscription upgraded to Enterprise");

Deleting a Project

await client.deleteProject("project-id");
console.log("Project deleted");

API Reference

Project Operations

createProject(input: CreateProjectInput): Promise<CreateProjectMutation>

Create a new Graphlit project. Projects are automatically provisioned on Azure in the South Central US region.

Parameters:

  • name (string, required) - Project name
  • description (string, optional) - Project description

Returns: Created project with id, name, uri, platform (Azure), region (southcentralus), etc.

Example:

const project = await client.createProject({
  name: "Production App",
  description: "Main production environment",
});

console.log(`Project created: ${project.createProject?.id}`);
console.log(`Data Plane API: ${project.createProject?.uri}`);

updateProject(input: ProjectUpdateInput): Promise<UpdateProjectMutation>

Update an existing project's metadata.

Parameters:

  • id (string, required) - Project ID
  • name (string, optional) - New project name
  • description (string, optional) - New description

Example:

await client.updateProject({
  id: "proj_abc123",
  name: "Updated Name",
});

deleteProject(id: string): Promise<DeleteProjectMutation>

Permanently delete a project and all its data.

⚠️ Warning: This action is irreversible. All environments, data, and configurations will be deleted.

Parameters:

  • id (string, required) - Project ID to delete

Example:

await client.deleteProject("proj_abc123");

getProject(id: string): Promise<GetProjectQuery>

Retrieve detailed information about a specific project.

Parameters:

  • id (string, required) - Project ID

Returns: Project details including quota, subscription, and configuration

Example:

const result = await client.getProject("proj_abc123");
console.log(result.project?.name);

queryProjects(filter?: ProjectFilter): Promise<QueryProjectsQuery>

Query projects with optional filtering.

Parameters:

  • filter (ProjectFilter, optional) - Filter criteria
    • ids (string[]) - Filter by specific project IDs
    • Additional filters available in schema

Returns: Array of projects matching the filter

Example:

const results = await client.queryProjects({
  ids: ["proj_1", "proj_2"],
});

Subscription Management

updateProjectSubscription(id: string, productIdentifier: string): Promise<UpdateProjectSubscriptionMutation>

Upgrade or change a project's subscription tier.

Parameters:

  • id (string, required) - Project ID
  • productIdentifier (string, required) - Stripe product identifier (e.g., prod_starter_monthly, prod_enterprise_yearly)

Example:

await client.updateProjectSubscription(
  "proj_abc123",
  "prod_enterprise_monthly",
);

API Endpoint

The SDK connects to the Graphlit Portal API at:

https://portal.graphlit.io/api/v1/graphql

This is configured by default. You typically don't need to specify the portalUri unless you have a custom deployment.

Error Handling

Handle errors gracefully in your applications:

import { GraphlitPortalClient } from "graphlit-portal-client";

const client = new GraphlitPortalClient();

try {
  const project = await client.createProject({
    name: "New Project",
    description: "My new project",
  });

  console.log("Success:", project.createProject?.id);
} catch (error) {
  if (error instanceof Error) {
    console.error("Failed to create project:", error.message);

    // Check for specific error types
    if (error.message.includes("quota")) {
      console.error("Project quota exceeded");
    } else if (error.message.includes("authentication")) {
      console.error("Invalid API key or organization ID");
    }
  }
}

Common Error Scenarios

Error Cause Solution
API key is required Missing GRAPHLIT_API_KEY Set environment variable or pass to constructor
Organization ID is required Missing GRAPHLIT_ORGANIZATION_ID Set environment variable or pass to constructor
Failed to create project Invalid parameters or quota exceeded Check parameters and organization limits
Authentication failed Invalid API key Generate new API key in portal
Project not found Invalid project ID Verify project ID exists

TypeScript Support

The SDK is built with TypeScript and provides full type safety:

import {
  GraphlitPortalClient,
  CreateProjectInput,
  Project,
} from "graphlit-portal-client";

const client = new GraphlitPortalClient();

// Type-safe project creation
const input: CreateProjectInput = {
  name: "My Project",
  description: "Description",
};

const result = await client.createProject(input);

// Type-safe access to result
const project: Project | null | undefined = result.createProject;
if (project) {
  console.log(project.id); // TypeScript knows these properties exist
  console.log(project.name);
  console.log(project.uri);
  console.log(project.platform); // Azure
  console.log(project.region); // southcentralus
}

Available Types

All types are auto-generated from the GraphQL schema:

import type {
  // Input types
  CreateProjectInput,
  ProjectUpdateInput,
  ProjectFilter,

  // Return types
  Project,
  ProjectQuota,
  Subscription,

  // Enums
  EntityState,
  SubscriptionStatus,

  // Mutation results
  CreateProjectMutation,
  UpdateProjectMutation,
  DeleteProjectMutation,

  // Query results
  GetProjectQuery,
  QueryProjectsQuery,
} from "graphlit-portal-client";

Related SDKs

The Graphlit Platform has two complementary SDKs:

SDK Purpose Auth Scope
graphlit-portal-client (this SDK) Infrastructure management Organization API key Organization-wide
graphlit-client Data operations & AI Project JWT Single project

Typical Workflow

  1. Use Portal Client to provision infrastructure:

    import { GraphlitPortalClient } from 'graphlit-portal-client';
    
    const portal = new GraphlitPortalClient();
    const project = await portal.createProject({ ... });
  2. Use Data Client for application operations:

    import { Graphlit } from "graphlit-client";
    
    const client = new Graphlit({
      organizationId: process.env.GRAPHLIT_ORGANIZATION_ID,
      environmentId: project.productionEnvId,
      jwtSecret: project.jwtSecret,
    });
    
    // Now ingest content, chat with AI, etc.
    await client.ingestUri({ uri: "https://example.com/doc.pdf" });

Development

Building from Source

# Clone the repository
git clone https://github.com/graphlit/graphlit-portal-client-typescript.git
cd graphlit-portal-client-typescript

# Install dependencies
npm install

# Generate GraphQL types from schema
npm run generate

# Build the SDK
npm run build

# Format code
npm run format

Project Structure

graphlit-portal-client-typescript/
├── src/
│   ├── client.ts                 # Main SDK client
│   ├── documents/                # GraphQL operations
│   │   └── project/
│   │       ├── createProject.graphql
│   │       ├── updateProject.graphql
│   │       └── ...
│   └── generated/                # Auto-generated types
│       ├── graphql-types.ts
│       └── graphql-documents.ts
├── examples/
│   └── basic-usage.ts           # Usage examples
├── dist/                        # Compiled output
├── package.json
├── codegen.yml                  # GraphQL code generation config
└── tsconfig.json

Running Examples

# Set up environment
cp examples/.env.example .env
# Edit .env with your credentials

# Run example
npx ts-node examples/basic-usage.ts

Support

Documentation

Community & Help

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

MIT License - see LICENSE for details


Built with ❤️ by Unstruk Data Inc.

About

TypeScript client for the Graphlit Platform Control Plane

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published