N

Nokfa Docs

ไม่มีชื่อบทความ

การสร้างไฟล์เชื่อมต่อ Google Calendar API: googleClient.js

1. ตำแหน่งไฟล์

สร้างไฟล์ใหม่ที่:

src/lib/googleClient.js

ใช้รูปแบบ ESM (JavaScript module)

2. โค้ดตัวอย่างเต็ม

// src/lib/googleClient.js

import { google } from 'googleapis';

/**
 * คืนค่า Calendar client ที่ authenticate แล้วด้วย Service Account
 * Returns an authenticated Google Calendar client instance.
 */
export function getCalendarClient() {
  try {
    const client = new google.auth.JWT({
      email: process.env.GOOGLE_CLIENT_EMAIL,
      key: process.env.GOOGLE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
      scopes: ['https://www.googleapis.com/auth/calendar'],
    });

    const calendar = google.calendar({
      version: 'v3',
      auth: client,
    });

    return calendar;
  } catch (error) {
    if (process.env.NODE_ENV !== 'production') {
      console.warn('Failed to create Google Calendar client:', error);
    }
    throw new Error('Google Calendar Client Initialization Failed');
  }
}

3. อธิบายโครงสร้าง

  • ใช้ google.auth.JWT เพื่อยืนยันตัวตนผ่าน Service Account
  • อ่านค่า config จาก process.env
  • แปลง \n ใน GOOGLE_PRIVATE_KEY ให้เป็นบรรทัดใหม่จริง ๆ
  • Scopes ที่ใช้: https://www.googleapis.com/auth/calendar
  • ดักจับ error:
    • แสดง console.warn เฉพาะ NODE_ENV !== 'production'
    • โยน Error ใหม่เพื่อให้ API layer จับต่อได้

4. ตัวอย่าง Unit Test ด้วย Jest

สร้างไฟล์ test:

src/lib/__tests__/googleClient.test.js

โค้ดตัวอย่าง:

import { getCalendarClient } from '../googleClient';

// Mock Environment Variables
beforeAll(() => {
  process.env.GOOGLE_CLIENT_EMAIL = 'test-sa@project-id.iam.gserviceaccount.com';
  process.env.GOOGLE_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\\nTEST_KEY\\n-----END PRIVATE KEY-----';
});

test('should create Google Calendar client successfully', () => {
  const calendar = getCalendarClient();
  expect(calendar).toHaveProperty('calendarList');
  expect(typeof calendar.calendarList.list).toBe('function');
});

test('should throw error if environment variables are missing', () => {
  delete process.env.GOOGLE_CLIENT_EMAIL;
  expect(() => getCalendarClient()).toThrow('Google Calendar Client Initialization Failed');
});

5. หมายเหตุเพิ่มเติม

  • ใช้ Jest version ล่าสุดที่รองรับ ESM (jest@29+)
  • การใช้ real API Key ใน unit test จริง ๆ ต้อง mock ให้ปลอดภัยยิ่งขึ้น (ที่นี่เป็น test เบื้องต้น)
  • หลีกเลี่ยงการทำ unit test ที่ยิงไปยัง Google API จริงในการ run ทั่วไป

อ้างอิง: Google Auth Library for Node.js