zync-nest-library
Version:
NestJS library with database backup and file upload utilities
84 lines (70 loc) • 2.44 kB
text/typescript
import { IDriveFileQuery } from "./google.interface";
import { google } from "googleapis";
import axios from "axios";
const rootFolder = process.cwd();
export class GoogleApiService {
private authClient: any;
private credentials = require(`${rootFolder}/credentials.json`);
constructor() {
this.setClient();
}
private setClient(tokens?: string) {
this.authClient = new google.auth.OAuth2(
this.credentials.installed.client_id,
this.credentials.installed.client_secret,
this.credentials.installed.redirect_uris[0]
);
this.authClient.setCredentials({ access_token: tokens });
}
public getAuthUrl() {
// Set the desired scope for accessing Drive API
const scope = ["https://www.googleapis.com/auth/drive.readonly"];
// Generate an authentication URL and prompt the user to visit it
return this.authClient.generateAuthUrl({
access_type: "offline",
scope: scope,
});
}
public async getAuthToken(code: string) {
const { tokens } = await this.authClient.getToken(code);
this.authClient.setCredentials(tokens);
return tokens;
}
public async getFolders(query: IDriveFileQuery): Promise<any> {
try {
this.setClient(query.accessToken);
const drive = google.drive({ version: "v3", auth: this.authClient });
const response = await drive.files.list({
q: `'${query.folderId}' in parents and mimeType = 'application/vnd.google-apps.folder'`,
fields: "files(id, name)",
pageSize: query.pageSize || 1000,
});
return response?.data?.files;
} catch (error) {
console.error("Error querying files:", error.message);
throw error;
}
}
public async downloadFiles(folderId: string, token: string) {
this.setClient(token);
const drive = google.drive({ version: "v3", auth: this.authClient });
const { data } = await drive.files.list({
q: `'${folderId}' in parents and mimeType contains 'image/'`,
fields: "files(id, name)",
});
const files = [];
for await (const file of data.files) {
const response = await axios.get(
`https://www.googleapis.com/drive/v3/files/${file.id}?alt=media`,
{
responseType: "stream",
headers: {
Authorization: `Bearer ${this.authClient.credentials.access_token}`,
},
}
);
files.push(response);
}
return files;
}
}