JSPM

  • Created
  • Published
  • Downloads 64
  • Score
    100M100P100Q72001F
  • License ISC

A comprehensive JavaScript SDK for interacting with SuperLeap CRM API with Django-like query builder

Package Exports

  • superleap-sdk
  • superleap-sdk/superleap.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (superleap-sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

SuperLeap SDK

A comprehensive JavaScript SDK for interacting with SuperLeap CRM API with Django-like query builder functionality.

Features

  • 🚀 Django-like Query Builder: Familiar ORM-style querying with method chaining
  • Lazy Execution: Await query builders directly for intuitive querying
  • 📝 Full CRUD Operations: Create, read, update, and delete records
  • 🔍 Advanced Filtering: Support for complex filters with AND/OR conditions
  • 🎯 TypeScript Support: Full TypeScript definitions included
  • 📊 Pagination: Built-in pagination support
  • 🔄 Relationship Support: Handle related objects and foreign keys
  • 🎨 Modern API: Clean, intuitive interface with promises/async-await
  • 📦 Zero Dependencies: Pure JavaScript with no external dependencies

Installation & Usage

For React/Vue/Angular Apps (Module Import)

Installation

# Via npm
npm install superleap-sdk

# Via yarn
yarn add superleap-sdk

Usage in React Component

import { createSuperLeapSDK } from 'superleap-sdk';
// or
import SuperLeapSDK from 'superleap-sdk';

function MyComponent() {
  const [records, setRecords] = useState([]);
  
  useEffect(() => {
    // Initialize SDK
    const sdk = createSuperLeapSDK({
      apiKey: 'your-api-key',
      baseUrl: 'https://app.superleap.dev/api/v1',
      clientId: 'your-client-id',
      clientSecret: 'your-client-secret'
    });
    
    // Use the SDK with lazy execution
    const loadData = async () => {
      const userModel = sdk.getModel('user');
      // Just await the query builder directly
      const users = await userModel.selectAll().limit(10);
      setRecords(users);
    };
    
    loadData();
  }, []);
  
  return (
    <div>
      {records.map(record => (
        <div key={record.id}>{record.get('name')}</div>
      ))}
    </div>
  );
}

TypeScript Usage

import { SuperLeapSDK, createSuperLeapSDK, Model, RecordInstance } from 'superleap-sdk';

const sdk: SuperLeapSDK = createSuperLeapSDK({
  apiKey: 'your-api-key',
  baseUrl: 'https://app.superleap.dev/api/v1',
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret'
});

    // Full type safety
    const userModel: Model = sdk.getModel('user');
    const users: RecordInstance[] = await userModel.selectAll();

For Vanilla JS/HTML (Script Tag)

Installation

<!-- Via CDN -->
<script src="https://cdn.jsdelivr.net/npm/superleap-sdk@latest/superleap.js"></script>

<!-- Or download and include locally -->
<script src="path/to/superleap.js"></script>

Usage in HTML/JavaScript

<!DOCTYPE html>
<html>
<head>
  <title>SuperLeap SDK Example</title>
  <script src="https://cdn.jsdelivr.net/npm/superleap-sdk@latest/superleap.js"></script>
</head>
<body>
  <div id="results"></div>
  
  <script>
    // SDK is automatically available as global
    const sdk = createSuperLeapSDK({
      apiKey: 'your-api-key',
      baseUrl: 'https://app.superleap.dev/api/v1',
      clientId: 'your-client-id',
      clientSecret: 'your-client-secret'
    });
    
    // Alternative: Direct instantiation
    // const sdk = new SuperLeapSDK({...options});
    
    async function loadUsers() {
      try {
        const userModel = sdk.getModel('user');
        // Await the query builder directly
        const users = await userModel.selectAll().limit(10);
        
        const resultsDiv = document.getElementById('results');
        resultsDiv.innerHTML = users.map(user => 
          `<div>${user.get('name')} - ${user.get('email')}</div>`
        ).join('');
        
      } catch (error) {
        console.error('Error:', error);
      }
    }
    
    // Load data when page loads
    loadUsers();
  </script>
</body>
</html>

Global Variables Available

// These are automatically available in vanilla JS:
window.SuperLeapSDK          // Constructor class
window.createSuperLeapSDK    // Factory function
window.DataType              // Data type constants

// Usage examples:
const sdk1 = new SuperLeapSDK({apiKey: 'key'});
const sdk2 = createSuperLeapSDK({apiKey: 'key'});
console.log(DataType.Email); // 11

Quick Start

Initialize the SDK

const sdk = createSuperLeapSDK({
    apiKey: 'your-bearer-token',           // Required
    baseUrl: 'https://app.superleap.dev/api/v1',  // Optional
    clientId: 'your-client-id',            // Required
    clientSecret: 'your-client-secret'     // Required
});

Basic CRUD Operations

// Initialize the SDK
const sdk = createSuperLeapSDK({
    apiKey: 'your-api-key',
    baseUrl: 'https://app.superleap.dev/api/v1',
    clientId: 'your-client-id',
    clientSecret: 'your-client-secret'
});

// Get a model
const userModel = sdk.getModel('user');

// Create a new record
const newUser = await userModel.create({
    name: 'John Doe',
    email: 'john@example.com',
    status: 'active'
});

// Query records - await the query builder directly
const activeUsers = await userModel.selectAll()
    .filter('status', 'eq', 'active')
    .orderBy('-created_at')
    .limit(10);

// Update a record
const updatedUser = await newUser.update({
    name: 'John Smith'
});

// Delete a record
await newUser.delete();

Documentation

Initialization

const sdk = createSuperLeapSDK({
    apiKey: 'your-bearer-token',           // Required
    baseUrl: 'https://app.superleap.dev/api/v1',  // Optional
    clientId: 'your-client-id',            // Required
    clientSecret: 'your-client-secret'     // Required
});

Models

Get a model instance for any SuperLeap object:

const model = sdk.getModel('objectSlug');
// or
const model = sdk.model('objectSlug');

Query Builder

The query builder provides a Django-like interface with lazy execution - you can await query builders directly:

Basic Queries

// Get all records
const records = await model.selectAll();

// Get first 10 records
const records = await model.selectAll().limit(10);

// Get first record
const record = await model.selectAll().first();

// Count records
const count = await model.selectAll().count();

// Check if records exist
const exists = await model.selectAll().exists();

Field Selection

// Select specific fields
const records = await model.select('name', 'email', 'created_at');

// Select all fields
const records = await model.selectAll();

// Select related fields (dot notation)
const records = await model.select('user.name', 'user.email');

Filtering

// Simple where conditions
const records = await model.selectAll()
    .where({ status: 'active', type: 'premium' });

// Field-specific filters
const records = await model.selectAll()
    .exact('status', 'active')
    .contains('name', 'John')
    .gt('age', 18)
    .in('department', ['sales', 'marketing']);

Available Filter Methods

Method Description Example
exact(field, value) Exact match .exact('status', 'active')
contains(field, value) Contains text .contains('name', 'John')
icontains(field, value) Case-insensitive contains .icontains('name', 'john')
startswith(field, value) Starts with .startswith('name', 'John')
endswith(field, value) Ends with .endswith('email', '@gmail.com')
gt(field, value) Greater than .gt('age', 18)
gte(field, value) Greater than or equal .gte('score', 80)
lt(field, value) Less than .lt('price', 100)
lte(field, value) Less than or equal .lte('quantity', 50)
in(field, values) In array .in('status', ['active', 'pending'])
notin(field, values) Not in array .notin('status', ['inactive'])
between(field, [min, max]) Between values .between('age', [18, 65])
isempty(field) Field is empty .isempty('description')
isnotempty(field) Field is not empty .isnotempty('email')

Complex Filtering

// AND conditions
const records = await model.selectAll()
    .whereAnd(q => {
        q.gte('age', 18);
        q.contains('name', 'John');
        q.exact('status', 'active');
    });

// OR conditions
const records = await model.selectAll()
    .whereOr(q => {
        q.contains('name', 'John');
        q.contains('name', 'Jane');
    });

// Combined AND/OR
const records = await model.selectAll()
    .whereAnd(q => {
        q.exact('status', 'active');
        q.gte('age', 18);
    })
    .whereOr(q => {
        q.contains('department', 'sales');
        q.contains('department', 'marketing');
    });

Sorting

// Single field ascending
const records = await model.selectAll()
    .orderBy('name');

// Single field descending
const records = await model.selectAll()
    .orderBy('-created_at');

// Multiple fields
const records = await model.selectAll()
    .orderBy('department', '-created_at', 'name');

Pagination

// Limit results
const records = await model.selectAll()
    .limit(10);

// Page-based pagination
const records = await model.selectAll()
    .page(2)
    .limit(10);

// Offset-based pagination
const records = await model.selectAll()
    .offset(20)
    .limit(10);

CRUD Operations

Create

// Create a single record
const record = await model.create({
    name: 'John Doe',
    email: 'john@example.com',
    status: 'active'
});

// Bulk create
const records = await model.bulkCreate([
    { name: 'John', email: 'john@example.com' },
    { name: 'Jane', email: 'jane@example.com' }
]);

// Bulk update (records must have IDs)
const updatedRecords = await model.bulkUpdate([
    { id: 'record-id-1', name: 'Updated John' },
    { id: 'record-id-2', email: 'updated@example.com' }
]);

// Bulk operations with ignoreDuplicates parameter
// For bulk create: ignoreDuplicates = true (default) - ignores duplicates
const createdRecords = await model.bulkCreate([
    { name: 'John', email: 'john@example.com' },
    { name: 'Jane', email: 'jane@example.com' }
], true); // ignoreDuplicates = true

// For bulk update: ignoreDuplicates = false (default) - updates existing records
const updatedRecords = await model.bulkUpdate([
    { id: 'record-id-1', name: 'Updated John' },
    { id: 'record-id-2', email: 'updated@example.com' }
], false); // ignoreDuplicates = false

Read

// Get by ID
const record = await model.get('record-id');

// Get or create
const result = await model.getOrCreate(
    { email: 'john@example.com' },
    { name: 'John Doe', status: 'active' }
);
console.log(result.record, result.created);

Update

// Update by ID
const updated = await model.update('record-id', {
    name: 'Updated Name'
});

// Update or create
const result = await model.updateOrCreate(
    { email: 'john@example.com' },
    { name: 'John Doe', status: 'active' }
);

Delete

// Delete by ID
const deleted = await model.delete('record-id');

// Delete multiple records
const deleted = await model.deleteMany(['id1', 'id2', 'id3']);

Working with Records

// Get field values
const name = record.get('name');
const email = record.get('email');

// Set field values
record.set('name', 'New Name');
record.set('status', 'inactive');

// Update record
const updated = await record.update({
    name: 'Updated Name',
    status: 'active'
});

// Delete record
const deleted = await record.delete();

// Refresh from server
const refreshed = await record.refresh();

// Convert to plain object
const data = record.toJSON();

Schema and Field Information

// Get object schema
const schema = await model.getSchema();

// Get all fields
const fields = await model.getFields();

// Get specific field info
const field = await model.getField('fieldSlug');
console.log(field.displayName, field.dataType, field.isRequired);

Error Handling

try {
    // Query with error handling
    const records = await model.selectAll()
        .filter('email', 'contains', 'invalid');
} catch (error) {
    console.error('Query failed:', error.message);
}

try {
    const record = await model.create({
        name: 'Test User',
        email: 'invalid-email'
    });
} catch (error) {
    console.error('Failed to create record:', error.message);
}

TypeScript Support

The SDK includes full TypeScript definitions:

import { SuperLeapSDK, createSuperLeapSDK } from 'superleap-sdk';

const sdk: SuperLeapSDK = createSuperLeapSDK({
    apiKey: 'your-api-key',
    baseUrl: 'https://app.superleap.dev/api/v1'
});

// TypeScript will provide full autocomplete and type checking
const model = sdk.getModel('user');
const records = await model.selectAll();

Browser Support

The SDK works in all modern browsers and supports:

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+

Development

Setup for Local Development

  1. Clone the repository

  2. Install dependencies:

    yarn install
  3. Link the package for local development:

    yarn link
  4. In your consuming project:

    yarn link superleap-sdk
  5. Start the demo server:

    yarn demo

Publishing

# Build and publish to npm
yarn publish

Examples

Check out the included index.html file for a complete interactive example with Monaco Editor integration.

API Reference

SuperLeapSDK Class

Method Description
getModel(slug) Get model instance
setApiKey(key) Set API key
setClientCredentials(id, secret) Set client credentials
request(endpoint, options) Make raw API request

Model Class

Method Description
select(...fields) Get query builder with selected fields
selectAll() Get query builder with all fields
create(data) Create record
get(id) Get record by ID
update(id, data) Update record
delete(id) Delete record
getSchema() Get object schema
getFields() Get all fields

QueryBuilder Class

Method Description
await queryBuilder Execute query and return results
select(...fields) Select fields
where(conditions) Add WHERE conditions
filter(field, operator, value) Add filter
orderBy(...fields) Add sorting
limit(n) Limit results
first() Get first result
count() Get count

Contributing

  1. Fork the repository
  2. Install dependencies: yarn install
  3. Create your feature branch (git checkout -b feature/amazing-feature)
  4. Commit your changes (git commit -m 'Add some amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

License

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

Support

For questions and support, please open an issue on GitHub or contact the SuperLeap team.