Last active
October 19, 2022 13:25
-
-
Save Charlesmendez/ddeac6f7f7521dc879d3a0c65e9b3b8f to your computer and use it in GitHub Desktop.
Typescript script to copy a file in a bucket and pastes it in another path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {QueryDocumentSnapshot} from "@google-cloud/firestore"; | |
import * as functions from "firebase-functions"; | |
import {EventContext} from "firebase-functions"; | |
import {Storage} from "@google-cloud/storage"; | |
export const shareToAnotherGraph = async (snap: QueryDocumentSnapshot, _context: EventContext, db: FirebaseFirestore.Firestore) => { | |
const data = snap.data(); | |
// The ID of your GCP project | |
const projectId = "example"; | |
// The ID of the bucket the original object is in | |
const sourceBucket = "example.appspot.com"; | |
// The ID of the GCS object to copy | |
const sourceFile = data.sourcePath; | |
functions.logger.log("sourceFile: ", sourceFile); | |
// The ID of the bucket to copy the object to | |
const destinationBucket = "example.appspot.com"; | |
// get the name of the file to copy | |
const sourceFileString = String(snap.data().sourcePathString); | |
const sourceFileSegments = sourceFileString.split("/"); | |
const sourceFileName = String(sourceFileSegments[sourceFileSegments.length - 1]); | |
functions.logger.log("sourceFileName: ", sourceFileName); | |
// get the last item after the / of the destination path | |
const destinationPath = String(snap.data().destinationPathString); | |
const destinationPathSegments = destinationPath.split("/"); | |
const destinationPathName = String(destinationPathSegments[destinationPathSegments.length - 1]); | |
functions.logger.log("destinationPathName: ", destinationPathName); | |
const storage = new Storage({ | |
projectId: projectId, | |
}); | |
const [Files] = await storage.bucket(sourceBucket).getFiles({ | |
prefix: sourceFile, | |
}); | |
// create a regex to use the replace function | |
const regex = new RegExp(sourceFileName, "g"); | |
for (const file of Files) { | |
const fileName = file.name; | |
if (fileName.includes(sourceFileName)) { | |
const destination = storage.bucket(destinationBucket).file(fileName.replace(regex, destinationPathName)); | |
functions.logger.log("Destination file.name: ", file.name); | |
await file.copy(destination); | |
} | |
} | |
return; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment