Class: SheetAPI

SheetAPI()

Comprehensive Google Sheets API wrapper providing full CRUD operations, advanced querying, caching, and type-safe data management. ## Core Features ### Data Operations - **Full CRUD Support**: Create, read, update, delete operations with automatic ID generation - **Advanced Querying**: Filter, sort, paginate, and search across sheet data - **Type Safety**: Automatic type casting and validation based on schema definitions - **Batch Operations**: Efficient bulk operations for multiple records ### Caching System - **Multi-Level Caching**: Data cache, record cache, and query result cache - **TTL Management**: Time-based expiration with automatic cleanup - **Performance Tracking**: Cache hit/miss statistics and optimization metrics - **Auto-Optimization**: Dynamic cache duration adjustment based on usage patterns ### Authentication & Security - **OAuth2 Integration**: Automatic token refresh and management - **Secure Token Handling**: Encrypted storage and secure transmission - **Rate Limiting**: Built-in request throttling and retry logic - **Error Recovery**: Comprehensive error handling with detailed diagnostics ### Data Management - **Schema Definition**: Flexible column definitions with type specifications - **Data Validation**: Input validation and type coercion - **ID Generation**: Automatic unique identifier creation - **Data Transformation**: Custom field mapping and processing ## Architecture Overview The SheetAPI class implements a layered architecture: ``` ┌─────────────────┐ │ SheetAPI │ ← Public API layer │ (Main Class) │ └─────────────────┘ │ ▼ ┌─────────────────┐ │ SheetAPIToken- │ ← Authentication layer │ Manager │ └─────────────────┘ │ ▼ ┌─────────────────┐ │ Google Sheets │ ← External API layer │ API v4 │ └─────────────────┘ ``` ### Layer Responsibilities **Public API Layer (SheetAPI)**: - High-level CRUD operations - Query processing and optimization - Cache management and invalidation - Data transformation and validation - Error handling and user feedback **Authentication Layer (SheetAPITokenManager)**: - OAuth2 token lifecycle management - Automatic token refresh - Secure HTTP request authentication - Rate limiting and retry logic **External API Layer (Google Sheets API v4)**: - Raw HTTP communication - API-specific request formatting - Response parsing and normalization ## Performance Characteristics ### Caching Strategy - **Data Cache**: Full sheet data cached for 15-60 minutes (user-dependent) - **Record Cache**: Individual records cached for 30-120 minutes - **Query Cache**: Query results cached for 10-40 minutes - **Auto-optimization**: Cache durations adjust based on user count and access patterns ### Optimization Features - **Lazy Loading**: Data loaded only when needed - **Incremental Updates**: Only changed data transmitted - **Batch Processing**: Multiple operations combined for efficiency - **Connection Pooling**: Reused HTTP connections for reduced latency ## Usage Patterns ### Basic CRUD Operations ```javascript const api = new SheetAPI({ spreadsheetId: "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms", accessToken: "ya29...", sheetName: "Users", headers: ["id", "name", "email", "age"] }); await api.init(); // Create const user = await api.create({ name: "John Doe", email: "john@example.com", age: 30 }); console.log(user.id); // Auto-generated ID // Read const allUsers = await api.getAll(); const specificUser = await api.getById(user.id); // Update await api.update(user.id, { age: 31 }); // Delete await api.delete(user.id); ``` ### Advanced Querying ```javascript // Filter and sort const activeUsers = await api.getAll({ filter: { status: "active" }, sort: { name: "asc" }, limit: 10 }); // Search across multiple fields const searchResults = await api.search("john", ["name", "email"]); // Paginated results const page1 = await api.getAll({ page: 1, limit: 50 }); const page2 = await api.getAll({ page: 2, limit: 50 }); ``` ### Schema Definition ```javascript const api = new SheetAPI({ spreadsheetId: "your-id", accessToken: "your-token", sheetName: "Products", headers: [ "id", { name: "name", type: "string" }, { name: "price", type: "number" }, { name: "inStock", type: "boolean" }, { name: "createdAt", type: "date" } ] }); ``` ### Cache Configuration ```javascript const api = new SheetAPI({ // ... other config cache: { userCount: 100, // Optimize for 100 concurrent users durationUnit: 'hours', // Use hours instead of minutes maxRecordCacheSize: 200 // Cache up to 200 records } }); ``` ## Error Handling The SheetAPI provides comprehensive error handling with detailed error messages: ```javascript try { await api.create({ name: "John" }); } catch (error) { if (error.code === 'VALIDATION_ERROR') { console.log('Validation failed:', error.details); } else if (error.code === 'AUTH_ERROR') { console.log('Authentication failed, token may be expired'); } else if (error.code === 'NETWORK_ERROR') { console.log('Network issue, will retry automatically'); } } ``` ## Security Considerations ### Token Security - Access tokens are never stored in plain text - Refresh tokens are encrypted using client credentials - Automatic token rotation prevents token exhaustion - Secure HTTPS-only communication with Google APIs ### Data Protection - Input validation prevents injection attacks - Type coercion ensures data integrity - Rate limiting prevents abuse - Audit logging for sensitive operations ### Access Control - OAuth2 scopes limit API permissions - Sheet-level access control through Google Sheets permissions - Row-level security through application logic ## Performance Optimization ### Caching Best Practices - Cache durations auto-adjust based on data volatility - Cache invalidation on data modifications - Memory-efficient cache storage with size limits - Cache statistics for monitoring and tuning ### Query Optimization - Client-side filtering reduces API calls - Pagination prevents large data transfers - Batch operations combine multiple requests - Connection reuse minimizes latency ## Extensibility The SheetAPI is designed for extension through: - Custom data transformers - Plugin architecture for additional features - Event hooks for operation monitoring - Custom validation rules - Integration with other data sources ## Dependencies - **SheetAPITokenManager**: Handles OAuth2 authentication - **Google Sheets API v4**: External REST API for sheet operations - **Fetch API**: Modern HTTP client for API communication - **ES6+ Features**: Promises, async/await, Map, Set ## Browser Compatibility - Modern browsers with ES6+ support - Node.js 14+ with fetch polyfill - HTTPS required for OAuth2 security - CORS-enabled environments for web applications

