Skip to content

Commit

Permalink
feat(bin): object storage find method
Browse files Browse the repository at this point in the history
  • Loading branch information
sg-gs committed Jan 4, 2024
1 parent 3a9ac11 commit e9c4bef
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions bin/delete-objects/ObjectStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface StorageObject {

export interface ObjectStorageReader {
listObjects(pageSize: number): AsyncGenerator<StorageObject>;
find(key: string): Promise<StorageObject | null>;
}

/**
Expand Down Expand Up @@ -51,6 +52,22 @@ export class FileListObjectStorageReader implements ObjectStorageReader {
yield { Key, Size: parseInt(Size), LastModified: new Date() };
}
}

async find(key: string): Promise<StorageObject | null> {
const fileStream = createReadStream(this.filename);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity // To recognize '\n' as a line delimiter
});

for await (const line of rl) {
const [Size, Key] = line.split(' ');
if (Key === key) {
return { Key, Size: parseInt(Size), LastModified: new Date() };
}
}
return null;
}
}

export class S3ObjectStorageReader implements ObjectStorageReader {
Expand Down Expand Up @@ -92,5 +109,25 @@ export class S3ObjectStorageReader implements ObjectStorageReader {
lastPointer = response.NextContinuationToken;
} while (lastPointer);
}

async find(key: string): Promise<StorageObject | null> {
try {
const response = await this.s3.headObject({
Bucket: this.bucket,
Key: key,
}).promise();

return {
Key: key,
Size: response.ContentLength ?? 0,
LastModified: response.LastModified ?? new Date(),
};
} catch (error) {
if ((error as { code: string }).code === 'NotFound') {
return null;
}
throw error;
}
}
}

0 comments on commit e9c4bef

Please sign in to comment.