Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: make google sheet row more flexible #226

Merged
merged 1 commit into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/app/api/emailSubscription/route.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
import { apiWrapper } from '@/lib/backend/api/apiWrapper'
import { NextResponse } from 'next/server'
import * as z from 'zod'
import { addEmailSubscription } from '@/lib/backend/emailSubscriptions/addEmailSubscription'
import { addRowToGoogleSheet } from '@/lib/backend/google-sheets/addRowToGoogleSheet'
import { JuiceCrowdError } from '@/lib/error'

const GOOGLE_SPREADSHEET_ID = '1_OpoitLq1pLQIqsdDGh6SbRrdtmABXdIXuJD6HMAVCo'
const EMAIL_SUBSCRIPTIONS_SHEET_NUMBER = 1

const emailSubscriptionsSchema = z.object({
email: z.string().email('Invalid email address'),
})

export const POST = apiWrapper(emailSubscriptionsSchema, async data => {
try {
await addEmailSubscription(data.email)
await addRowToGoogleSheet({
row: data.email,
sheetId: GOOGLE_SPREADSHEET_ID,
sheetNumber: EMAIL_SUBSCRIPTIONS_SHEET_NUMBER,
unique: true,
})
} catch (e) {
if (typeof e === 'object' && e instanceof JuiceCrowdError) {
throw e
Expand Down
73 changes: 0 additions & 73 deletions src/lib/backend/emailSubscriptions/addEmailSubscription.ts

This file was deleted.

98 changes: 98 additions & 0 deletions src/lib/backend/google-sheets/addRowToGoogleSheet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { JuiceCrowdError } from '@/lib/error'
import { google } from 'googleapis'

export type AddRowToGoogleSheetParams = {
row: string | string[]
sheetId: string
sheetNumber: number
unique?: boolean
}

/**
* Add a row to a google sheet.
*
* @param row The row to add. Can be a string or an array of strings.
* @param sheetId The ID of the google sheet to add the row to.
* @param unique If true, will throw an error if the row already exists.
*/
export const addRowToGoogleSheet = async ({
row,
sheetId,
sheetNumber,
unique = false,
}: AddRowToGoogleSheetParams) => {
if (sheetNumber < 1) {
throw new Error('Sheet number must be greater than 0')
}
const jwtClient = getGoogleJWTClient()

try {
await jwtClient.authorize()
} catch (e) {
console.error('Google Auth Error:', e)
throw new Error('Google Auth Error')
}

const sheetsApi = google.sheets({ version: 'v4', auth: jwtClient })

const existingRowsRes = await sheetsApi.spreadsheets.values.get({
spreadsheetId: sheetId,
// Get all rows and cols
range: `Sheet${sheetNumber}!A:Z`,
})
const existingRows = existingRowsRes.data.values || []

if (unique) {
if (typeof row === 'string') {
if (existingRows.flat().includes(row)) {
throw new JuiceCrowdError('Row already exists', 409)
}
} else {
if (existingRows.includes(row)) {
throw new JuiceCrowdError('Row already exists', 409)
}
}
}

const nextRow = existingRows.length + 1
const range = `Sheet${sheetNumber}!A${nextRow}`

try {
const values = typeof row === 'string' ? [[row]] : [row]
await sheetsApi.spreadsheets.values.append({
spreadsheetId: sheetId,
range: range,
valueInputOption: 'RAW',
insertDataOption: 'INSERT_ROWS',
requestBody: {
values,
},
})
} catch (e) {
console.error('Failed to append row', e)
throw new Error('Failed to append row')
}
}

const getGoogleJWTClient = () => {
const GoogleSheetsServiceAccountRaw =
process.env.GOOGLE_SHEETS_SERVICE_ACCOUNT
if (!GoogleSheetsServiceAccountRaw) {
throw new Error('GOOGLE_SHEETS_SERVICE_ACCOUNT is not set in .env')
}
const GoogleSheetsServiceAccount = JSON.parse(
GoogleSheetsServiceAccountRaw,
) as {
client_email: string
private_key: string
}

const jwtClient = new google.auth.JWT(
GoogleSheetsServiceAccount.client_email,
undefined,
GoogleSheetsServiceAccount.private_key,
['https://www.googleapis.com/auth/spreadsheets'],
)

return jwtClient
}