Constructor

new SheetAPI()

Version:
  • 2.0.0
Since:
  • 1.0.0
Author:
  • SheetAPI Development Team
License:
  • MIT
Source:
Examples
// Complete setup and usage example
const api = new SheetAPI({
  spreadsheetId: "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
  accessToken: "ya29.a0AfH6SMC...",
  sheetName: "Users",
  headers: [
    "id",
    { name: "name", type: "string" },
    { name: "email", type: "string" },
    { name: "age", type: "number" },
    { name: "active", type: "boolean" }
  ],
  debug: true
});

// Initialize the API
await api.init();

// Perform operations
const user = await api.create({
  name: "Jane Smith",
  email: "jane@example.com",
  age: 28,
  active: true
});

console.log(`Created user with ID: ${user.id}`);
// Advanced configuration with caching
const api = new SheetAPI({
  spreadsheetId: "your-spreadsheet-id",
  refreshToken: "1//refresh-token",
  clientId: "your-client-id",
  clientSecret: "your-client-secret",
  sheetName: "Products",
  headers: ["id", "name", "price", "category"],
  cache: {
    userCount: 50,
    durationUnit: 'minutes',
    maxRecordCacheSize: 150
  },
  createIfMissing: true
});
// Error handling patterns
try {
  const users = await api.getAll();
  console.log(`Found ${users.length} users`);
} catch (error) {
  switch (error.code) {
    case 'AUTH_ERROR':
      console.error('Authentication failed:', error.message);
      break;
    case 'NETWORK_ERROR':
      console.error('Network issue:', error.message);
      break;
    case 'VALIDATION_ERROR':
      console.error('Data validation failed:', error.details);
      break;
    default:
      console.error('Unknown error:', error);
  }
}

