Skip to content

Commit 2bd4fc7

Browse files
AaronDDMcursoragentdemello.aaron
authored
Fix: Update ListGrantsQueryParams to use snake_case parameter values (Fixes #669) (#672)
Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: demello.aaron <demello.aaron@gmail.com>
1 parent e4ed8bd commit 2bd4fc7

File tree

15 files changed

+1170
-162
lines changed

15 files changed

+1170
-162
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99

1010
### Fixed
1111
- Make `Participant.email` optional in `Event` model to match API behavior ([#670](https://github.com/nylas/nylas-nodejs/issues/670))
12+
- Updated `ListGrantsQueryParams.sortBy` values to match API expectations (`'created_at' | 'updated_at'` instead of `'createdAt' | 'updatedAt'`)
1213

1314
## [7.13.1] - 2025-09-18
1415

examples/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ This directory contains examples of how to use the Nylas Node.js SDK to interact
44

55
## Examples
66

7+
- [Grants](./grants/README.md) - Examples of how to fetch, list, sort, and filter grants (authenticated connections to email/calendar providers).
78
- [Notetakers](./notetakers/README.md) - Examples of how to use the Nylas Notetakers API to invite a Notetaker bot to meetings, get recordings and transcripts, and more.
89
- [Messages](./messages/README.md) - Examples of how to use the Nylas Messages API to list, find, send, update messages, and work with new features like tracking options and raw MIME data.
910
- [Folders](./folders/README.md) - Examples of how to use the Nylas Folders API, including the new `singleLevel` parameter for Microsoft accounts.
@@ -32,17 +33,20 @@ To run these examples, you'll need to:
3233
4. Run the example:
3334
```bash
3435
# Using ts-node
36+
npx ts-node grants/grants.ts
3537
npx ts-node notetakers/notetaker.ts
3638
npx ts-node calendars/event_with_notetaker.ts
3739
npx ts-node messages/messages.ts
3840

3941
# Or using npm scripts
42+
npm run grants
4043
npm run notetakers
4144
npm run calendars
4245
npm run messages
4346

4447
# Or if you compiled the examples
4548
npm run build
49+
node dist/grants/grants.js
4650
node dist/notetakers/notetaker.js
4751
node dist/calendars/event_with_notetaker.js
4852
node dist/messages/messages.js

examples/grants/README.md

Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
# Nylas Grants Examples
2+
3+
This directory contains examples demonstrating how to work with grants using the Nylas Node.js SDK. Grants represent authenticated connections between your application and email/calendar providers like Gmail, Outlook, Yahoo, and others.
4+
5+
## What are Grants?
6+
7+
In the Nylas API, a **Grant** represents an authenticated connection to a user's email or calendar account. Each grant contains:
8+
9+
- **Authentication details** - OAuth tokens and provider information
10+
- **Scope permissions** - What data your app can access (email, calendar, contacts, etc.)
11+
- **Account metadata** - Email address, provider type, creation/update timestamps
12+
- **Status information** - Whether the grant is valid or needs re-authentication
13+
14+
## Examples Overview
15+
16+
The `grants.ts` file demonstrates comprehensive grant management including:
17+
18+
### 📋 **Basic Operations**
19+
- **List all grants** - Retrieve all authenticated accounts
20+
- **Fetch specific grant** - Get detailed information about a single grant
21+
- **Pagination** - Handle large numbers of grants efficiently
22+
23+
### 🔄 **Sorting & Filtering**
24+
- **Sort by creation date** - See newest or oldest grants first
25+
- **Sort by update date** - Find recently modified grants
26+
- **Filter by provider** - Show only Gmail, Outlook, etc.
27+
- **Filter by status** - Find valid, invalid, or expired grants
28+
- **Filter by date range** - Grants created in specific time periods
29+
30+
### 🎯 **Advanced Features**
31+
- **Multiple filters** - Combine provider, status, and date filters
32+
- **Client-side grouping** - Organize grants by provider or other criteria
33+
- **Scope analysis** - Find grants with specific permissions
34+
- **Rate limit monitoring** - Track API usage limits
35+
36+
## Quick Start
37+
38+
### 1. Set up environment
39+
Create a `.env` file in the `examples` directory:
40+
```bash
41+
NYLAS_API_KEY=your_api_key_here
42+
NYLAS_API_URI=https://api.us.nylas.com # Optional: defaults to US API
43+
```
44+
45+
### 2. Install dependencies
46+
```bash
47+
cd examples
48+
npm install
49+
```
50+
51+
### 3. Run the example
52+
```bash
53+
# Using ts-node (recommended for development)
54+
npx ts-node grants/grants.ts
55+
56+
# Or compile and run
57+
npm run build
58+
node dist/grants/grants.js
59+
```
60+
61+
## Example Functions
62+
63+
### Basic Listing
64+
```typescript
65+
// List all grants
66+
const grants = await nylas.grants.list();
67+
68+
// List with pagination
69+
const grants = await nylas.grants.list({
70+
queryParams: {
71+
limit: 10,
72+
offset: 0,
73+
},
74+
});
75+
```
76+
77+
### Sorting
78+
```typescript
79+
// Sort by creation date (newest first)
80+
const grants = await nylas.grants.list({
81+
queryParams: {
82+
sortBy: 'created_at',
83+
orderBy: 'desc',
84+
},
85+
});
86+
87+
// Sort by update date (most recently updated first)
88+
const grants = await nylas.grants.list({
89+
queryParams: {
90+
sortBy: 'updated_at',
91+
orderBy: 'desc',
92+
},
93+
});
94+
```
95+
96+
### Filtering
97+
```typescript
98+
// Filter by provider
99+
const gmailGrants = await nylas.grants.list({
100+
queryParams: {
101+
provider: 'google',
102+
},
103+
});
104+
105+
// Filter by status
106+
const validGrants = await nylas.grants.list({
107+
queryParams: {
108+
grantStatus: 'valid',
109+
},
110+
});
111+
112+
// Filter by date range (last 30 days)
113+
const thirtyDaysAgo = Math.floor((Date.now() - (30 * 24 * 60 * 60 * 1000)) / 1000);
114+
const recentGrants = await nylas.grants.list({
115+
queryParams: {
116+
since: thirtyDaysAgo,
117+
},
118+
});
119+
```
120+
121+
### Fetching Individual Grants
122+
```typescript
123+
// Fetch a specific grant by ID
124+
const grant = await nylas.grants.find({
125+
grantId: 'grant-id-here',
126+
});
127+
128+
console.log(`Grant for ${grant.data.email} (${grant.data.provider})`);
129+
console.log(`Scopes: ${grant.data.scope.join(', ')}`);
130+
console.log(`Status: ${grant.data.grantStatus}`);
131+
```
132+
133+
## Grant Object Properties
134+
135+
Each grant object contains the following key properties:
136+
137+
```typescript
138+
interface Grant {
139+
id: string; // Unique grant identifier
140+
provider: string; // 'google', 'microsoft', 'yahoo', etc.
141+
email?: string; // Associated email address
142+
name?: string; // User's display name
143+
grantStatus?: string; // 'valid', 'invalid', 'expired'
144+
scope: string[]; // Permissions: ['email', 'calendar', 'contacts']
145+
createdAt: number; // Unix timestamp
146+
updatedAt?: number; // Unix timestamp of last update
147+
providerUserId?: string; // Provider's internal user ID
148+
ip?: string; // IP address during authentication
149+
userAgent?: string; // Browser/client used for auth
150+
settings?: Record<string, unknown>; // Provider-specific settings
151+
}
152+
```
153+
154+
## Available Query Parameters
155+
156+
When listing grants, you can use these parameters:
157+
158+
- **`limit`** (number) - Maximum results to return (default: 10, max: 200)
159+
- **`offset`** (number) - Skip this many results for pagination
160+
- **`sortBy`** - Sort field: `'created_at'` or `'updated_at'`
161+
- **`orderBy`** - Sort direction: `'asc'` or `'desc'`
162+
- **`since`** (number) - Unix timestamp to filter grants created after
163+
- **`before`** (number) - Unix timestamp to filter grants created before
164+
- **`email`** (string) - Filter by email address
165+
- **`grantStatus`** (string) - Filter by status: `'valid'`, `'invalid'`, etc.
166+
- **`ip`** (string) - Filter by IP address
167+
- **`provider`** (string) - Filter by provider: `'google'`, `'microsoft'`, etc.
168+
169+
## Common Use Cases
170+
171+
### 1. **Health Check Dashboard**
172+
```typescript
173+
// Get overview of all grants and their status
174+
const allGrants = await nylas.grants.list();
175+
const grantsByStatus = allGrants.data.reduce((acc, grant) => {
176+
const status = grant.grantStatus || 'valid';
177+
acc[status] = (acc[status] || 0) + 1;
178+
return acc;
179+
}, {});
180+
console.log('Grant Status Overview:', grantsByStatus);
181+
```
182+
183+
### 2. **Find Grants Needing Re-authentication**
184+
```typescript
185+
// Find invalid or expired grants
186+
const invalidGrants = await nylas.grants.list({
187+
queryParams: {
188+
grantStatus: 'invalid',
189+
},
190+
});
191+
console.log(`${invalidGrants.data.length} grants need re-authentication`);
192+
```
193+
194+
### 3. **Provider Distribution Analysis**
195+
```typescript
196+
// See which providers your users prefer
197+
const grants = await nylas.grants.list();
198+
const providerCounts = grants.data.reduce((acc, grant) => {
199+
acc[grant.provider] = (acc[grant.provider] || 0) + 1;
200+
return acc;
201+
}, {});
202+
console.log('Provider Distribution:', providerCounts);
203+
```
204+
205+
### 4. **Recent Activity Monitoring**
206+
```typescript
207+
// Find grants created or updated in the last week
208+
const weekAgo = Math.floor((Date.now() - (7 * 24 * 60 * 60 * 1000)) / 1000);
209+
const recentActivity = await nylas.grants.list({
210+
queryParams: {
211+
since: weekAgo,
212+
sortBy: 'created_at',
213+
orderBy: 'desc',
214+
},
215+
});
216+
```
217+
218+
## Rate Limiting
219+
220+
The Nylas API includes rate limiting. You can monitor your usage:
221+
222+
```typescript
223+
const response = await nylas.grants.list();
224+
if (response.rawHeaders) {
225+
const limit = response.rawHeaders['x-rate-limit-limit'];
226+
const remaining = response.rawHeaders['x-rate-limit-remaining'];
227+
console.log(`Rate Limit: ${remaining}/${limit} requests remaining`);
228+
}
229+
```
230+
231+
## Error Handling
232+
233+
Always wrap grant operations in try-catch blocks:
234+
235+
```typescript
236+
try {
237+
const grants = await nylas.grants.list();
238+
// Process grants...
239+
} catch (error) {
240+
if (error.status === 401) {
241+
console.error('Invalid API key');
242+
} else if (error.status === 429) {
243+
console.error('Rate limit exceeded');
244+
} else {
245+
console.error('Error listing grants:', error);
246+
}
247+
}
248+
```
249+
250+
## Next Steps
251+
252+
After exploring grants, you might want to:
253+
254+
1. **Use grants to access data** - Use grant IDs to list messages, events, or contacts
255+
2. **Monitor grant health** - Set up automated checks for invalid grants
256+
3. **Implement re-authentication** - Handle expired grants gracefully
257+
4. **Build user dashboards** - Show users their connected accounts
258+
259+
## Related Documentation
260+
261+
- [Nylas Authentication Guide](https://developer.nylas.com/docs/the-basics/authentication/)
262+
- [Grant Management API](https://developer.nylas.com/docs/api/v3/admin/#tag--Grants)
263+
- [OAuth Scopes Reference](https://developer.nylas.com/docs/the-basics/authentication/oauth-scopes/)

0 commit comments

Comments
 (0)