跳到内容

TypeScript Rust SDK

由于 RustFS 是一个完全兼容 S3 的对象存储系统,您可以通过包装 S3 TypeScript SDK 来构建适用于 RustFS 的 TypeScript SDK。通过该 SDK,您可以对 RustFS 进行操作,包括存储桶/对象的创建和删除、文件上传和下载等。

先决条件

RustFS TypeScript SDK 构建

使用 TypeScript 的 S3Client,通过 regionaccess_key_idsecret_access_keyendpoint_url 来构建 RustFS 客户端。

typescript
const rustfs_client = new S3Client({
    region: "cn-east-1",
    credentials: {
        accessKeyId: process.env.RUSTFS_ACCESS_KEY_ID!,
        secretAccessKey: process.env.RUSTFS_SECRET_ACCESS_KEY!,
    },
    endpoint: process.env.RUSTFS_ENDPOINT_URL!,
});

然后使用构建好的 rustfs_client 进行相应的操作。

创建存储桶

typescript
async function createBucket() {
    try {
        const response = await rustfs_client.send(new CreateBucketCommand({
            Bucket: "my-bucket",
        }));
        console.log(response);
    } catch (error) {
        console.log(error);
    }
}

删除存储桶

typescript
async function deleteBucket() {
    try {
        const response = await rustfs_client.send(new DeleteBucketCommand({
            Bucket: "my-bucket",
        }));
        console.log(response);
    } catch (error) {
        console.log(error);
    }
}

列出存储桶

typescript
async function listBuckets() {
    try {
        const response = await rustfs_client.send(new ListBucketsCommand({}));
        console.log(response);
    } catch (error) {
        console.log(error);
    }
}

列出对象

typescript
async function listObjects() {
    try {
        const response = await rustfs_client.send(new ListObjectsV2Command({
            Bucket: "rust-sdk-demo",
        }));
        console.log(response);
    } catch (error) {
        console.log(error);
    }
}

上传文件

typescript
async function uploadFile() {
    try {
        const response = await rustfs_client.send(new PutObjectCommand({
            Bucket: "my-bucket",
            Key: "/test/1.txt",
            Body: fs.createReadStream("/Users/jhma/Desktop/1.txt"),
        }));
    } catch (error) {
        console.log(error);
    }
}

下载对象

typescript
async function getObject() {
    try {
        const response = await rustfs_client.send(new GetObjectCommand({
            Bucket: "rust-sdk-demo",
            Key: "1.txt",
        }));

        // get object content
        if (response.Body) {
            const chunks: Buffer[] = [];
            for await (const chunk of response.Body as any) {
                chunks.push(chunk as Buffer);
            }
            const data = Buffer.concat(chunks).toString("utf-8");
            console.log("Object content:", data);
        }
    } catch (error) {
        console.log(error);
    }
}

其他用法可以自行探索,如果使用 Vibe Coding,会更加简单!

根据 Apache 许可证 2.0 发布。