@geekmidas/storage

中文文档
9.6.1发布于 2026/11/16TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1.4万

一个全面,类型安全的存储客户端,用于云存储服务,支持多个供应商,以及版本和预签名的URL等高级功能.

中文使用文档
文档目录21 节
  1. 特征
  2. 安装
  3. 同伴依赖关系
  4. 快速启动
  5. AWS S3 导弹
  6. MinIO / 本地软件包
  7. API 参考
  8. 存储客户端接口
  9. 亚马逊Storage客户端
  10. 类型
  11. 高级使用
  12. 自定义 S3 客户端
  13. 访问控制列表
  14. 缓存
  15. 处理错误
  16. 发展
  17. 运行测试
  18. 地方发展与MINIO
  19. 项目结构
  20. 捐款
  21. 许可证

@geekmidas/仓库

一个全面,类型安全的存储客户端,用于云存储服务,支持多个供应商,以及版本和预签名的URL等高级功能.

特征

  • 多供应商支助: AWS S3, 有谷歌云存储和Azure Blob存储的可扩展接口
  • 类型安全: 包含全面类型定义的完整类型脚本支持
  • 已指定 URL: 生成安全上传和下载 URL而不暴露证书
  • 文件版本: 支持检索和管理文件版本
  • 直接上传: 直接上传文件到没有中间服务器的存储
  • 灵活配置: 支持自定义端点(用于 MinIO, LocalStack等)
  • 现代合成/等待 API: 整个基于承诺的界面
  • URL 缓存: 用于缓存预签名 URL 的内置支持以减少 API 调用并改进性能

安装

npm install @geekmidas/storage

同伴依赖关系

对于 AWS S3 支持,您需要安装 AWS SDK v3 包 :

npm install @aws-sdk/client-s3 @aws-sdk/s3-presigned-post @aws-sdk/s3-request-presigner

快速启动

AWS S3 导弹

import { AmazonStorageClient } from '@geekmidas/storage/aws';
import { InMemoryCache } from '@geekmidas/cache/memory';

// Create client with credentials
const storage = AmazonStorageClient.create({
  bucket: 'my-bucket',
  region: 'us-east-1',
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});

// Create client with caching enabled
const cache = new InMemoryCache<string>();
const storageWithCache = AmazonStorageClient.create({
  bucket: 'my-bucket',
  region: 'us-east-1',
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  cache,
});

// Upload a file directly
await storage.upload('documents/readme.txt', 'Hello, World!', 'text/plain');

// Generate a download URL
const downloadUrl = await storage.getDownloadURL({ 
  path: 'documents/readme.txt',
  name: 'README.txt' // Optional: sets Content-Disposition header
});

// Generate a presigned upload URL
const uploadUrl = await storage.getUploadURL({
  path: 'uploads/new-file.pdf',
  contentType: 'application/pdf',
  contentLength: 1024 * 1024, // 1MB
});

MinIO / 本地软件包

import { AmazonStorageClient } from '@geekmidas/storage/aws';

// For local development with MinIO
const storage = AmazonStorageClient.create({
  bucket: 'test-bucket',
  region: 'us-east-1',
  accessKeyId: 'minioadmin',
  secretAccessKey: 'minioadmin',
  endpoint: 'http://localhost:9000',
});

API 参考

存储客户端接口

所有存储提供者执行的核心接口 :

interface StorageClient {
  readonly provider: StorageProvider;
  readonly cache?: Cache<string>;
  
  // Direct upload
  upload(key: string, data: string | Buffer, contentType: string): Promise<void>;
  
  // Download URLs
  getDownloadURL(file: File, expiresIn?: number): Promise<string>;
  
  // Upload URLs
  getUploadURL(params: GetUploadParams, expiresIn?: number): Promise<string>;
  getUpload(params: GetUploadParams, expiresIn?: number): Promise<GetUploadResponse>;
  
  // Versioning
  getVersions(key: string): Promise<DocumentVersion[]>;
  getVersionDownloadURL(file: File, versionId: string): Promise<string>;
}

亚马逊Storage客户端

工厂方法

AmazonStorageClient.create(options: AmazonStorageClientCreateOptions)