Methods

(async) batchDelete(ids) → {Promise.<Object>}

Batch delete multiple records by ID
Parameters:
Name Type Description
ids Array.<string> Array of record IDs to delete
Source:
Returns:
Standard {status, data: Array, error} response
Type
Promise.<Object>
Example
const result = await api.batchDelete(["user-1", "user-2", "user-3"]);

(async) batchInsert(records) → {Promise.<Object>}

Batch insert multiple records
Parameters:
Name Type Description
records Array.<Object> Array of record objects to insert
Source:
Returns:
Standard {status, data: Array, error} response
Type
Promise.<Object>
Example
const users = [
  { name: "John", email: "john@example.com" },
  { name: "Jane", email: "jane@example.com" }
];
const result = await api.batchInsert(users);
// IDs are auto-generated if not provided

(async) batchUpdate(updates) → {Promise.<Object>}

Batch update multiple records by ID
Parameters:
Name Type Description
updates Array.<Object> Array of update objects, each must have an 'id' property
Source:
Returns:
Standard {status, data: Array, error} response
Type
Promise.<Object>
Example
const updates = [
  { id: "user-1", status: "active" },
  { id: "user-2", status: "inactive" }
];
const result = await api.batchUpdate(updates);

clearCaches()

Clear all caches manually
Source:

(async) deleteAll() → {Promise.<Object>}

Delete all records (keeps headers)
Source:
Returns:
Returns success message or error
Type
Promise.<Object>
Example
const result = await api.deleteAll();

(async) deleteBy(fieldName, value) → {Promise.<Object>}

Delete records by field value
Parameters:
Name Type Description
fieldName string Name of the field to search
value string | number | boolean Value to match for deletion
Source:
Returns:
Returns success message or error
Type
Promise.<Object>
Example
const result = await api.deleteBy("email", "john@example.com");

(async) deleteById(idValue) → {Promise.<Object>}

Delete a record by its ID
Parameters:
Name Type Description
idValue string The record ID to delete
Source:
Returns:
Returns success with deleted record or error message
Type
Promise.<Object>
Example
const result = await api.deleteById("user-123");

(async) findRowById(idValue) → {Promise.<Object>}

Internal helper: find a row by ID
Parameters:
Name Type Description
idValue string Record ID
Source:
Returns:
{status, data: {rowData, rowIndex, sheetId}, error}
Type
Promise.<Object>

generateUniqueId(lenopt) → {string}

Generate a unique ID for records
Parameters:
Name Type Attributes Default Description
len number <optional>
15 Length of the ID to generate
Source:
Returns:
A unique alphanumeric ID
Type
string
Example
const id = api.generateUniqueId();
// result: "a1b2c3d4e5f6g7h"

(async) getByField(fieldName, value) → {Promise.<Object>}

Get a record by any field value
Parameters:
Name Type Description
fieldName string Name of the field to search
value string | number | boolean Value to match
Source:
Returns:
Returns success with the record or error message
Type
Promise.<Object>
Example
const user = await api.getByField("email", "john@example.com");

getCacheStats() → {Object}

Get cache statistics for debugging
Source:
Returns:
Cache stats
Type
Object

(async) getIdByField(fieldName, value) → {Promise.<Object>}

Get record ID by field value
Parameters:
Name Type Description
fieldName string Name of the field to search
value string | number | boolean Value to match
Source:
Returns:
Returns success with the ID or error message
Type
Promise.<Object>
Example
const userId = await api.getIdByField("email", "john@example.com");

getSchema() → {Object}

Get the current schema (field types)
Source:
Returns:
Schema object with field names as keys and types as values
Type
Object

(async) recordExists(idValue) → {Promise.<Object>}

