Slide 12
Slide 12 text
Server ActionからのDynamoDBへの操作
● AWS Amplify SDK v6とNext.js Adapterで
DynamoDBクライアントの初期化とユーザー情
報の取得行う共通メソッドを予め用意する
● Server ActionsでそのままDynamoDBクライア
ントとユーザー情報を取得し、それを利用して
DBへのCRUD操作を行う
● Server Action自体はClient Componentと
Server Component両方インポートして実行で
きるので非常に便利。
○ バックエンドとフロントエンドとの連携は、
Component側からServer Actionをインポート
するだけで済むので API GatewayとLambdaを
構築する手間を省ける
"use server"
import { Note } from "@/entities";
import { v4 as uuidv4 } from "uuid";
import { getCurrentUserFromServer, getDynamoDBClient } from "@/utils";
import {
QueryCommand, QueryCommandInput, PutItemCommand, PutItemCommandInput, DeleteItemCommand,
DeleteItemCommandInput,
} from "@aws-sdk/client-dynamodb";
import { revalidatePath } from "next/cache";
export const putNote = async (data: FormData) => {
const note_name = data.get("note_name") as string;
const note_content = data.get("note_content") as string;
let note_id = data.get("note_id") as string;
if (!note_id) {
note_id = uuidv4();
}
const client = await getDynamoDBClient();
const user = await getCurrentUserFromServer();
const putItemRequest: PutItemCommandInput = {
TableName: tableName,
Item: {
note_id: { S: note_id },
user_id: { S: user.userId },
note_name: { S: note_name },
note_content: { S: note_content },
},
};
await client.send(new PutItemCommand(putItemRequest));
revalidatePath("/");
};