选项 :

  • bucket (需要):S3桶名
  • region: AWS 区域( 默认: 使用 AWS SDK 默认)
  • accessKeyId: AWS 访问密钥 ID
  • secretAccessKey: AWS 秘密访问密钥
  • endpoint: 自定义 S3 端点(用于 MinIO, LocalStack)
  • acl: Canned ACL 用于上传(默认: authenticated-read(中文(简体) )
  • cache: 用于存储预签名的 URL 的可选缓存执行
  • forcePathStyle: 强制路径样式 URL(用于 MinIO)

方法

upload(key: string, data: string | Buffer, contentType: string): Promise<void>

将数据直接上传到存储中 .

// Upload text
await storage.upload('documents/hello.txt', 'Hello, World!', 'text/plain');

// Upload binary data
const buffer = Buffer.from('binary data');
await storage.upload('files/binary.dat', buffer, 'application/octet-stream');
getDownloadURL(file: File, expiresIn?: number): Promise<string>

生成一个预先签名的下载 URL 。 当缓存被配置时,会根据文件路径缓存 URL.

// Simple download URL
const url = await storage.getDownloadURL({ path: 'documents/file.pdf' });

// With custom filename in Content-Disposition
const url = await storage.getDownloadURL({ 
  path: 'documents/file.pdf',
  name: 'My Document.pdf'
});

// Custom expiration (in seconds)
const url = await storage.getDownloadURL({ path: 'documents/file.pdf' }, 3600);

缓存行为 :

  • URL以密钥格式缓存 : download-url:{file.path}
  • 缓存 TTL 设置为 expiresIn - 60 秒(带有1分缓冲)
  • 过期 < 60 秒的 URL 不缓存
  • 缓存的 URL 立即返回, 不生成新的预签 URL
getUploadURL(params: GetUploadParams, expiresIn?: number): Promise<string>

生成一个 PUT 上传 URL .

const uploadUrl = await storage.getUploadURL({
  path: 'uploads/new-file.pdf',
  contentType: 'application/pdf',
  contentLength: 1024 * 1024,
});

// Use the URL to upload
const response = await fetch(uploadUrl, {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/pdf',
    'Content-Length': '1048576',
  },
  body: fileData,
});
getUpload(params: GetUploadParams, expiresIn?: number): Promise<GetUploadResponse>

生成一个带有窗体字段的预签名 POST 上传 .

const upload = await storage.getUpload({
  path: 'uploads/form-upload.jpg',
  contentType: 'image/jpeg',
  contentLength: 500000,
});

// Use with HTML form
const formData = new FormData();
upload.fields.forEach(({ key, value }) => {
  formData.append(key, value);
});
formData.append('file', fileInput.files[0]);

const response = await fetch(upload.url, {
  method: 'POST',
  body: formData,
});
getVersions(key: string): Promise<DocumentVersion[]>

获取文件的所有版本( 需要 S3 版本) .

const versions = await storage.getVersions('documents/versioned-file.txt');
console.log(versions); // [{ id: 'version-1', createdAt: Date }, ...]
getVersionDownloadURL(file: File, versionId: string): Promise<string>

生成特定版本的下载 URL .

const url = await storage.getVersionDownloadURL(
  { path: 'documents/file.txt' },
  'version-12345'
);

类型

文件

interface File {
  path: string;
  name?: string; // Optional display name for Content-Disposition
}

获取上行程序

interface GetUploadParams {
  path: string;
  contentType: string;
  contentLength: number;
}

文档版本

interface DocumentVersion {
  id: string;
  createdAt: Date;
}

存储器

enum StorageProvider {
  AWSS3 = 'geekimdas.toolbox.storage.aws.s3',
  GCP = 'geekimdas.toolbox.storage.gcp',
  AZURE = 'geekimdas.toolbox.storage.azure',
}

高级使用

自定义 S3 客户端

import { S3Client } from '@aws-sdk/client-s3';
import { AmazonStorageClient, AmazonCannedAccessControlList } from '@geekmidas/storage/aws';
import { InMemoryCache } from '@geekmidas/cache/memory';

const s3Client = new S3Client({
  region: 'us-east-1',
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
});

// Without cache
const storage = new AmazonStorageClient(
  s3Client,
  'my-bucket',
  AmazonCannedAccessControlList.PublicRead
);

// With cache
const cache = new InMemoryCache<string>();
const storageWithCache = new AmazonStorageClient(
  s3Client,
  'my-bucket',
  AmazonCannedAccessControlList.PublicRead,
  cache
);

访问控制列表

import { AmazonCannedAccessControlList } from '@geekmidas/storage/aws';

const storage = AmazonStorageClient.create({
  bucket: 'my-bucket',
  acl: AmazonCannedAccessControlList.PublicRead, // Files will be publicly readable
});

可用的控制列表 :

  • Private - 所有人得到全能控制, 没有其他人可以进入
  • PublicRead - 所有人得到全控,其他人得到读取权限
  • PublicReadWrite - 所有者得到全控,其他人得到读取/写取
  • AuthenticatedRead - 所有者获得全控,认证用户获得阅读访问
  • BucketOwnerRead - 对象拥有者获得全控,桶拥有者获得读取权限
  • BucketOwnerFullControl - 物体和桶主得到全面的控制
  • LogDeliveryWrite - 寄出日志服务获得写入权限
  • AwsExecRead - Amazon EC2 读取 AMI 捆绑