CHECK if a record exists by ID
Parameters:
Name Type Description
idValue string The record ID to check
Source:
Returns:
Standard {status, data: boolean, error} response
Type
Promise.<Object>
Example
const exists = await api.recordExists("user-123");
// result: { status: "success", data: true } or { status: "error", data: false }

(async) rowCount() → {Promise.<Object>}

Get the number of data rows in the sheet
Source:
Returns:
Returns success with the count or error message
Type
Promise.<Object>
Example
const count = await api.rowCount();

(async) sheetExists(sheetNameopt) → {Promise.<Object>}

CHECK if a sheet exists
Parameters:
Name Type Attributes Description
sheetName string <optional>
Name of sheet to check (defaults to configured sheetName)
Source:
Returns:
Standard {status, data: boolean, error} response
Type
Promise.<Object>
Example
const exists = await api.sheetExists("Users");
// result: { status: "success", data: true }

(async) update(record) → {Promise.<Object>}

Update a record using an object that includes the ID
Parameters:
Name Type Description
record Object The record data including ID
Source:
Returns:
Returns success with updated record or error message
Type
Promise.<Object>
Example
const result = await api.update({ id: "user-123", age: 25 });

(async) updateById(idValue, updatedData) → {Promise.<Object>}

Update a record by its ID
Parameters:
Name Type Description
idValue string The record ID to update
updatedData Object The fields to update
Source:
Returns:
Returns success with updated record or error message
Type
Promise.<Object>
Example
const result = await api.updateById("user-123", { status: "inactive" });

SheetAPI(config)

new SheetAPI(config)

