Constructor
new SheetAPI()
- Version:
- 2.0.0
- Since:
- 1.0.0
- 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" });