Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add listBuckets method #38

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from "./src/client.ts";
export * from "./src/bucket.ts";
export type {
Bucket,
CommonPrefix,
CopyDirective,
CopyObjectOptions,
Expand All @@ -13,10 +14,12 @@ export type {
GetObjectResponse,
HeadObjectResponse,
ListAllObjectsOptions,
ListBucketsResponse,
ListObjectsOptions,
ListObjectsResponse,
LocationConstraint,
LockMode,
Owner,
PutObjectOptions,
PutObjectResponse,
ReplicationStatus,
Expand Down
50 changes: 4 additions & 46 deletions src/bucket.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
AWSSignerV4,
decodeXMLEntities,
parseXML,
pooledMap,
} from "../deps.ts";
import { AWSSignerV4, parseXML, pooledMap } from "../deps.ts";
import type { S3Config } from "./client.ts";
import type {
CommonPrefix,
Expand All @@ -27,6 +22,8 @@ import { S3Error } from "./error.ts";
import type { Signer } from "../deps.ts";
import { doRequest, encodeURIS3 } from "./request.ts";
import type { Params } from "./request.ts";
import type { Document } from "./xml.ts";
import { extractContent, extractField, extractRoot } from "./xml.ts";

export interface S3BucketConfig extends S3Config {
bucket: string;
Expand Down Expand Up @@ -329,9 +326,7 @@ export class S3Bucket {
}

const parsed = {
isTruncated: extractContent(root, "IsTruncated") === "true"
? true
: false,
isTruncated: extractContent(root, "IsTruncated") === "true",
contents: root.children
.filter((node) => node.name === "Contents")
.map<S3Object>((s3obj) => {
Expand Down Expand Up @@ -624,40 +619,3 @@ export class S3Bucket {
return deleted;
}
}

interface Document {
declaration: {
attributes: Record<string, unknown>;
};
root: Xml | undefined;
}

interface Xml {
name: string;
attributes: unknown;
children: Xml[];
content?: string;
}

function extractRoot(doc: Document, name: string): Xml {
if (!doc.root || doc.root.name !== name) {
throw new S3Error(
`Malformed XML document. Missing ${name} field.`,
JSON.stringify(doc, undefined, 2),
);
}
return doc.root;
}

function extractField(node: Xml, name: string): Xml | undefined {
return node.children.find((node) => node.name === name);
}

function extractContent(node: Xml, name: string): string | undefined {
const field = extractField(node, name);
const content = field?.content;
if (content === undefined) {
return content;
}
return decodeXMLEntities(content);
}
52 changes: 50 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { AWSSignerV4 } from "../deps.ts";
import type { CreateBucketOptions } from "./types.ts";
import { AWSSignerV4, parseXML } from "../deps.ts";
import type { CreateBucketOptions, ListBucketsResponse } from "./types.ts";
import { S3Error } from "./error.ts";
import { S3Bucket } from "./bucket.ts";
import { doRequest, encoder } from "./request.ts";
import type { Params } from "./request.ts";
import {
extractContent,
extractField,
extractFields,
extractRoot,
} from "./xml.ts";
import type { Document } from "./xml.ts";

export interface S3Config {
region: string;
Expand Down Expand Up @@ -121,4 +128,45 @@ export class S3 {

return this.getBucket(bucket);
}

/** Returns a list of all buckets owned by the authenticated sender of the request. */
async listBuckets(): Promise<ListBucketsResponse> {
const resp = await doRequest({
host: this.#host,
signer: this.#signer,
method: "GET",
});

if (resp.status !== 200) {
throw new S3Error(
`Failed to list buckets": ${resp.status} ${resp.statusText}`,
await resp.text(),
);
}

const xml = await resp.text();
return this.#parseListBucketsResponseXml(xml);
}

#parseListBucketsResponseXml(x: string): ListBucketsResponse {
const doc: Document = parseXML(x);
const root = extractRoot(doc, "ListAllMyBucketsResult");
const buckets = extractField(root, "Buckets")!;
const owner = extractField(root, "Owner")!;

return {
buckets: extractFields(buckets, "Bucket")
.map((bucket) => {
const creationDate = extractContent(bucket, "CreationDate");
return {
name: extractContent(bucket, "Name"),
creationDate: creationDate ? new Date(creationDate) : undefined,
};
}),
owner: {
id: extractContent(owner, "ID"),
displayName: extractContent(owner, "DisplayName"),
},
};
}
}
18 changes: 16 additions & 2 deletions src/client_test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assertEquals, assertThrowsAsync } from "../test_deps.ts";
import { assert, assertEquals, assertRejects } from "../test_deps.ts";
import { S3Error } from "./error.ts";
import { S3 } from "./client.ts";
import { encoder } from "./request.ts";
Expand Down Expand Up @@ -39,7 +39,7 @@ Deno.test({
const body = await new Response(resp?.body).text();
assertEquals(body, "test");

await assertThrowsAsync(
await assertRejects(
() => s3.createBucket("create-bucket-test"),
S3Error,
'Failed to create bucket "create-bucket-test": 409 Conflict',
Expand All @@ -50,3 +50,17 @@ Deno.test({
// @TODO: delete also bucket once s3.deleteBucket is implemented.
},
});

Deno.test({
name: "[client] should list all buckets",
async fn() {
const { buckets, owner } = await s3.listBuckets();
assert(buckets.length, "no buckets available");
assertEquals(buckets[0].name, "test");
assert(
buckets[0].creationDate instanceof Date,
"creationDate is not of type Date",
);
assertEquals(owner.displayName, "minio");
},
});
24 changes: 24 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -604,3 +604,27 @@ export interface CreateBucketOptions extends CreateBucketConfiguration {
/** Allows grantee to write the ACL for the applicable bucket. */
grantWriteAcp?: string;
}

export interface Bucket {
/**
* Date the bucket was created. This date can change when making changes to
* your bucket, such as editing its bucket policy.
*/
creationDate?: Date;
/** The name of the bucket. */
name?: string;
}

export interface Owner {
/** Container for the display name of the owner. */
displayName?: string;
/** Container for the ID of the owner. */
id?: string;
}

export interface ListBucketsResponse {
/** The list of buckets owned by the requestor. */
buckets: Array<Bucket>;
/** The owner of the buckets listed. */
owner: Owner;
}
43 changes: 43 additions & 0 deletions src/xml.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { S3Error } from "./error.ts";
import { decodeXMLEntities } from "../deps.ts";

export interface Document {
declaration: {
attributes: Record<string, unknown>;
};
root: Xml | undefined;
}

export interface Xml {
name: string;
attributes: unknown;
children: Xml[];
content?: string;
}

export function extractRoot(doc: Document, name: string): Xml {
if (!doc.root || doc.root.name !== name) {
throw new S3Error(
`Malformed XML document. Missing ${name} field.`,
JSON.stringify(doc, undefined, 2),
);
}
return doc.root;
}

export function extractField(node: Xml, name: string): Xml | undefined {
return node.children.find((node) => node.name === name);
}

export function extractFields(node: Xml, name: string): Array<Xml> {
return node.children.filter((node) => node.name === name);
}

export function extractContent(node: Xml, name: string): string | undefined {
const field = extractField(node, name);
const content = field?.content;
if (content === undefined) {
return content;
}
return decodeXMLEntities(content);
}
2 changes: 1 addition & 1 deletion test_deps.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export {
assert,
assertEquals,
assertThrowsAsync,
assertRejects,
} from "https://deno.land/[email protected]/testing/asserts.ts";