缓存

缓存预签名的URL可以显著地减少API呼叫AWS S3的次数并改进性能.

import { AmazonStorageClient } from '@geekmidas/storage/aws';
import { InMemoryCache } from '@geekmidas/cache/memory';
import { UpstashCache } from '@geekmidas/cache/upstash';

// In-memory cache for development/testing
const memoryCache = new InMemoryCache<string>();
const storage = AmazonStorageClient.create({
  bucket: 'my-bucket',
  cache: memoryCache,
});

// Redis cache for production
const redisCache = new UpstashCache<string>({
  url: process.env.UPSTASH_REDIS_URL,
  token: process.env.UPSTASH_REDIS_TOKEN,
});
const productionStorage = AmazonStorageClient.create({
  bucket: 'my-bucket',
  cache: redisCache,
});

// Cache behavior example
const url1 = await storage.getDownloadURL({ path: 'file.pdf' }); // Generates new URL
const url2 = await storage.getDownloadURL({ path: 'file.pdf' }); // Returns cached URL
console.log(url1 === url2); // true

快取密钥和 TTL :

  • 下载 URL 以密钥缓存 : download-url:{path}
  • 缓存 TTL 自动计算为 expiresIn - 60 秒数
  • 60秒后到期的 URL 不缓存
  • 上传 URL 不缓存( 通常是单用)

处理错误

try {
  await storage.upload('documents/file.txt', 'content', 'text/plain');
} catch (error) {
  if (error.name === 'NoSuchBucket') {
    console.error('Bucket does not exist');
  } else if (error.name === 'AccessDenied') {
    console.error('Access denied');
  } else {
    console.error('Upload failed:', error);
  }
}

发展

运行测试

# Run all tests
npm test

# Run unit tests only
npm run test:unit

# Run integration tests only (requires MinIO)
npm run test:integration

# Run tests once
npm run test:once

地方发展与MINIO

  1. 使用 Docker 作曲启动 MiNIO :

    docker-compose up -d minio
    
  2. MinIO将在下列地点提供:

    • API:http://localhost:9000 (英语)
    • 控制台:http://localhost:9001
    • 全权证书:米诺阿明/米诺阿明
  3. 运行集成测试 :

    npm run test:integration
    

项目结构

src/
├── index.ts              # Main exports
├── aws.ts                # AWS-specific exports
├── StorageClient.ts      # Core interfaces and types
├── AmazonStorageClient.ts # AWS S3 implementation
└── __tests__/
    ├── StorageClient.spec.ts                    # Interface tests
    ├── AmazonStorageClient.spec.ts              # Unit tests
    └── AmazonStorageClient.integration.spec.ts  # Integration tests

捐款

  1. 遵循现有的代码样式(2个空格,单引号,分号)
  2. 添加新特性的综合测试
  3. 更新 API 更改的文档
  4. 使用“ 整合比单位” 测试哲学 - 倾向于真正的依赖性而不是模拟

许可证

麻省理工学院执照 - 详情见LICENSE文件.

版本与发布记录

@geekmidas/storage 共发布 206 个版本,首次发布于 2025/07/15;过去 12 个月发布了 201 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
9.6.1latest2026/11/16今天
10.0.0-alpha.185alpha2026/11/16今天
10.0.0-alpha.1842026/11/16今天
10.0.0-alpha.1832026/11/16今天
10.0.0-alpha.1822026/11/132 天前
10.0.0-alpha.1812026/11/133 天前

关于 @geekmidas/storage 的常见问题

@geekmidas/storage 是什么?

一个全面,类型安全的存储客户端,用于云存储服务,支持多个供应商,以及版本和预签名的URL等高级功能.

如何安装 @geekmidas/storage?

在项目目录运行 npm install @geekmidas/storage,或使用 pnpm add / yarn add / bun add。

@geekmidas/storage 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@geekmidas/storage 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@geekmidas/storage 可以商用吗?

@geekmidas/storage 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@geekmidas/storage 的下载量有多少?

根据 npm 官方下载统计,@geekmidas/storage 在 2026/10/16 – 2026/11/14 这 30 天内被下载 14,024 次,日均约 467 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@geekmidas/storage 还在维护吗?

最新版本 9.6.1 发布于 2026/11/16(今天);至今共发布 206 个版本,其中过去 12 个月发布了 201 个;首次发布于 2025/07/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。