Initializes a new SheetAPI instance with comprehensive configuration for Google Sheets operations. This constructor performs extensive validation, schema processing, authentication setup, and cache configuration to create a fully functional Google Sheets API wrapper. It implements intelligent defaults and auto-optimization based on the provided configuration parameters. ## Initialization Process 1. **Parameter Validation**: Validates all required and optional parameters 2. **Schema Processing**: Processes header definitions and creates type schema 3. **Authentication Setup**: Configures OAuth2 token management if needed 4. **Cache Configuration**: Auto-calculates optimal cache settings based on user count 5. **Instance Setup**: Initializes all internal state and data structures ## Parameter Requirements ### Required Parameters - `spreadsheetId`: The unique identifier of your Google Spreadsheet - `sheetName`: The name of the worksheet tab within the spreadsheet - **Authentication**: Either `accessToken` OR all of `refreshToken`, `clientId`, `clientSecret` ### Authentication Options **Option 1: Direct Access Token** ```javascript const api = new SheetAPI({ spreadsheetId: "1abc...", accessToken: "ya29.abc...", sheetName: "Data" }); ``` **Option 2: Refresh Token (Recommended)** ```javascript const api = new SheetAPI({ spreadsheetId: "1abc...", refreshToken: "1//refresh-token", clientId: "your-client-id", clientSecret: "your-client-secret", sheetName: "Data" }); ``` ## Schema Definition The `headers` parameter supports two formats for flexible schema definition: ### Simple String Format ```javascript headers: ["id", "name", "email", "age"] // All columns default to 'string' type ``` ### Advanced Object Format ```javascript headers: [ "id", // Simple string, defaults to 'string' type { name: "name", type: "string" }, { name: "age", type: "number" }, { name: "active", type: "boolean" }, { name: "createdAt", type: "date" } ] ``` ### Supported Data Types - `"string"`: Text data (default) - `"number"`: Numeric data with automatic parsing - `"boolean"`: True/false values - `"date"`: Date/time values with ISO parsing ## Cache Configuration The caching system auto-optimizes based on the `userCount` parameter: ### Auto-Optimization Logic - **userCount = 0**: Disables all caching for real-time experience - **userCount = 1**: Optimized for single-user applications (default) - **userCount > 1**: Scales cache durations based on concurrent users ### Cache Types - **Data Cache**: Full sheet data caching - **Record Cache**: Individual record caching with LRU eviction - **Query Cache**: Query result caching for performance ### Duration Calculation ```javascript // Base durations (single user, minutes) const baseDurations = { data: 15, // 15 minutes record: 30, // 30 minutes query: 10 // 10 minutes }; // Multiplier based on user count const userMultiplier = Math.max(0.1, 1 / Math.log10(userCount + 1)); // Final duration in milliseconds duration = baseDuration * userMultiplier * 60000; ``` ## Error Conditions The constructor throws detailed errors for invalid configurations: ```javascript // Missing spreadsheetId throw new Error("spreadsheetId is required"); // Missing sheetName throw new Error("sheetName is required"); // Invalid authentication throw new Error("Either accessToken or all of refreshToken, clientId, and clientSecret are required"); ``` ## Performance Considerations ### Memory Usage - Cache sizes scale with user count - Record cache limited to prevent memory exhaustion - Automatic cleanup of expired cache entries ### Initialization Time - Schema processing: O(n) where n = number of headers - Cache configuration: O(1) with mathematical calculations - Token manager setup: O(1) for refresh token validation ## Security Features - **Token Validation**: Ensures authentication parameters are complete - **Input Sanitization**: Validates spreadsheet ID and sheet name formats - **Secure Defaults**: Conservative cache settings for data protection - **Audit Logging**: Debug mode provides detailed initialization logs ## Debug Information When `debug: true`, the constructor provides detailed logging: ``` Cache auto-optimized for 1 users: { dataCache: 15, recordCache: 30, queryCache: 10, unit: 'minutes' } ```
Parameters:
Name Type Description
config Object Comprehensive configuration object for SheetAPI initialization
Properties
Name Type Attributes Default Description
spreadsheetId string The unique Google Spreadsheet identifier (required) - Format: Typically 44 characters with dashes (e.g., "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms") - Must be accessible with the provided authentication credentials - Can be found in the Google Sheets URL: https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/edit
accessToken string <optional>
OAuth2 access token for immediate API access - Short-lived token (typically 1 hour) - Must have appropriate Google Sheets API scopes - Required if not using refresh token authentication - Example: "ya29.a0AfH6SMCaR9..."
refreshToken string <optional>
OAuth2 refresh token for long-term access - Long-lived token for automatic access token renewal - Obtained during initial OAuth2 authorization flow - Required with clientId and clientSecret for automatic token management - Example: "1//04R9..."
clientId string <optional>
OAuth2 client identifier from Google Cloud Console - Public identifier for your OAuth2 application - Required when using refresh token authentication - Format: "{random-string}.apps.googleusercontent.com"
clientSecret string <optional>
OAuth2 client secret from Google Cloud Console - Private secret for your OAuth2 application - Required when using refresh token authentication - Must be kept secure and never exposed in client-side code
sheetName string Name of the worksheet tab within the spreadsheet (required) - Case-sensitive sheet name as displayed in Google Sheets - Must exist in the spreadsheet or createIfMissing must be true - Example: "Sheet1", "Users", "Products"
headers Array.<(string|Object)> <optional>
[] Column definitions for data schema - Array of column names or column definition objects - Determines data structure and type validation - Used for automatic type casting and validation - Simple format: ["id", "name", "email"] - Advanced format: [{name: "id", type: "string"}, {name: "age", type: "number"}]
createIfMissing boolean <optional>
true Auto-create sheet if it doesn't exist - When true: Creates the sheet tab if not found - When false: Throws error if sheet doesn't exist - Useful for preventing accidental sheet creation - Default: true for development convenience
debug boolean <optional>
false Enable detailed logging and debug information - When true: Logs initialization details, cache operations, API calls - When false: Minimal logging for production use - Useful for troubleshooting and development - Performance impact: Minimal (console.log calls)
cache Object <optional>
{} Advanced cache configuration for performance optimization
Properties
Name Type Attributes Default Description
userCount number <optional>
1 Expected number of concurrent users - Used for auto-optimization of cache durations - 0 = disable all caching, 1 = single user, >1 = multi-user scaling - Affects cache duration calculations
durationUnit string <optional>
'minutes' Unit for cache duration calculations - Supported: 'milliseconds', 'seconds', 'minutes', 'hours' - Affects how duration multipliers are applied - Default 'minutes' for user-friendly configuration
maxRecordCacheSize number <optional>
100 Maximum cached records - Limits memory usage for record cache - LRU eviction when limit exceeded - Balance between memory usage and performance
enableQueryCaching boolean <optional>
true Enable query result caching - Caches filtered, sorted, and paginated results - Improves performance for repeated queries - Can be disabled for highly dynamic data
name string <optional>
null Optional instance name for debugging - Used in debug logs to identify multiple instances - Helpful when using multiple SheetAPI instances - Example: "UserAPI", "ProductAPI"
Version:
  • 2.0.0
