v5 から v6 への移行
このガイドは、Amplify JavaScript v5 の Storage API を新しい v6 の Storage API に移行するのに役立ちます。
削除されたオプション
以下の入力オプションは v6 の Storage API から削除されました:
provider: カスタムプロバイダーは v6 ではサポートされなくなりました。以下のすべての v5 の例では、デフォルトの S3 プロバイダーで想定される入出力値を使用しています。customPrefix: Storage Config にプレフィックスリゾルバーを追加して、accessLevel ごとにキープレフィックスをカスタマイズできます。移行の詳細についてはカスタムプレフィックスの使用を参照してください。track: Pinpoint での Storage イベントの自動トラッキングは V6 で削除されました。Storage イベントはAnalytics カテゴリを使用してトラッキングできます。移行の詳細についてはストレージイベントのトラッキングを参照してください。ServerSideEncryption、SSECustomerAlgorithm、SSECustomerKey、SSECustomerKeyMD5、およびSSEKMSKeyId: これらのオプションは廃止予定です。サーバー側の暗号化は 2023 年 1 月以来 S3 によってデフォルトキーを使用して自動的に適用されています。cacheControl: このオプションは削除され、実行時によって構成された HTTP キャッシング動作に従うようになりました。
bucket:bucketはAmplify.configure()の一部であるStorage設定オブジェクトに必須であるため、入力オプションから削除されました。
注意: v6 ではすべての大文字の入出力キーを「camelCase」に変更しました。
非推奨のオプション
バージョン 6.2.0 以降、以下の API パラメータと出力オプションは非推奨としてマークされており、将来のバージョンで削除される可能性があります。
-
key: 新しいpathパラメータが導入され、入出力オプションのkeyパラメータの代わりに使用されます。pathパラメータはユーザーのアイデンティティ ID に基づく柔軟なパス構築を可能にします。 -
accessLevel:public、protected、およびprivateのスコープ付きアクセス許可を持つファイルaccessLevelは廃止予定です。代わりに、Amplify (Gen2)はより洗練されたアクセス制御メカニズムを導入しています。クライアントに同様の柔軟性を提供するために、入力オプションのpathパラメータを利用します。
Storage.put
Storage.put API は v6 で uploadData に名前が変更されました。v5 から v6 への体験にはいくつかの変更があります。上記に記載されているもの以外にも:
ACLオプションを削除しました: S3 バケット ACL は Amplify で現在サポートされていない追加的なアクセス制御オプションを提供します。ACL は S3 セキュリティのベストプラクティスに従ってはもう推奨されていません。Expiresオプションは廃止予定です。resumableオプションは v6 のconfigから削除されました。v6 ではすべてのアップロードタスクがデフォルトで再開可能です。pause、resume、およびcancel関数はuploadDataの戻り値で見つけることができます。詳細は v6 Storage ドキュメントを参照してください。- アップロードおよびダウンロード操作の
progressCallbackオプションは v6 でonProgressに置き換わりました。関数入力プロパティ名のloadedとtotalは now map totransferredBytesとtotalBytesにマップされます。
入力
V5
// AWSS3 (デフォルト) プロバイダーkey: stringobject: { ACL?: string; // V6 で削除 CacheControl?: string; // V6 で削除 ContentDisposition? string; ContentEncoding?: string; ContentMD5?: string; ContentType?: string; Expires?: Date; // V6 で削除 Metadata?: Record<string, string>; ServerSideEncryption?: string; // V6 で削除 SSECustomerAlgorithm?: string; // V6 で削除 SSECustomerKey?: string; // V6 で削除 SSECustomerKeyMD5?: string; // V6 で削除 SSEKMSKeyId?: string; // V6 で削除 Bucket: string; Key: string; Body?: string | ReadableStream<any> | Blob | Uint8Array | Buffer; Tagging?: string; // V6 で削除}// 非再開可能設定config?: { level?: 'public' | 'protected' | 'private'; provider?: string; // V6 で削除 customPrefix?: { // V6 で削除 private?: string; public?: string; protected?: string; }; track?: boolean; // V6 で削除 progressCallback?: (progress: any) => any; serverSideEncryption?: string; // V6 で削除 SSECustomerAlgorithm?: string; // V6 で削除 SSECustomerKey?: string; // V6 で削除 SSECustomerKeyMD5?: string; // V6 で削除 SSEKMSKeyId?: string; // V6 で削除 acl?: string; // V6 で削除 bucket?: string; cacheControl?: string; // V6 で削除 contentDisposition?: string; contentEncoding?: string; contentType?: string; expires?: Date; metadata?: Record<string, string>; tagging?: string; // V6 で削除 useAccelerateEndpoint?: boolean; resumable?: boolean; // v6 では必須ではありません: すべての put 操作は再開可能です}// 再開可能設定config?: { // 上記の標準設定をすべて含む progressCallback?: (progress: { loaded: number; total: number; }) => any; // 上記の progressCallback より具体的 completeCallback?: (event: { key?: string }) => any; errorCallback?: (err: any) => any;}V6
input: { path: string | ({identityId}: {identityId: string}) => string; data: string | Blob | ArrayBufferView | ArrayBuffer; options?: { useAccelerateEndpoint?: boolean; onProgress?: (event: { transferredBytes: number; totalBytes?: number; }) => void; contentDisposition?: string; contentEncoding?: string; contentType?: string; metadata?: Record<string, string>; };}出力
V5
// 再開可能StoragePutOutput { resume(): any; pause(): any; percent: number; isInProgress: boolean;}
// 非再開可能StoragePutOutput { key: string;};V6
UploadDataOutput { cancel: (message?: string) => void; pause: () => void; resume: () => void; readonly state: | 'IN_PROGRESS' | 'PAUSED' | 'CANCELED' | 'SUCCESS' | 'ERROR'; result: Promise<Item>;}
Item { path: string; lastModified?: Date; size?: number; eTag?: string; metadata?: Record<string, string>; versionId?: string; contentType?: string;}import { uploadData } from 'aws-amplify/storage';
const handleUpload = async (path: string, data: string | Blob) => { const operation = uploadData({ path, data });
const result = await operation.result;}import { Storage } from 'aws-amplify';
const handleUpload = async (key: string, data: string | Blob) => { // アクセスレベル `public` でファイルをアップロード const result = await Storage.put(key, data, { level: 'public', });}アップロード進度の監視
progressCallback オプションは v6 で onProgress に置き換わりました。関数入力プロパティ名の loaded と total は transferredBytes と totalBytes にマップされます。
import { uploadData } from 'aws-amplify/storage';
const handleUpload = async (path: string, data: string | Blob) => { const operation = uploadData({ path, data, options: { onProgress: ({ transferredBytes, totalBytes }) => { // 進度の実装 } } });
const result = await operation.result;}import { Storage } from 'aws-amplify';
const handleUpload = async (key: string, data: string | Blob) => { // アクセスレベル `public` でファイルをアップロード const result = await Storage.put(key, data, { level: 'public', progressCallback: ({ loaded, total }) => { // 進度の実装 } });}Storage.get
Storage.get API は v6 で 2 つの API getURL と downloadData に分離されました。v5 から v6 への体験にはいくつかの変更があります。上記に記載されているもの以外にも:
- コンテンツオプション (
contentDisposition、contentLanguage、contentEncoding、およびcontentType) は、これらの値がアップロードされたファイルで既に提供されているため、getAPI ではサポートされなくなりました。 - v5 で AWS SDK から継承された次の応答キーは v6 の API 出力から削除されました:
- DeleteMarker
- AcceptRanges
- Expiration
- Restore
- ChecksumXXX
- MissingMeta
- VersionId
- ContentRange
- Expires
- WebsiteRedirectLocation
- BucketKeyEnabled
- StorageClass
- RequestCharged
- ReplicationStatus
- PartsCount
- TagCount
- ObjectLockMode
- ObjectLockRetainUntilDate
- ObjectLockLegalHoldStatus
- アップロードおよびダウンロード操作の
progressCallbackオプションは v6 でonProgressに置き換わりました。関数入力プロパティ名のloadedとtotalはtransferredBytesとtotalBytesにマップされます。
入力
V5
// デフォルト S3 プロバイダーを想定key: stringoptions: { level?: 'public' | 'protected' | 'private'; provider?: 'AWSS3'; customPrefix?: { // V6 で削除 private?: string; public?: string; protected?: string; }; track?: boolean; // V6 で削除 download?: boolean; // V6 で削除 expires?: number; identityId?: string; progressCallback?: (progress: any) => any; cacheControl?: string; // V6 で削除 contentDisposition?: string; // V6 で削除 contentEncoding?: string; // V6 で削除 contentLanguage?: string; // V6 で削除 contentType?: string; // V6 で削除 SSECustomerAlgorithm?: string; // V6 で削除 SSECustomerKey?: string; // V6 で削除 SSECustomerKeyMD5?: string; // V6 で削除 validateObjectExistence?: boolean;};V6
// getUrl{ path: string | ({identityId}: {identityId: string}) => string; options?: { useAccelerateEndpoint?: boolean; };}// downloadDatainput: { path: string | ({identityId}: {identityId: string}) => string; options?: { useAccelerateEndpoint?: boolean; onProgress?: (event: { transferredBytes: number; totalBytes?: number; }) => void; bytesRange?: { start: number; end: number; }; };}出力
V5
// download: falsestring // 署名付き URL
// download: trueS3ProviderGetOutput { Body?: Blob; DeleteMarker?: boolean; // V6 で削除 AcceptRanges?: string; // V6 で削除 Expiration?: string; // V6 で削除 Restore?: string; // V6 で削除 LastModified?: Date; ContentLength?: number; ETag?: string; ChecksumCRC32?: string; // V6 で削除 ChecksumCRC32C?: string; // V6 で削除 ChecksumSHA1?: string; // V6 で削除 ChecksumSHA256?: string; // V6 で削除 MissingMeta?: number; // V6 で削除 VersionId?: string; // V6 で削除 CacheControl?: string; // V6 で削除 ContentDisposition?: string; // V6 で削除 ContentEncoding?: string; // V6 で削除 ContentLanguage?: string; // V6 で削除 ContentRange?: string; // V6 で削除 ContentType?: string; Expires?: Date; // V6 で削除 WebsiteRedirectLocation?: string; // V6 で削除 ServerSideEncryption?: ServerSideEncryption | string; // V6 で削除 Metadata?: Record<string, string>; SSECustomerAlgorithm?: string; // V6 で削除 SSECustomerKeyMD5?: string; // V6 で削除 SSEKMSKeyId?: string; // V6 で削除 BucketKeyEnabled?: boolean; // V6 で削除 StorageClass?: StorageClass | string; // V6 で削除 RequestCharged?: RequestCharged | string; // V6 で削除 ReplicationStatus?: ReplicationStatus | string; // V6 で削除 PartsCount?: number; // V6 で削除 TagCount?: number; // V6 で削除 ObjectLockMode?: ObjectLockMode | string; // V6 で削除 ObjectLockRetainUntilDate?: Date; // V6 で削除 ObjectLockLegalHoldStatus?: ObjectLockLegalHoldStatus | string; // V6 で削除 $metadata: { // V6 で削除 httpStatusCode?: number; requestId?: string }}V6
// getUrlGetUrlOutput { url: URL; expiresAt: Date;}// downloadDataDownloadDataOutput { cancel: (message?: string) => void; readonly state: TransferTaskState; result: Promise<StorageDownloadDataOutput<Item>>;}
StorageDownloadDataOutput<Item> { path: string; lastModified?: Date; size?: number; eTag?: string; metadata?: Record<string, string>; versionId?: string; contentType?: string; body: { blob: () => Promise<Blob>; json: () => Promise<any>; text: () => Promise<string>; };}URL のみを取得 (デフォルト)
import { getUrl } from 'aws-amplify/storage';
const handleGetUrl = async (path: string) => { const url = await getUrl({ path, options: { validateObjectExistence: true }, });}import { Storage } from 'aws-amplify';
const handleGetUrl = async (key: string) => { const url = await Storage.get(key, { validateObjectExistence: true });}ファイルコンテンツをメモリにダウンロード
import { downloadData } from 'aws-amplify/storage';
const handleDownload = async (path: string) => { const { body, eTag } = await downloadData({ path }).result;}import { Storage } from 'aws-amplify';
const handleDownload = async (key: string) => { const { Body, ETag } = await Storage.get(key, { download: true });}ダウンロード進度の監視
progressCallback オプションは v6 で onProgress に置き換わりました。関数入力プロパティ名の loaded と total は transferredBytes と totalBytes にマップされます。
import { downloadData } from 'aws-amplify/storage';
const handleDownload = async (path: string) => { const { body, eTag } = await downloadData({ path, options: { onProgress: ({ transferredBytes, totalBytes }) => { // 進度の実装 } } }).result;}import { Storage } from 'aws-amplify';
const handleDownload = async (key: string) => { const { Body, ETag } = await Storage.get(key, { download: true, progressCallback: ({ loaded, total }) => { // 進度の実装 } });}Storage.copy
上記に記載されている変更に加えて、v6 の copy API はコンテンツオプション (contentDisposition、contentLanguage、および contentType) をサポートしなくなりました。これらの値は既存ファイルによって既に提供されています。
入力
V5
// デフォルト S3 プロバイダーを想定src: { key: string; level?: string; identityId?: string;}dest: { level?: string; key: string;}config?: { provider?: 'AWSS3'; customPrefix?: { // V6 で削除 public?: string; protected?: string; private?: string; }; track?: boolean; // V6 で削除 bucket?: string; cacheControl?: string; // V6 で削除 contentDisposition?: string; // V6 で削除 contentLanguage?: string; // V6 で削除 contentType?: string; // V6 で削除 expires?: Date; tagging?: string; // V6 で削除 acl?: | 'private' | 'authenticated-read' | 'aws-exec-read' | 'bucket-owner-full-control' | 'bucket-owner-read' | 'public-read' | 'public-read-write' | string; metadata?: Record<string, string>; serverSideEncryption?: 'AES256' | 'aws:kms'; SSECustomerAlgorithm?: string; // V6 で削除 SSECustomerKey?: string; // V6 で削除 SSECustomerKeyMD5?: string; // V6 で削除 SSEKMSKeyId?: string; // V6 で削除}V6
input: { source: { path: string | ({identityId}: {identityId: string}) => string; }; destination: { path: string | ({identityId}: {identityId: string}) => string; };}出力
V5
S3ProviderCopyOutput { key: string;}V6
CopyOutput { path: string;}import { copy } from 'aws-amplify/storage';
const handleCopy = async (sourcePath: string, destinationPath: string) => { const { path } = await copy({ source: { path: sourcePath }, destination: { path: destinationPath }, });};import { Storage } from 'aws-amplify';
const handleCopy = async (sourceKey: string, destinationKey: string) => { const { key } = await Storage.copy( src: { key: sourceKey }, dest: { key: destinationKey } )};Storage.remove
上記に記載されている変更に加えて、v6 の remove API の出力は削除されたファイルの path のみを返します。DeleteMarker、VersionId、RequestCharged、および $metadata は出力から削除されました。
入力
V5
// デフォルト S3 プロバイダーを想定key: string config?: { level?: 'public' | 'protected' | 'private'; provider?: 'AWSS3'; customPrefix?: { // V6 で削除 public?: string; protected?: string; private?: string; }; track?: boolean; // V6 で削除 bucket?: string;}V6
input: { path: string | ({identityId}: {identityId: string}) => string; options?: { useAccelerateEndpoint?: boolean; };}出力
V5
DeleteMarker?: boolean; // V6 で削除VersionId?: string; // V6 で削除RequestCharged?: 'requester' | string; // V6 で削除$metadata: { // V6 で削除 httpStatusCode?: number; requestId?: string; extendedRequestId?: string; cfId?: string; attempts?: number; totalRetryDelay?: number;};V6
RemoveOutput { path: string;}import { remove } from 'aws-amplify/storage';
const handleRemove = async (path: string) => { await remove({ path, });}import { Storage } from 'aws-amplify';
const handleRemove = async (key: string, accessLevel: string) => { await Storage.remove(key, { // アクセスレベルが「public」以外の場合は必須 level: accessLevel });}Storage.list
v5 から v6 への list API にはいくつかの変更があります。上記に記載されている変更に加えて:
hasNextToken出力プロパティが削除されました。nextTokenが定義されているかどうかをチェックして、より多くのアイテムを取得できるかどうかを確認できます。
入力
V5
// デフォルト S3 プロバイダーを想定path: string,config?: { level?: 'public' | 'protected' | 'private'; provider?: 'AWSS3'; customPrefix?: { // V6 で削除 private?: string; public?: string; protected?: string; }; track?: boolean; // V6 で削除 bucket?: string; pageSize?: number | 'ALL'; identityId?: string; nextToken?: string;}V6
// ページ分割リストinput { path: string | ({identityId}: {identityId: string}) => string; options?: { listAll?: false; pageSize?: number; nextToken?: string; useAccelerateEndpoint?: boolean; };}
// すべてをリスト化input { path: string | ({identityId}: {identityId: string}) => string; options?: { listAll: true; useAccelerateEndpoint?: boolean; };}出力
V5
StorageListOutput { results: S3ProviderListOutputItem[]; nextToken?: string; hasNextToken: boolean; // V6 で削除};
S3ProviderListOutputItem { key: string; eTag: string; lastModified: Date; size: number;}V6
// ページ分割リストListPaginateOutput { items: ListOutputItem[]; nextToken?: string;}
// すべてをリスト化ListAllOutput { items: ListOutputItem[];}
ListOutputItem { path: string; lastModified?: Date; size?: number; eTag?: string;}ページ分割リスト (デフォルト)
import { list } from 'aws-amplify/storage';
const PAGE_SIZE = 20;let nextToken = undefined;let hasNextPage = true;
const loadNextPage = async (path: string) => { if (hasNextPage) { let response = await list({ path, options: { pageSize: PAGE_SIZE, nextToken: nextToken } }); if (response.nextToken) { nextToken = response.nextToken; } else { nextToken = undefined; hasNextPage = false; } // response.results からリストアイテムをレンダリング }};import { Storage } from 'aws-amplify';
const PAGE_SIZE = 20;let nextToken = undefined;let hasNextPage = true;
const loadNextPage = async () => { if (hasNextPage) { let response = await Storage.list('', { pageSize: PAGE_SIZE, nextToken: nextToken }); if (response.hasNextToken) { nextToken = response.nextToken; } else { nextToken = undefined; hasNextPage = false; } // response.results からリストアイテムをレンダリング }};すべてのファイル
import { list } from 'aws-amplify/storage';
const handleListAll = async ( path: string) => { const { items } = list({ path, options: { listAll: true, } });}import { Storage } from 'aws-amplify';
const handleListAll = async ( prefix: string, accessLevel: string, id: string) => { const { results } = Storage.list(prefix, { pageSize: 'ALL', // level と identityId は level が「public」の場合は必須ではありません level: accessLevel, identityId: id });}Storage.getProperties
上記に記載されている変更に加えて、v6 の getProperties API は結果に path も追加します。
入力
V5
key: string config?: { level?: 'public' | 'protected' | 'private'; provider?: string; // V6 で削除 customPrefix?: { // V6 で削除 private?: string; public?: string; protected?: string; }; track?: boolean; // V6 で削除 SSECustomerAlgorithm?: string; // V6 で削除 SSECustomerKey?: string; // V6 で削除 SSECustomerKeyMD5?: string; // V6 で削除}V6
input: { path: string | ({identityId}: {identityId: string}) => string; options?: { useAccelerateEndpoint?: boolean; };}出力
V5
StorageGetPropertiesOutput { contentType: string; contentLength: number; eTag: string; lastModified: Date; metadata: Record<string, string>;};V6
GetPropertiesOutput { path: string; lastModified?: Date; size?: number'; eTag?: string'; metadata?: Record<string, string>'; versionId?: string; contentType?: string;}import { getProperties } from 'aws-amplify/storage';
const handleGetProperties = async ( path: string,) => { const result = await getProperties({ path });}import { Storage } from 'aws-amplify';
const handleGetProperties = async ( key: string, accessLevel: string) => { const result = await Storage.getProperties(key, { // level が「public」の場合は必須ではありません level: accessLevel, });}Storage.cancel
リクエストをキャンセルするためのプロセスは v6 で変更されました。v5 では、Storage API 呼び出しから返されるプロミスまたは UploadTask 参照を保持し、それを Storage.cancel API への入力として供給する必要があります。v6 では、cancel は Storage 操作の結果で返される関数です。操作をキャンセルするには、operation.cancel() を呼び出します。
import { downloadData } from 'aws-amplify/storage';
const operation = downloadData({ path: "photos/1.jpg"});
operation.response.then(result => { // GET 操作が正常に完了しました}).catch(error => { // リクエストがキャンセルされたため、ここでエラーを確認できます。 if(isCancelError(error)) { // 「キャンセルのためのメッセージ」 console.log(error.message); }})
// 上記のリクエストをキャンセルするにはoperation.cancel('my message for cancellation');import { Storage } from 'aws-amplify';
const operation = Storage.get(key, options);
operation.then(result => { // GET 操作が正常に完了しました}).catch(error => { // リクエストがキャンセルされたため、ここでエラーを確認できます。 if(Storage.isCancel(error)) { // 「キャンセルのためのメッセージ」 console.log(error.message); }});
// 上記のリクエストをキャンセルするにはStorage.cancel(operation, 'my message for cancellation');カスタムプレフィックスの使用 (非推奨)
customPrefix を使用してアイテムをアップロードまたはダウンロードしたい場合は、Amplify.configure の 2 番目のパラメータである libraryOptions にプレフィックスリゾルバーを設定できます。各 accessLevel をカスタム prefixResolver で解決する必要があることに注意してください。以下の例は protected と private アクセスレベルのデフォルトを示し、guest のカスタムプレフィックスを示しています。
import { uploadData } from 'aws-amplify/storage';import { Amplify } from 'aws-amplify';import amplifyconfig from './amplifyconfiguration.json';
const libraryOptions = { Storage: { S3: { prefixResolver: async ({ accessLevel, targetIdentityId }) => { if (accessLevel === 'guest') { return 'publicPrefix/'; } else if (accessLevel === 'protected') { return `protected/${targetIdentityId}/`; } else { return `private/${targetIdentityId}/`; } } } }};
Amplify.configure(amplifyConfig, libraryOptions);
const handleUpload = async (key: string, data: string | Blob) => { // v5 の `public` と同等のアクセスレベル `guest` を使用してファイルをアップロード const operation = uploadData({ key, data, options: { accessLevel: 'guest' } });
const result = await operation.result;}import { Storage } from 'aws-amplify';
const handleUpload = async (key: string, data: string | Blob) => { // アクセスレベル `public` でファイルをアップロード const result = await Storage.put(key, data, { level: 'public', customPrefix: { public: 'publicPrefix' } });}ストレージイベントのトラッキング
track オプションは v6 の Storage およびその API から削除されました。以前、v5 では、このオプションを有効にすると、Storage API 呼び出しの成功または失敗に関する分析イベントが Pinpoint に自動的に送信されていました。送信された分析イベントは Amplify によって定義されたため、設定することができませんでした。v6 では、このオプションは削除されていますが、Analytics カテゴリを使用してストレージ API の結果をより予測可能で設定可能な方法でトラッキングし続けることができます。
以下の表は、以前 v5 API に関連付けられていた分析イベントと、代わりに関連付ける必要のある対応する v6 API を示しています。
| 分析イベント | V5 API | V6 API |
|---|---|---|
'copy' | copy | copy |
'download' | get (download: true) | downloadData |
'getSignedUrl' | get | getUrl |
'getProperties' | getProperties | getProperties |
'upload' | put | uploadData |
'delete' | remove | remove |
'list' | list | list |
import { list } from 'aws-amplify/storage';import { record } from 'aws-amplify/analytics';
const path = 'public/photos/';
try { const result = await list({ path }); record({ name: 'list', attributes: { result: 'success' }, }); // 結果を何か処理する} catch (error) { record({ name: 'list', attributes: { result: 'failure' }, }); // エラーを何か処理する};import { Storage } from 'aws-amplify';
const prefix = 'photos/';
Storage.configure({ track: true });
try { const result = Storage.list(prefix); // 結果を何か処理する} catch (error) { // エラーを何か処理する}