728x90
728x90

Azure Cosmos DB for MongoDB (RU) 연동하기

들어가며

  • Azure Cosmos DB for MongoDB (RU) 연동하는 방법을 간단하게 정리해본다.
  • Next.js 15를 이용하였다.

 

방법

Azure Cosmos DB for MongoDB (RU) 생성하기

  • 애저 포털에서 Azure Cosmos DB for MongoDB (RU) 리소스를 생성한다.

 

코드 작성하기

  • Next.js 15를 기준으로 다음과 같은 코드를 작성한다.

 

/.env.local (환경 변수)
  • Azure Cosmos DB For MongoDB (RU) 리소스를 생성하면 URI를 확인할 수 있다.
AZURE_COSMOS_MONGO_URI="YOUR_URI"
AZURE_COSMOS_MONGO_DB_NAME="YOUR_DB_NAME"

 

/app/api/sync/route.ts
import { NextResponse } from "next/server";

import clientPromise from "@/lib/mongodb";

// GET: 데이터 조회 (query: collectionName, page)
export async function GET(request: Request) {
  try {
    const client = await clientPromise;
    const { searchParams } = new URL(request.url);

    const dbName = process.env.AZURE_COSMOS_MONGO_DB_NAME;
    const collectionName = searchParams.get("collectionName");

    if (!collectionName) {
      return NextResponse.json(
        { error: "Missing collectionName" },
        { status: 400 },
      );
    }

    const page = parseInt(searchParams.get("page") || "1", 10);
    const limit = 50;
    const skip = (page - 1) * limit;

    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    const docs = await collection
      .find({})
      .sort({ _id: 1 })
      .skip(skip)
      .limit(limit)
      .toArray();

    return NextResponse.json(
      { data: docs, page, hasNextPage: docs.length === limit },
      { status: 200 },
    );
  } catch (error) {
    console.error("MongoDB GET error:", error);
    return NextResponse.json(
      { error: "Internal Server Error" },
      { status: 500 },
    );
  }
}

// POST: 데이터 추가 (body: { collectionName, document })
export async function POST(request: Request) {
  try {
    const client = await clientPromise;
    const body = await request.json();

    const dbName = process.env.AZURE_COSMOS_MONGO_DB_NAME;
    const { collectionName, document } = body;

    if (!collectionName || !document || typeof document !== "object") {
      return NextResponse.json({ error: "Invalid payload" }, { status: 400 });
    }

    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    const result = await collection.insertOne(document);

    return NextResponse.json(
      { message: "Document inserted", insertedId: result.insertedId },
      { status: 201 },
    );
  } catch (error) {
    console.error("MongoDB POST error:", error);
    return NextResponse.json(
      { error: "Internal Server Error" },
      { status: 500 },
    );
  }
}

 

/lib/mongodb.ts
import { MongoClient } from "mongodb";

const uri = process.env.AZURE_COSMOS_MONGO_URI!;
if (!uri) throw new Error("Missing AZURE_COSMOS_MONGO_URI");

const options = {
  tls: true,
  retryWrites: false,
  maxIdleTimeMS: 120000,
};

let client: MongoClient;
let clientPromise: Promise<MongoClient>;

declare global {
  var _mongoClientPromise: Promise<MongoClient> | undefined;
}

if (process.env.NODE_ENV === "development") {
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options);
    global._mongoClientPromise = client.connect();
  }
  clientPromise = global._mongoClientPromise;
} else {
  client = new MongoClient(uri, options);
  clientPromise = client.connect();
}

export default clientPromise;

 

/lib/api/sync.ts
const API_BASE = "/api/sync";

// 데이터 가져오기
export async function fetchSyncData(
  collectionName: string,
  page: number = 1,
): Promise<{
  data: any[];
  page: number;
  hasNextPage: boolean;
}> {
  const res = await fetch(
    `${API_BASE}?collectionName=${collectionName}&page=${page}`,
  );

  if (!res.ok) {
    throw new Error(`Failed to fetch data: ${res.status}`);
  }

  return res.json();
}

// 데이터 업로드
export async function uploadSyncData(
  collectionName: string,
  document: Record<string, any>,
): Promise<{
  message: string;
  insertedId: string;
}> {
  const res = await fetch(API_BASE, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ collectionName, document }),
  });

  if (!res.ok) {
    throw new Error(`Failed to upload data: ${res.status}`);
  }

  return res.json();
}

 

참고 사이트

 

Quickstart - Node.js - Azure Cosmos DB for MongoDB (RU)

Deploy a .NET web application that uses the client library for Node.js to interact with Azure Cosmos DB for MongoDB (RU) data in this quickstart.

learn.microsoft.com

 

728x90
728x90