Since:
  • 1.0.0
Source:
Throws:
  • When spreadsheetId is missing or invalid
    Type
    Error
  • When sheetName is missing or invalid
    Type
    Error
  • When authentication parameters are incomplete
    Type
    Error
  • When headers array contains invalid definitions
    Type
    Error
Examples
// Basic setup with access token
const api = new SheetAPI({
  spreadsheetId: "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
  accessToken: "ya29.a0AfH6SMCaR9dX8...",
  sheetName: "Users",
  headers: ["id", "name", "email", "department"]
});
// Advanced setup with refresh token and schema
const api = new SheetAPI({
  spreadsheetId: "1abc123def456",
  refreshToken: "1//04R9X8...",
  clientId: "123456789-abc.apps.googleusercontent.com",
  clientSecret: "GOCSPX-xyz123",
  sheetName: "Products",
  headers: [
    { name: "id", type: "string" },
    { name: "name", type: "string" },
    { name: "price", type: "number" },
    { name: "inStock", type: "boolean" },
    { name: "createdAt", type: "date" }
  ],
  createIfMissing: false,
  debug: true,
  cache: {
    userCount: 50,
    durationUnit: 'hours',
    maxRecordCacheSize: 200
  },
  name: "ProductInventory"
});
// Real-time setup (no caching)
const api = new SheetAPI({
  spreadsheetId: "1xyz789",
  accessToken: "ya29.token...",
  sheetName: "LiveData",
  headers: ["timestamp", "value"],
  cache: { userCount: 0 } // Disable all caching
});
// Error handling for invalid configuration
try {
  const api = new SheetAPI({
    // Missing required parameters
    sheetName: "Data"
  });
} catch (error) {
  console.error("Configuration error:", error.message);
  // Output: "spreadsheetId is required"
}

Methods

(async) batchDelete(ids) → {Promise.<Object>}

Batch delete multiple records by ID
Parameters:
Name Type Description
ids Array.<string> Array of record IDs to delete
Source:
Returns:
Standard {status, data: Array, error} response
Type
Promise.<Object>
Example
const result = await api.batchDelete(["user-1", "user-2", "user-3"]);

(async) batchInsert(records) → {Promise.<Object>}

Batch insert multiple records
Parameters:
Name Type Description
records Array.<Object> Array of record objects to insert
Source:
Returns:
Standard {status, data: Array, error} response
Type
Promise.<Object>
Example
const users = [
  { name: "John", email: "john@example.com" },
  { name: "Jane", email: "jane@example.com" }
];
const result = await api.batchInsert(users);
// IDs are auto-generated if not provided

(async) batchUpdate(updates) → {Promise.<Object>}

Batch update multiple records by ID
Parameters:
Name Type Description
updates Array.<Object> Array of update objects, each must have an 'id' property
Source:
Returns:
Standard {status, data: Array, error} response
Type
Promise.<Object>
Example
const updates = [
  { id: "user-1", status: "active" },
  { id: "user-2", status: "inactive" }
];
const result = await api.batchUpdate(updates);

clearCaches()

Clear all caches manually
Source:

