Skip to content

apito-io/js-internal-sdk

Repository files navigation

Apito JavaScript SDK

npm version License: MIT

A comprehensive JavaScript SDK for communicating with Apito GraphQL API endpoints. This SDK provides both type-safe and flexible interfaces for interacting with Apito's backend services.

πŸš€ Features

  • βœ… Complete SDK Implementation: Full implementation matching the Go SDK
  • βœ… Type-Safe Operations: Generic typed methods for better development experience
  • βœ… GraphQL-Based: Native GraphQL communication with Apito backend
  • βœ… Authentication Ready: API key and tenant-based authentication
  • βœ… Promise-Based: Modern async/await support
  • βœ… Comprehensive Error Handling: Detailed error responses and GraphQL error support
  • βœ… Plugin-Ready: Perfect for Node.js applications and microservices
  • βœ… Production Ready: Battle-tested patterns and error handling

πŸ“¦ Installation

npm install @apito/apito-sdk

or

yarn add @apito/apito-sdk

🎯 Quick Start

import { ApitoClient } from '@apito/apito-sdk';

// Create a new client
const client = new ApitoClient({
  baseURL: 'https://api.apito.io/graphql',
  apiKey: 'your-api-key-here',
  timeout: 30000,
});

// Create a new todo
async function createTodo() {
  const todoData = {
    title: 'Learn Apito SDK',
    description: 'Complete the SDK tutorial',
    status: 'todo',
    priority: 'high',
  };

  const request = {
    model: 'todos',
    payload: todoData,
  };

  const todo = await client.createNewResource(request);
  console.log('Created todo:', todo.id);
}

πŸ“š API Reference

Client Configuration

const client = new ApitoClient({
  baseURL: 'https://api.apito.io/graphql',  // Your Apito GraphQL endpoint
  apiKey: 'your-api-key-here',             // X-APITO-KEY header value
  timeout: 30000,                          // Request timeout in milliseconds
  tenantId: 'your-tenant-id',              // Optional tenant ID
  httpClient: {                            // Optional axios configuration
    maxRedirects: 5,
    // ... other axios config
  },
});

Core Methods

getSingleResource(model, id, singlePageData?)

Get a single resource by model and ID.

const todo = await client.getSingleResource('todos', '123');
console.log(todo.data.title);

searchResources(model, filter?, aggregate?)

Search resources in a model with filtering.

const results = await client.searchResources('todos', {
  where: { status: 'todo' },
  limit: 10,
  page: 1,
});
console.log(`Found ${results.count} todos`);

createNewResource(request)

Create a new resource.

const newTodo = await client.createNewResource({
  model: 'todos',
  payload: {
    title: 'New Task',
    status: 'todo',
  },
  connect: { user: 'user-123' }, // Optional relations
});

updateResource(request)

Update an existing resource.

const updatedTodo = await client.updateResource({
  model: 'todos',
  id: '123',
  payload: {
    status: 'completed',
    completed_at: new Date().toISOString(),
  },
  connect: { tags: ['urgent'] }, // Add relations
  disconnect: { tags: ['low-priority'] }, // Remove relations
});

deleteResource(model, id)

Delete a resource.

await client.deleteResource('todos', '123');

getRelationDocuments(id, connection)

Get related documents.

const relatedUsers = await client.getRelationDocuments('todo-123', {
  model: 'users',
  field: 'assigned_to',
});

Typed Operations

For type-safe operations, use the TypedOperations class:

import { TypedOperations } from '@apito/apito-sdk';

const typed = new TypedOperations(client);

// Define your types
interface Todo {
  id: string;
  title: string;
  description: string;
  status: 'todo' | 'in_progress' | 'completed';
  priority: 'low' | 'medium' | 'high';
}

// Type-safe operations
const typedTodo = await typed.createNewResourceTyped<Todo>({
  model: 'todos',
  payload: {
    title: 'Type-safe todo',
    status: 'todo',
    priority: 'high',
  },
});

// TypeScript will infer the correct type
console.log(typedTodo.data.title); // string
console.log(typedTodo.data.status); // 'todo' | 'in_progress' | 'completed'

Error Handling

The SDK provides comprehensive error handling:

import { ApitoError, ValidationError, GraphQLError } from '@apito/apito-sdk';

try {
  const result = await client.getSingleResource('todos', 'invalid-id');
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation error:', error.message);
  } else if (error instanceof GraphQLError) {
    console.error('GraphQL error:', error.graphQLErrors);
  } else if (error instanceof ApitoError) {
    console.error('API error:', error.statusCode, error.message);
  } else {
    console.error('Unknown error:', error);
  }
}

Environment Variables

You can configure the client using environment variables:

# Required
APITO_BASE_URL=https://api.apito.io/graphql
APITO_API_KEY=your-production-api-key

# Optional
APITO_TENANT_ID=your-tenant-id
APITO_TIMEOUT=30000
import { ApitoClient } from '@apito/apito-sdk';

const client = new ApitoClient({
  baseURL: process.env.APITO_BASE_URL,
  apiKey: process.env.APITO_API_KEY,
  tenantId: process.env.APITO_TENANT_ID,
  timeout: parseInt(process.env.APITO_TIMEOUT || '30000'),
});

πŸ§ͺ Examples

Basic CRUD Operations

import { ApitoClient } from '@apito/apito-sdk';

const client = new ApitoClient({
  baseURL: 'https://api.apito.io/graphql',
  apiKey: 'your-api-key',
});

// Create
const user = await client.createNewResource({
  model: 'users',
  payload: {
    name: 'John Doe',
    email: 'john@example.com',
  },
});

// Read
const fetchedUser = await client.getSingleResource('users', user.id);

// Update
const updatedUser = await client.updateResource({
  model: 'users',
  id: user.id,
  payload: {
    name: 'John Updated',
  },
});

// Delete
await client.deleteResource('users', user.id);

Advanced Filtering

// Complex search with multiple filters
const results = await client.searchResources('products', {
  where: {
    AND: [
      { price: { gte: 100 } },
      { category: { in: ['electronics', 'books'] } },
      { status: 'active' },
    ],
  },
  search: 'laptop',
  limit: 20,
  page: 1,
});

Batch Operations

// Create multiple records
const todos = [
  { title: 'Task 1', status: 'todo' },
  { title: 'Task 2', status: 'todo' },
  { title: 'Task 3', status: 'todo' },
];

const createdTodos = await Promise.all(
  todos.map(todo => client.createNewResource({
    model: 'todos',
    payload: todo,
  }))
);

πŸ—οΈ Development

Building from Source

git clone https://github.com/apito-io/js-apito-sdk.git
cd js-apito-sdk
npm install
npm run build

Running Tests

npm test

Running Examples

cd examples/basic
npm install
npm start

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ”— Links

πŸ†˜ Support

About

JS SDK to connect apito any JS project or used under Apito JS Plugin

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published