npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

google-calendar-client

v1.0.1

Published

Simple, type-safe TypeScript client for Google Calendar API with automatic OAuth2 token refresh and batch operations

Readme

Google Calendar API Client

npm version npm downloads License: MIT TypeScript

A simple, type-safe TypeScript wrapper for Google Calendar API with automatic token refresh.

Features

  • ✅ Full CRUD operations (Create, Read, Update, Delete)
  • ✅ List and search events with advanced filters
  • ✅ Batch operations for multiple events
  • ✅ Automatic OAuth2 token refresh
  • ✅ Google Meet integration
  • ✅ TypeScript support
  • ✅ Zero dependencies

Installation

npm install google-calendar-client

Quick Start

1. Setup

Get your Google OAuth credentials from Google Cloud Console:

  • Create a project
  • Enable Google Calendar API
  • Create OAuth 2.0 credentials

2. Initialize

import { GoogleCalendarAPI } from 'google-calendar-client';

const calendar = new GoogleCalendarAPI({
  clientId: 'your-client-id.apps.googleusercontent.com',
  clientSecret: 'your-client-secret',
});

3. Authenticate User

// Redirect user to Google OAuth
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({
  client_id: 'your-client-id',
  redirect_uri: 'http://localhost:3000/callback',
  response_type: 'code',
  scope: 'https://www.googleapis.com/auth/calendar',
  access_type: 'offline',
  prompt: 'consent',
})}`;

// After redirect, exchange code for tokens
const tokens = await calendar.exchangeAuthCode({
  code: 'code-from-redirect',
  redirectUri: 'http://localhost:3000/callback',
});

// Save these tokens
const accessToken = tokens.access_token;
const refreshToken = tokens.refresh_token;

4. Use the API

// Create an event
const event = await calendar.createEvent({
  title: 'Team Meeting',
  startEpoch: Math.floor(Date.now() / 1000) + 3600, // 1 hour from now
  endEpoch: Math.floor(Date.now() / 1000) + 5400,   // 1.5 hours from now
  accessToken,
  refreshToken,
});

console.log('Event created:', event.event.htmlLink);
console.log('Meet link:', event.event.hangoutLink);

Basic Usage

Create Event

const result = await calendar.createEvent({
  title: 'Product Demo',
  description: 'Demo for new client',
  startEpoch: 1698336000,
  endEpoch: 1698339600,
  timeZone: 'America/New_York',
  location: 'Conference Room A',
  attendees: [
    { email: '[email protected]' },
    { email: '[email protected]' },
  ],
  accessToken,
  refreshToken,
});

List Events

const result = await calendar.listEvents({
  accessToken,
  refreshToken,
  timeMin: Math.floor(Date.now() / 1000), // From now
  timeMax: Math.floor(Date.now() / 1000) + 7 * 86400, // Next 7 days
  maxResults: 50,
  singleEvents: true, // Expand recurring events
  orderBy: 'startTime',
});

for (const event of result.events) {
  console.log(`${event.summary} - ${event.start.dateTime}`);
}

Update Event

await calendar.updateEvent({
  eventId: 'event-id',
  title: 'Updated Title',
  startEpoch: 1698340000,
  endEpoch: 1698343600,
  accessToken,
  refreshToken,
});

Delete Event

await calendar.deleteEvent({
  eventId: 'event-id',
  accessToken,
  refreshToken,
});

Get Single Event

const result = await calendar.getEvent({
  eventId: 'event-id',
  accessToken,
  refreshToken,
});

console.log(result.event);

Advanced Features

Batch Operations

Create, update, or delete multiple events in one call:

const result = await calendar.batchOperations({
  accessToken,
  refreshToken,
  operations: [
    // Create events
    {
      type: 'create',
      data: {
        title: 'Event 1',
        startEpoch: 1698336000,
        endEpoch: 1698339600,
      },
    },
    // Update events
    {
      type: 'update',
      data: {
        eventId: 'existing-id',
        title: 'Updated Event',
      },
    },
    // Delete events
    {
      type: 'delete',
      data: {
        eventId: 'old-event-id',
      },
    },
  ],
});

console.log(`Success: ${result.successCount}, Failed: ${result.failureCount}`);

Recurring Events

await calendar.createEvent({
  title: 'Weekly Standup',
  startEpoch: 1698336000,
  endEpoch: 1698337800,
  recurrence: ['RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR;COUNT=10'],
  accessToken,
  refreshToken,
});

Search Events

const result = await calendar.listEvents({
  accessToken,
  refreshToken,
  q: 'team meeting', // Search text
  timeMin: Math.floor(Date.now() / 1000),
});

Custom Event Properties

await calendar.createEvent({
  title: 'Client Meeting',
  startEpoch: 1698336000,
  endEpoch: 1698339600,
  extendedProperties: {
    private: {
      clientId: '12345',
      salesRep: 'john',
    },
  },
  accessToken,
  refreshToken,
});

Important Notes

Token Refresh

The library automatically refreshes expired tokens. Always save the new token:

const result = await calendar.createEvent({...});

if (result.token) {
  // Token was refreshed - save it!
  accessToken = result.token.access_token;
  refreshToken = result.token.refresh_token || refreshToken;
  // Update your database
}

Timestamps

Use seconds, not milliseconds:

// ✅ Correct
const startEpoch = Math.floor(Date.now() / 1000);

// ❌ Wrong
const startEpoch = Date.now();

Error Handling

try {
  await calendar.createEvent({...});
} catch (error) {
  console.error('Failed:', error.message);
}

API Methods

| Method | Description | |--------|-------------| | exchangeAuthCode() | Exchange OAuth code for tokens | | createEvent() | Create a new calendar event | | updateEvent() | Update an existing event | | deleteEvent() | Delete an event | | getEvent() | Get a single event | | listEvents() | List/search events with filters | | moveEvent() | Move event between calendars | | batchOperations() | Bulk create/update/delete |

Type Definitions

Full TypeScript support with comprehensive types. See API_REFERENCE.md for details.

import type {
  CalendarEvent,
  CreateEventPayload,
  ListEventsPayload,
  BatchOperationsPayload,
} from 'google-calendar-client';

Examples

Complete App Example

import { GoogleCalendarAPI } from 'google-calendar-client';

class CalendarService {
  private calendar: GoogleCalendarAPI;

  constructor() {
    this.calendar = new GoogleCalendarAPI({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    });
  }

  async createMeeting(data: {
    title: string;
    startTime: Date;
    duration: number;
    attendees: string[];
  }) {
    const tokens = await this.getTokens(); // Your token storage
    const startEpoch = Math.floor(data.startTime.getTime() / 1000);
    const endEpoch = startEpoch + data.duration * 60;

    const result = await this.calendar.createEvent({
      title: data.title,
      startEpoch,
      endEpoch,
      attendees: data.attendees.map(email => ({ email })),
      accessToken: tokens.accessToken,
      refreshToken: tokens.refreshToken,
    });

    if (result.token) {
      await this.saveTokens(result.token); // Update stored tokens
    }

    return {
      eventId: result.event.id,
      meetLink: result.event.hangoutLink,
    };
  }
}

Import from CSV

const events = parseCSV('events.csv');

const result = await calendar.batchOperations({
  accessToken,
  refreshToken,
  operations: events.map(e => ({
    type: 'create',
    data: {
      title: e.title,
      startEpoch: parseDate(e.start),
      endEpoch: parseDate(e.end),
    },
  })),
});

console.log(`Imported ${result.successCount} events`);

Documentation

License

MIT

Support