(async) deleteAll() → {Promise.<Object>}

Delete all records (keeps headers)
Source:
Returns:
Returns success message or error
Type
Promise.<Object>
Example
const result = await api.deleteAll();

(async) deleteBy(fieldName, value) → {Promise.<Object>}

Delete records by field value
Parameters:
Name Type Description
fieldName string Name of the field to search
value string | number | boolean Value to match for deletion
Source:
Returns:
Returns success message or error
Type
Promise.<Object>
Example
const result = await api.deleteBy("email", "john@example.com");

(async) deleteById(idValue) → {Promise.<Object>}

Delete a record by its ID
Parameters:
Name Type Description
idValue string The record ID to delete
Source:
Returns:
Returns success with deleted record or error message
Type
Promise.<Object>
Example
const result = await api.deleteById("user-123");

(async) findRowById(idValue) → {Promise.<Object>}

Internal helper: find a row by ID
Parameters:
Name Type Description
idValue string Record ID
Source:
Returns:
{status, data: {rowData, rowIndex, sheetId}, error}
Type
Promise.<Object>

generateUniqueId(lenopt) → {string}

Generate a unique ID for records
Parameters:
Name Type Attributes Default Description
len number <optional>
15 Length of the ID to generate
Source:
Returns:
A unique alphanumeric ID
Type
string
Example
const id = api.generateUniqueId();
// result: "a1b2c3d4e5f6g7h"

(async) getByField(fieldName, value) → {Promise.<Object>}

Get a record by any field value
Parameters:
Name Type Description
fieldName string Name of the field to search
value string | number | boolean Value to match
Source:
Returns:
Returns success with the record or error message
Type
Promise.<Object>
Example
const user = await api.getByField("email", "john@example.com");

getCacheStats() → {Object}

Get cache statistics for debugging
Source:
Returns:
Cache stats
Type
Object

(async) getIdByField(fieldName, value) → {Promise.<Object>}

Get record ID by field value
Parameters:
Name Type Description
fieldName string Name of the field to search
value string | number | boolean Value to match
Source:
Returns:
Returns success with the ID or error message
Type
Promise.<Object>
Example
const userId = await api.getIdByField("email", "john@example.com");

getSchema() → {Object}

Get the current schema (field types)
Source:
Returns:
Schema object with field names as keys and types as values
Type
Object

(async) recordExists(idValue) → {Promise.<Object>}

CHECK if a record exists by ID
Parameters:
Name Type Description
idValue string The record ID to check
Source:
Returns:
Standard {status, data: boolean, error} response
Type
Promise.<Object>
Example
const exists = await api.recordExists("user-123");
// result: { status: "success", data: true } or { status: "error", data: false }

(async) rowCount() → {Promise.<Object>}

Get the number of data rows in the sheet
Source:
Returns:
Returns success with the count or error message
Type
Promise.<Object>
Example
const count = await api.rowCount();

(async) sheetExists(sheetNameopt) → {Promise.<Object>}

CHECK if a sheet exists
Parameters:
Name Type Attributes Description
sheetName string <optional>
Name of sheet to check (defaults to configured sheetName)
Source:
Returns:
Standard {status, data: boolean, error} response
Type
Promise.<Object>
Example
const exists = await api.sheetExists("Users");
// result: { status: "success", data: true }

(async) update(record) → {Promise.<Object>}

Update a record using an object that includes the ID
Parameters:
Name Type Description
record Object The record data including ID
Source:
Returns:
Returns success with updated record or error message
Type
Promise.<Object>
Example
const result = await api.update({ id: "user-123", age: 25 });

(async) updateById(idValue, updatedData) → {Promise.<Object>}

Update a record by its ID
Parameters:
Name Type Description
idValue string The record ID to update
updatedData Object The fields to update
Source:
Returns:
Returns success with updated record or error message
Type
Promise.<Object>
Example
const result = await api.updateById("user-123", { status: "inactive" });