All files / libs/vendors/google-cloud/google-docs/src/lib google-docs.service.ts

99.43% Statements 353/355
94.59% Branches 35/37
100% Functions 11/11
99.43% Lines 353/355

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 3561x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 27x 27x 27x 27x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 1x 1x 1x 1x 1x     1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 3x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 5x 5x 1x 1x 1x 1x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 1x  
import { type Readable } from 'node:stream';
 
import { ForbiddenException, Injectable } from '@nestjs/common';
import { google, type docs_v1, type drive_v3 } from 'googleapis';
 
import { toError } from '@amalia/ext/typescript';
 
import {
  type GdocsCopyDocArgs,
  type GdocsCreateFolderArgs,
  type GdocsDeleteFileOrFolderArgs,
  type GdocsExportDocToPdfArgs,
  type GdocsFindFileIdByNameArgs,
  type GdocsFindFolderIdByNameArgs,
  type GdocsGetRawContentArgs,
  type GdocsReplaceTextsInDocumentArgs,
  type GdocsRetrieveFolderOrCreateItArgs,
  type GdocsStreamFileArgs,
} from './types';
 
export const GOOGLE_TIMEOUT_MILLISECONDS = 180_000;
 
@Injectable()
export class GoogleDocsService {
  private readonly gDocsService: docs_v1.Docs;
 
  private readonly gDriveService: drive_v3.Drive;
 
  public constructor() {
    this.gDocsService = google.docs({
      version: 'v1',
      timeout: GOOGLE_TIMEOUT_MILLISECONDS,
    });
    this.gDriveService = google.drive({
      version: 'v3',
      timeout: GOOGLE_TIMEOUT_MILLISECONDS,
    });
  }
 
  /**
   * Copy a Google Doc to a destination folder.
   *
   * @param copyArgs
   * @param options
   * @param options.currentAttempt - Current attempt number, used to increase the timeout
   * @returns the id of the created document
   */
  public async copyDocument(copyArgs: GdocsCopyDocArgs, { currentAttempt = 1 } = {}): Promise<string> {
    const { auth, destinationId, documentId, fileName } = copyArgs;
 
    try {
      const copyResponse = await this.gDriveService.files.copy(
        {
          auth,
          fileId: documentId,
          fields: 'id',
          requestBody: {
            parents: [destinationId],
            ...(fileName && {
              name: fileName,
            }),
          },
          supportsAllDrives: true,
        },
        {
          // Increase the timeout for each attempt
          timeout: currentAttempt * GOOGLE_TIMEOUT_MILLISECONDS,
        },
      );
 
      return copyResponse.data.id!;
    } catch (e: unknown) {
      const err = toError(e);
      err.message = `An error occurred while copying the document with id "${documentId}": ${err.message}`;
 
      // If gDrive don't have access to the document, it returns 404
      if (e && typeof e === 'object' && 'code' in e && e.code === 404) {
        throw new ForbiddenException(err);
      }
      throw err;
    }
  }
 
  /**
   * Create a Google Drive folder inside parent.
   *
   * @param createFolderArgs
   * @returns the id of the created folder
   */
  public async createFolder(createFolderArgs: GdocsCreateFolderArgs): Promise<string> {
    const { auth, destinationId, folderName } = createFolderArgs;
 
    try {
      const createdFolder = await this.gDriveService.files.create({
        auth,
        fields: 'id',
        requestBody: {
          name: folderName,
          parents: [destinationId],
          mimeType: 'application/vnd.google-apps.folder',
        },
        supportsAllDrives: true,
      });
      return createdFolder.data.id!;
    } catch (e) {
      const err = toError(e);
      err.message = `An error occurred while creating folder with name "${folderName}": ${err.message}`;
      throw err;
    }
  }
 
  /**
   * Search for a folder with the given name in the parent folder, if found return the id of the folder, else
   * create the folder and return the id of the newly created folder.
   *
   * @param searchFolderArgs
   * @returns The id of the folder if found or the id of the newly created folder
   */
  public async createFolderOrRetrieveIt(searchFolderArgs: GdocsRetrieveFolderOrCreateItArgs): Promise<string> {
    const { auth, folderName, parentFolderId } = searchFolderArgs;
 
    const folderId = await this.findFolderIdByName({
      auth,
      folderName,
      parentFolderId,
    });
 
    if (folderId) return folderId;
 
    return this.createFolder({
      auth,
      folderName,
      destinationId: parentFolderId,
    });
  }
 
  /**
   * Delete a Google Drive file or folder.
   *
   * If toTrash is true, the file or folder will be moved to the trash.
   * If toTrash is false, the file or folder will be permanently deleted.
   *
   * @param deleteFileOrFolderArgs
   */
  public async deleteFileOrFolder(deleteFileOrFolderArgs: GdocsDeleteFileOrFolderArgs): Promise<void> {
    const { auth, documentId, toTrash } = deleteFileOrFolderArgs;
    try {
      if (toTrash) {
        await this.gDriveService.files.update({
          auth,
          fileId: documentId,
          requestBody: {
            trashed: true,
          },
          supportsAllDrives: true,
        });
        return;
      }
 
      await this.gDriveService.files.delete({
        auth,
        fileId: documentId,
        supportsAllDrives: true,
      });
    } catch (e) {
      const err = toError(e);
      err.message = `An error occurred while deleting file or folder with id "${documentId}": ${err.message}`;
      throw err;
    }
  }
 
