import * as wmill from "windmill-client"
import { S3Object } from "windmill-client"
/**
* Update File
* Rename a file, change its description, and/or replace its content with a file from Windmill object storage (a new revision; any size, resumable upload). Leave a field empty to keep it unchanged. Google Docs/Sheets/Slides can't take raw content; replace those by uploading a new file.
*/
export async function main(
auth: RT.Gdrive,
file_id: string,
name: string | undefined,
description: string | undefined,
file: S3Object | undefined,
mime_type: string | undefined
) {
const metadata: { [key: string]: any } = {}
if (name) metadata.name = name
if (description) metadata.description = description
const headers = { Authorization: `Bearer ${auth.token}` }
if (!file?.s3) {
const url = new URL(`https://www.googleapis.com/drive/v3/files/${file_id}`)
url.searchParams.append("supportsAllDrives", "true")
url.searchParams.append("fields", "*")
const response = await fetch(url, {
method: "PATCH",
headers: {
...headers,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(metadata),
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return await response.json()
}
const bytes = await wmill.loadS3File(file)
if (!bytes) {
throw new Error("Could not load the file from object storage")
}
// 1. Open a resumable session carrying the metadata changes
const url = new URL(
`https://www.googleapis.com/upload/drive/v3/files/${file_id}`
)
url.searchParams.append("uploadType", "resumable")
url.searchParams.append("supportsAllDrives", "true")
url.searchParams.append("fields", "*")
const session = await fetch(url, {
method: "PATCH",
headers: {
...headers,
"Content-Type": "application/json; charset=UTF-8",
...(mime_type ? { "X-Upload-Content-Type": mime_type } : {}),
},
body: JSON.stringify(metadata),
})
if (!session.ok) {
throw new Error(`${session.status} ${await session.text()}`)
}
// 2. Send the new bytes to the session URI
const response = await fetch(session.headers.get("Location")!, {
method: "PUT",
headers: {
...headers,
...(mime_type ? { "Content-Type": mime_type } : {}),
},
body: bytes,
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return await response.json()
}
Submitted by hugo989 2 hours ago