Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | import {
GetObjectCommand,
HeadObjectCommand,
NoSuchKey,
PutObjectCommand,
S3Client,
} from "@aws-sdk/client-s3";
function isNotFoundError(error: unknown): boolean {
if (error instanceof NoSuchKey) {
return true;
}
const statusCode = (error as { $metadata?: { httpStatusCode?: number } })?.$metadata
?.httpStatusCode;
const errorName = (error as { name?: string })?.name;
return statusCode === 404 || errorName === "NotFound" || errorName === "NoSuchKey";
}
export async function getObjectText({
client,
bucket,
key,
}: {
client: S3Client;
bucket: string;
key: string;
}): Promise<string | undefined> {
try {
const response = await client.send(
new GetObjectCommand({
Bucket: bucket,
Key: key,
}),
);
if (!response.Body) {
return undefined;
}
return await response.Body.transformToString();
} catch (error) {
if (isNotFoundError(error)) {
return undefined;
}
throw error;
}
}
export async function getJsonObject<T>({
client,
bucket,
key,
}: {
client: S3Client;
bucket: string;
key: string;
}): Promise<T | undefined> {
const value = await getObjectText({ client, bucket, key });
if (!value) {
return undefined;
}
return JSON.parse(value) as T;
}
export async function putJsonObject({
client,
bucket,
key,
body,
}: {
client: S3Client;
bucket: string;
key: string;
body: unknown;
}): Promise<void> {
await client.send(
new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: JSON.stringify(body),
ContentType: "application/json",
}),
);
}
export async function objectExists({
client,
bucket,
key,
}: {
client: S3Client;
bucket: string;
key: string;
}): Promise<boolean> {
try {
await client.send(
new HeadObjectCommand({
Bucket: bucket,
Key: key,
}),
);
return true;
} catch (error) {
if (isNotFoundError(error)) {
return false;
}
throw error;
}
}
|