インポート/エクスポートパターン
このガイドでは、CSVの処理、Excelファイルの処理、Step Functionsを使用したバッチデータ操作など、データのインポートおよびエクスポート操作のパターンについて説明します。
このガイド を使用するタイミング
以下の場合にこのガイドを使用してください:
- CSVまたはExcelファイルから一括データをインポートする
- 様々な形式にデータをエクスポートする
- Step Functionsで大規模なデータセットを処理する
- S3署名付きURLでファイルアップロードを実装する
- 外部形式と内部形式の間でデータを変換する
インポートアーキテクチャの概要
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Client │────>│ S3 │────>│Step Function│────>│ Lambda │
│ (Upload) │ │ (Storage) │ │(Orchestrate)│ │ (Process) │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
│
┌───────────────────────────┘
▼
┌─────────────┐ ┌─────────────┐
│ DynamoDB │<────│ Import │
│ (Command) │ │ Handler │
└─────────────┘ └─────────────┘
ファイルアップロードパターン
ストレージサービス
安全なファイルアップロードのための署名付きURLを生成します:
// storage/storage.service.ts
import { Injectable } from '@nestjs/common';
import { S3Service } from '@mbc-cqrs-serverless/core';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
@Injectable()
export class StorageService {
constructor(private readonly s3Service: S3Service) {}
/**
* Generate upload URL for file import (ファイルインポート用のアップロードURLを生成)
*/
async genUploadUrl(
filename: string,
contentType = 'text/csv',
): Promise<{ bucket: string; key: string; url: string }> {
const bucket = this.s3Service.privateBucket;
const timestamp = Date.now();
const key = `imports/${timestamp}/${filename}`;
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
ContentType: contentType,
ACL: 'private',
});
const url = await getSignedUrl(this.s3Service.client, command, {
expiresIn: 3600, // 1 hour (1時間)
});
return { bucket, key, url };
}
/**
* Generate download URL for file export (ファイルエクスポート用のダウンロードURLを生成)
*/
async genDownloadUrl(
key: string,
filename?: string,
): Promise<{ url: string }> {
const command = new GetObjectCommand({
Bucket: this.s3Service.privateBucket,
Key: key,
ResponseContentDisposition: filename
? `attachment; filename="${filename}"`
: undefined,
});
const url = await getSignedUrl(this.s3Service.client, command, {
expiresIn: 3600,
});
return { url };
}
}
ストレージコントローラー
// storage/storage.controller.ts
import { Controller, Post, Get, Body, Query } from '@nestjs/common';
import { StorageService } from './storage.service';
@Controller('api/storage')
export class StorageController {
constructor(private readonly storageService: StorageService) {}
/**
* Get presigned URL for upload (アップロード用の署名付きURLを取得)
*/
@Post('upload-url')
async getUploadUrl(
@Body() dto: { filename: string; contentType?: string },
) {
return this.storageService.genUploadUrl(dto.filename, dto.contentType);
}
/**
* Get presigned URL for download (ダウンロード用の署名付きURLを取得)
*/
@Get('download-url')
async getDownloadUrl(
@Query('key') key: string,
@Query('filename') filename?: string,
) {
return this.storageService.genDownloadUrl(key, filename);
}
}