0

I am trying to migrate data in storage from documents/docId/file.name to users/userId/documents/docId/file.name. Is it possible to copy folders like documents/docId without needing to define "file.name"?

My code currently only works when I provide the exact file name. It looks like this:

const updateStorageData = async () => {
  return admin
    .storage()
    .bucket()
    .file('documents/1/Screenshot 2023-05-09 at 00.33.45.png')
    .copy(
      admin
        .storage()
        .bucket()
        .file('users/testID/documents/1/Screenshot 2023-05-09 at 00.33.45.png'),
    );
};

I would like to try to copy all files in the folder without needing to provide the exact file name. Is this possible?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Mark James
  • 338
  • 4
  • 15
  • 43

2 Answers2

1

There no single API to copy all files in a folder, but you can list the files in a folder and then copy them one-by-one in a loop.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

You need to use the getFiles() and move() methods along the following lines:

const getFilesResponse = await admin
    .storage()
    .bucket()
    .getFiles();
const arrayOfFiles = getFilesResponse[0];

const promises = [];
arrayOfFiles.forEach(file => {
    // Check if the file needs to be moved based on its path (or metadata)
    if (fileToBeMoved) {
        promises.push(file.move('....png'))
    }
});

await Promise.all(promises)
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121