import * as fs from "fs" ; import * as path from "path" ; import { AuthClientBase } from "./AuthClientBase" ; import { File } from "./File" ; import { Query } from "./Query" ; import { ICreateFolderOptions , ITsGoogleDriveOptions , IUpdateMetaOptions } from "./types" ; export const GOOGLE_DRIVE_API = "https://www.googleapis.com/drive/v3" ; export const GOOGLE_DRIVE_UPLOAD_API = "https://www.googleapis.com/upload/drive/v3/files" ; export const FIELDS = "id,kind,name,mimeType,parents,modifiedTime,createdTime,size" ; export class TsGoogleDrive extends AuthClientBase { constructor ( options ) { super ( options ) ; } public query ( ) { return new Query ( this . options ) ; } public async getFile ( id ) { const client = await this . _getClient ( ) ; const url = `/files/${ id }` ; const params = { fields : FIELDS } ; try { const res = await client . request ( { baseURL : GOOGLE_DRIVE_API , url , params } ) ; const file = new File ( client ) ; Object . assign ( file , res . data ) ; return file ; } catch ( err ) { if ( typeof err === "object" && ( err as any ) ?. code === 404 ) { return undefined ; } throw err ; } } public async createFolder ( options = { } ) { const client = await this . _getClient ( ) ; const url = `/files` ; const params = { fields : FIELDS } ; const data = { mimeType : "application/vnd.google-apps.folder" , name : options . name , description : options . description } ; if ( options . parent ) { data . parents = [ options . parent ] ; } const res = await client . request ( { baseURL : GOOGLE_DRIVE_API , url , params , data , method : "POST" } ) ; const file = new File ( client ) ; Object . assign ( file , res . data ) ; return file ; } public async upload ( filename , options = { } ) { const client = await this . _getClient ( ) ; const params = { uploadType : "media" , fields : FIELDS } ; const buffer = fs . readFileSync ( filename ) ; const res = await client . request ( { url : GOOGLE_DRIVE_UPLOAD_API , method : "POST" , params , body : buffer } ) ; const file = new File ( client ) ; Object . assign ( file , res . data ) ; if ( ! options . name ) { options . name = path . basename ( filename ) ; } await file . update ( options ) ; return file ; } public async emptyTrash ( ) { const client = await this . _getClient ( ) ; const url = `/files/trash` ; const params = { } ; const res = await client . request ( { baseURL : GOOGLE_DRIVE_API , url , method : "DELETE" , params } ) ; return true ; } }