Skip to content

Commit

Permalink
docs: remove operations reference and update navigation; enhance data…
Browse files Browse the repository at this point in the history
… operations and examples #11
  • Loading branch information
teles committed Dec 29, 2024
1 parent e0e0178 commit 285a56d
Show file tree
Hide file tree
Showing 8 changed files with 587 additions and 42 deletions.
2 changes: 1 addition & 1 deletion docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export default defineConfig({
text: 'Reference',
items: [
{ text: 'Error Handling', link: '/en/reference/error-handling' },
{ text: 'Operations', link: '/en/reference/operations' }
{ text: 'Types', link: '/en/reference/types' }
]
},
{
Expand Down
47 changes: 40 additions & 7 deletions docs/en/concepts/data-operations.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,44 @@
# Data Operations

HolySheets! provides a set of CRUD-like operations:
HolySheets! provides a set of CRUD-like operations to interact with your Google Sheets data:

- **findFirst**, **findMany**, **findAll**: Query rows.
- **insert**: Insert new records.
- **updateFirst**, **updateMany**: Update existing rows.
- **deleteFirst**, **deleteMany**: Delete records.
- **clearFirst**, **clearMany**: Clear cell values without removing rows.
- **Finding Data**

All operations can optionally return metadata such as affected ranges and operation duration.
- [`findFirst`](/en/guides/finding-data.md#findfirst): Retrieves the first matching record.
- [`findMany`](/en/guides/finding-data.md#findmany): Retrieves multiple matching records.
- [`findAll`](/en/guides/finding-data.md#findall): Retrieves all records.

- **Inserting Data**

- [`insert`](/en/guides/inserting-data.md): Inserts new records.

- **Updating Data**

- [`updateFirst`](/en/guides/updating-data.md#updatefirst): Updates the first matching record.
- [`updateMany`](/en/guides/updating-data.md#updatemany): Updates all matching records.

- **Deleting Data**

- [`deleteFirst`](/en/guides/deleting-data.md#deletefirst): Deletes the first matching record.
- [`deleteMany`](/en/guides/deleting-data.md#deletemany): Deletes all matching records.

- **Clearing Data**
- [`clearFirst`](/en/guides/clearing-data.md#clearfirst): Clears the first matching record’s cell contents (row not removed).
- [`clearMany`](/en/guides/clearing-data.md#clearmany): Clears all matching records’ cell contents (rows not removed).

All operations can optionally return metadata such as affected ranges and operation duration. To include metadata in your responses, pass `{ includeMetadata: true }` in the second parameter of any operation method.

```typescript
// Example: Finding the first record named "Alice" and including metadata
const result = await holySheetsInstance.findFirst(
{
where: { name: 'Alice' }
},
{
includeMetadata: true
}
)

console.log(result.data) // The matching record
console.log(result.metadata) // Optional metadata (if requested)
```
13 changes: 13 additions & 0 deletions docs/en/concepts/where-filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@
| `endsWith` | Ends with a specified substring | `{ email: { endsWith: '@example.com' } }` |
| `search` | Matches a regular expression pattern | `{ name: { search: '^Pro.*' } }` |

> **Note**: When multiple filters are set on the **same field**, they are combined with an **AND** operation. For instance:
>
> ```typescript
> // Both conditions must be met:
> // The 'role' field is not 'admin', AND it starts with 'senior'
> where: {
> role: {
> not: 'admin',
> startsWith: 'senior'
> }
> }
> ```
## equals
Filters records where the specified field exactly matches the provided value.
Expand Down
142 changes: 138 additions & 4 deletions docs/en/configuration.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,141 @@
# Configuration

To configure HolySheets!:
**HolySheets!** requires a few key parameters and setup steps before you can begin interacting with your Google Sheets data. Below is a more detailed overview of the necessary configurations.

- **spreadsheetId**: The ID of your Google Spreadsheet.
- **auth**: A Google Auth client (JWT or OAuth2) with appropriate permissions.
- **Sheets Title**: Call `base(sheetTitle)` to target a specific sheet.
---

## Quick Start

1. **Install HolySheets!**

```bash
pnpm install holysheets
```

2. **Obtain Google Credentials**

- Create a **Google Cloud project** and enable the _Google Sheets API_.
- Generate the appropriate **credentials** (JWT or OAuth2) with permission to access the intended spreadsheet.
- For more information about authentication check [JWT](/en/authentication/jwt) and [OAuth](/en/authentication/oauth)

3. **Initialize HolySheets**

Pass both `spreadsheetId` and `auth` to the **HolySheets** constructor:

```Typescript
import HolySheets from 'holysheets'
import { authClient } from './your-auth-setup'

const holySheetsInstance = new HolySheets({
spreadsheetId: 'your-spreadsheet-id',
auth: authClient
})
```

---

## Essential Configuration Parameters

### `spreadsheetId`

- **Description**: The unique ID of your Google Spreadsheet, which can be found in the spreadsheet’s URL.
- **Example**:

```text
https://docs.google.com/spreadsheets/d/1AbCDefGhIJkLMNOPQRS_TUVWXYZ/edit#gid=0
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```

Everything between `d/` and `/edit` is your `spreadsheetId`.

---

### `auth`

- **Description**: An authenticated Google client capable of calling the Sheets API.
- **Supported Auth Types**:
- **JWT (Service Account)**: Commonly used for server-to-server communications.
- **OAuth2**: Used when you need user consent to access their Google Sheets.
- **Example (JWT)**:

```Typescript
import { google } from 'googleapis'

const authClient = new google.auth.JWT(serviceAccountEmail, null, privateKey, [
'https://www.googleapis.com/auth/spreadsheets'
])
```

- **Example (OAuth2)**:

```Typescript
import { google } from 'googleapis'

const authClient = new google.auth.OAuth2(clientId, clientSecret, redirectUri)
// Then use authClient.getToken(...) and authClient.setCredentials(...) as needed
```

---

## Specifying a Sheet

Once you have an instance of **HolySheets**, you can target a particular sheet (tab) within your spreadsheet by calling `base(sheetTitle)`:

```Typescript
const userSheet = holySheetsInstance.base('Users')

// Now all operations (find, insert, etc.) are performed against the "Users" sheet.
```

**Note**: If you omit `base(...)` or don’t specify a `sheet`, operations typically fail because the system doesn’t know which tab to target.

---

## Additional Tips

- **Permissions**: Your auth client must have permission to read/write the specified spreadsheet (depending on the operations you intend to perform).
- **Sheet Titles**: Keep your sheet (tab) names descriptive (e.g., `Orders`, `Users`, `Inventory`). You’ll use these names in `base(sheetTitle)`.
- **Environment Variables**: Consider storing your `spreadsheetId` and auth credentials in environment variables or a secure vault for better security and portability.

---

## Putting It All Together

```Typescript
// Example of a final setup:
import { google } from 'googleapis'
import HolySheets from 'holysheets'

async function createHolySheetsInstance() {
// 1. Auth - Service Account example
const authClient = new google.auth.JWT(
process.env.GOOGLE_CLIENT_EMAIL,
undefined,
(process.env.GOOGLE_PRIVATE_KEY || '').replace(/\\n/g, '\n'),
['https://www.googleapis.com/auth/spreadsheets']
)

// 2. Construct HolySheets
const holySheetsInstance = new HolySheets({
spreadsheetId: process.env.SPREADSHEET_ID as string,
auth: authClient
})

// 3. Select the "Users" sheet
const userSheet = holySheetsInstance.base('Users')

// 4. Perform an operation (e.g., insert)
const insertResult = await userSheet.insert({
data: [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 }
]
})

console.log(insertResult)
}

createHolySheetsInstance().catch(console.error)
```

Following these steps ensures that **HolySheets!** is properly configured and ready to handle your data operations on Google Sheets.
136 changes: 126 additions & 10 deletions docs/en/examples/advanced-queries.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,133 @@
# Advanced Queries Example
# Advanced Queries

```Typescript
// Find users with email ending in @example.com and age > 30
const results = await users.findMany({
This guide explores more in-depth features and patterns when working with HolySheets!, including complex filtering, metadata handling, and batch updates.

---

## 1. Using Multiple Filters in `where` (Logical AND)

```typescript
await holySheetsInstance.base('Orders').findMany(
{
where: {
status: { not: 'cancelled' },
total: { gt: 100 }
}
},
{
includeMetadata: true
}
)
```

**Explanation**:

- Both filters must be satisfied (logical AND).
- Fetches orders where `status` is NOT `'cancelled'` **and** `total` is greater than `100`.
- Includes metadata to inspect the affected ranges and operation duration.

---

## 2. Combining Filter Types

```typescript
await holySheetsInstance.base('Products').findMany({
where: {
email: { endsWith: '@example.com' },
age: { gt: 30 }
category: { in: ['Electronics', 'Apparel'] },
name: { startsWith: 'Pro' }
}
})
```

**Explanation**:

- Filters the `Products` sheet for rows in the categories `'Electronics'` or `'Apparel'`, **and** names starting with `'Pro'`.

---

## 3. Performing Batch Updates with `updateMany`

```typescript
await holySheetsInstance.base('Users').updateMany({
where: {
status: 'active'
},
data: { status: 'inactive' }
})
```

**Explanation**:

- Finds all users where `status` equals `'active'`, then sets `status` to `'inactive'`.
- Be cautious: **all** matching rows will be updated.

---

## 4. Bulk Clearing with `clearMany`

// Update multiple inactive users at once
await users.updateMany({
where: { status: { equals: 'inactive' } },
data: { status: 'active' }
```typescript
await holySheetsInstance.base('Logs').clearMany({
where: {
level: { in: ['debug', 'trace'] }
}
})
```

**Explanation**:

- Clears all rows in the `Logs` sheet that have `level` `'debug'` or `'trace'`.
- Does not delete rows, only empties their contents.

---

## 5. Retrieving All Records with Metadata

```typescript
const allRecords = await holySheetsInstance.base('Inventory').findAll(
{
includeEmptyRows: true
},
{
includeMetadata: true
}
)
console.log(allRecords.metadata)
```

**Explanation**:

- Retrieves every row from the `Inventory` sheet, **including** empty rows.
- Returns metadata about the operation, such as execution time and affected ranges.

---

## 6. Advanced Error Handling

You can catch and log errors when an operation fails:

```typescript
try {
await holySheetsInstance.base('Payments').deleteMany({
where: { status: 'failed' }
})
} catch (error) {
console.error('Error deleting failed payments:', error)
}
```

**Explanation**:

- If the Sheets API call fails or no permission is granted, an error is thrown.
- Log or handle this error in your application logic.

---

## Tips for Scaling

1. **Use Metadata**: Inspect operation duration, record counts, and any errors for performance insights or auditing.
2. **Refine Filters**: Use multiple filters (`gt`, `lt`, `not`, etc.) to narrow down large data sets.
3. **Optimize Sheets**: Regularly review the size of your spreadsheets and consider splitting data into multiple tabs for better performance.

---

Check [Basic Queries](./basic-queries.md) if you need a refresher on the fundamentals.
Loading

0 comments on commit 285a56d

Please sign in to comment.