Checking that an object exists in a bucket?

I'm trying to figure out what is the most efficient way to check for existence Object

in Bucket

the Google Cloud Store.

Here's what I'm doing now:

try
{
    final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
    if (md == null)
    {
        // do what I need to do here!
    }
}
catch (IOException e)
{
    L.error(e.getMessage());
}

      

As according to the documentation it returns null

if GcsFilename

doesn't exist.

...

/**
   * @param filename The name of the file that you wish to read the metadata of.
   * @return The metadata associated with the file, or null if the file does not exist.
   * @throws IOException If for any reason the file can't be read.
   */
  GcsFileMetadata getMetadata(GcsFilename filename) throws IOException;

      

Using .list()

on Bucket

and checking on .contains()

doesn't sound expensive, but clearly in its intent.

Personally, I think that testing to null

check if something exists is inelegant and not as straightforward as it is GCS_SERVICE.objectExists(fileName);

, but I suppose I don't need to design the GCS Client API. I am just creating a method for this test in my API.

Is there a more efficient (as in time) or more self-contained way of documenting this test?

+3


source to share


2 answers


Decision

Here is a working solution that I ended up with:



@Nonnull
protected Class<T> getEntityType() { (Class<T>) new TypeToken<T>(getClass()) {}.getRawType(); }

/**
 * purge ObjectMetadata records that don't have matching Objects in the GCS anymore.
 */
public void purgeOrphans()
{
    ofy().transact(new Work<VoidWork>()
    {
        @Override
        public VoidWork run()
        {
            try
            {
                for (final T bm : ofy().load().type(ObjectMetadataEntityService.this.getEntityType()).iterable())
                {
                    final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
                    if (md == null)
                    {
                        ofy().delete().entity(bm);
                    }
                }
            }
            catch (IOException e)
            {
                L.error(e.getMessage());
            }
            return null;
        }
    });
}

      

+1


source


They added a method file.exists()

.



const fileExists = _=>{
    return file.exists().then((data)=>{ console.log(data[0]); });
}

fileExists();
//logs a boolean to the console;
//true if the file exists;
//false if the file doesn't exist.

      

0


source







All Articles