Refactor GoogleService: streamline token handling and improve comments

This commit is contained in:
MOHAN 2026-07-15 21:08:06 +05:30
parent 4a37d5befb
commit bfe489d920

View File

@ -1,6 +1,5 @@
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
import { google } from "googleapis";
import { Credentials } from "google-auth-library";
import { PrismaService } from "../prisma/prisma.service";
const SCOPES = [
@ -31,19 +30,18 @@ export class GoogleService {
const authUrl = client.generateAuthUrl({
access_type: "offline",
scope: SCOPES,
prompt: "consent",
state: userId,
prompt: "consent", // always request a refresh_token
state: userId, // passed back in callback to identify the user
});
return { authUrl };
}
async exchangeCode(userId: string, code: string) {
const client = this.createClient();
let tokens: Credentials;
let tokens: import("google-auth-library").Credentials;
try {
const { tokens: t } = await client.getToken(code);
tokens = t;
const result = await client.getToken(code);
tokens = result.tokens;
} catch {
throw new BadRequestException("Invalid or expired authorization code.");
}
@ -54,6 +52,7 @@ export class GoogleService {
);
}
// Fetch the Google account email
client.setCredentials(tokens);
const oauth2 = google.oauth2({ version: "v2", auth: client });
const { data } = await oauth2.userinfo.get();
@ -67,7 +66,7 @@ export class GoogleService {
accessToken: tokens.access_token ?? null,
isConnected: true,
connectedAt: new Date(),
spreadsheetId: null,
spreadsheetId: null, // reset so a new spreadsheet is created on next export
},
create: {
userId,