  /**
   * Export a Google Doc to PDF format and upload the PDF to the requested folder.
   *
   * @param exportArgs
   * @returns the id of the PDF document uploaded
   */
  public async exportDocToPdf(exportArgs: GdocsExportDocToPdfArgs): Promise<string> {
    const { auth, destinationId, documentId, fileName } = exportArgs;
 
    try {
      const exportResponse = await this.gDriveService.files.export(
        {
          auth,
          fileId: documentId,
          mimeType: 'application/pdf',
        },
        { responseType: 'stream' },
      );
 
      const uploadResponse = await this.gDriveService.files.create({
        auth,
        requestBody: {
          name: `${fileName}.pdf`,
          parents: [destinationId],
        },
        media: {
          mimeType: 'application/pdf',
          body: exportResponse.data,
        },
        fields: 'id',
        supportsAllDrives: true,
      });
 
      return uploadResponse.data.id!;
    } catch (e) {
      const err = toError(e);
      err.message = `An error occurred while exporting the document with id "${documentId}" to PDF: ${err.message}`;
      throw err;
    }
  }
 
  /**
   * Find the first fileId that matches the given name.
   *
   * @param findArgs
   * @returns the id of the find file or undefined if not found.
   */
  public async findFileIdByName(findArgs: GdocsFindFileIdByNameArgs): Promise<string | undefined> {
    const { auth, fileName, parentFolderId } = findArgs;
 
    try {
      const findResponse = await this.gDriveService.files.list({
        auth,
        q: `mimeType!='application/vnd.google-apps.folder' and name='${fileName}' and '${parentFolderId}' in parents and trashed=false`,
        fields: 'files(id)',
        supportsAllDrives: true,
        includeItemsFromAllDrives: true,
      });
 
      return findResponse.data.files![0]?.id || undefined;
    } catch (e) {
      const err = toError(e);
      err.message = `An error occurred while finding file with name "${fileName}": ${err.message}`;
      throw err;
    }
  }
 
  /**
   * Find the first folderId that matches the given name.
   *
   * @param findArgs
   * @returns the id of the find folder or undefined if not found.
   */
  public async findFolderIdByName(findArgs: GdocsFindFolderIdByNameArgs): Promise<string | undefined> {
    const { auth, folderName, parentFolderId } = findArgs;
 
    try {
      const findResponse = await this.gDriveService.files.list({
        auth,
        q: `mimeType='application/vnd.google-apps.folder' and name='${folderName}' and '${parentFolderId}' in parents and trashed=false`,
        fields: 'files(id)',
        supportsAllDrives: true,
        includeItemsFromAllDrives: true,
      });
 
      return findResponse.data.files![0]?.id || undefined;
    } catch (e) {
      const err = toError(e);
      err.message = `An error occurred while finding folder with name "${folderName}": ${err.message}`;
      throw err;
    }
  }
 
  /**
   * Replace text(s) inside a Google Doc.
   *
   * @param replaceArgs
   * @param options
   * @param options.currentAttempt - Current attempt number, used to increase the timeout
   */
  public async replaceTextsInDocument(
    replaceArgs: GdocsReplaceTextsInDocumentArgs,
    { currentAttempt = 1 } = {},
  ): Promise<void> {
    const { auth, documentId, replaces } = replaceArgs;
 
    if (!replaces.length) return;
 
    try {
      await this.gDocsService.documents.batchUpdate(
        {
          auth,
          documentId,
          requestBody: {
            requests: replaces.map(({ matchCase, textToReplace, replaceText }) => ({
              replaceAllText: {
                containsText: {
                  matchCase,
                  text: textToReplace,
                },
                replaceText,
              },
            })),
          },
        },
        {
          timeout: currentAttempt * GOOGLE_TIMEOUT_MILLISECONDS,
        },
      );
    } catch (e) {
      const err = toError(e);
      err.message = `An error occurred while replacing texts in document with id "${documentId}": ${err.message}`;
      throw err;
    }
  }
 
  /**
   * Get a stream from a PDF file.
   *
   * @param streamArgs
   * @returns a readable stream with the PDF content
   */
  public async streamPdfFile(streamArgs: GdocsStreamFileArgs): Promise<Readable> {
    const { auth, documentId } = streamArgs;
 
    try {
      const document = await this.gDriveService.files.get(
        {
          auth,
          fileId: documentId,
          alt: 'media',
        },
        { responseType: 'stream' },
      );
 
      return document.data;
    } catch (e) {
      const err = toError(e);
      err.message = `An error occurred while streaming PDF file with id "${documentId}": ${err.message}`;
      throw err;
    }
  }
 
  /**
   * Get raw document content.
   *
   * @param getRawArgs
   * @returns raw document content
   */
  public async getRawDocumentContent(getRawArgs: GdocsGetRawContentArgs): Promise<string> {
    try {
      const doc = await this.gDriveService.files.export({
        auth: getRawArgs.auth,
        fileId: getRawArgs.documentId,
        mimeType: 'text/plain',
      });
      return doc.data as string;
    } catch (e) {
      const err = toError(e);
      err.message = `An error occurred while fetching raw document with id "${getRawArgs.documentId}": ${err.message}`;
      throw err;
    }
  }
}