기타

OpenFaaS로 MongoDB REST Proxy 통해 MongoDB 조회하는 예시

ipxy 2025. 4. 14. 15:52
728x90


OpenFaaS 함수JavaScript(Node.js) 로 작성해서,
MongoDB REST Proxy (예: RESTHeart) 를 통해
HTTP 요청으로 MongoDB 조회하는 예시.


🛠️ OpenFaaS + JavaScript 함수 예시

handler.js

"use strict"

const fetch = require('node-fetch');  // 외부 HTTP 호출용 라이브러리

module.exports = async (event, context) => {
    const MONGO_PROXY_URL = "http://restheart.mongodb.svc.cluster.local:8080/mydb/mycollection";

    try {
        const response = await fetch(MONGO_PROXY_URL, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json"
            }
        });

        if (!response.ok) {
            return context.status(response.status).succeed(`Mongo Proxy Error: ${await response.text()}`);
        }

        const data = await response.json();

        return context.status(200).succeed(JSON.stringify(data));

    } catch (error) {
        return context.status(500).succeed(`Internal Server Error: ${error.message}`);
    }
}

📦 1. 함수 구조 설명

 

항목  내용
fetch 사용 node-fetch 라이브러리로 MongoDB REST Proxy에 HTTP 요청
Mongo Proxy URL http://restheart.mongodb.svc.cluster.local:8080/mydb/mycollection (컬렉션 조회)
에러 처리 HTTP 상태코드에 따라 정상/오류 구분
결과 반환 JSON 형태로 클라이언트에 응답

⚙️ 2. faas.yml 파일 예시 (Node.js)

version: 1.0
provider:
  name: openfaas
  gateway: http://<openfaas-gateway-address>:8080

functions:
  mongo-query-fn-js:
    lang: node12  # 또는 node18 템플릿
    handler: ./mongo-query-fn-js
    image: your-dockerhub-id/mongo-query-fn-js:latest
    environment:
      content_type: application/json

📋 3. 빌드 & 배포 방법

1) 템플릿 준비:

faas-cli template store pull node12
# 또는 최신 버전 node18 템플릿도 가능

2) 함수 생성:

faas-cli new mongo-query-fn-js --lang node12

mongo-query-fn-js/handler.js 파일 생성됨.

3) 위에서 작성한 handler.js로 덮어쓰기


4) 함수 빌드 + 푸시 + 배포

faas-cli build -f mongo-query-fn-js.yml
faas-cli push -f mongo-query-fn-js.yml
faas-cli deploy -f mongo-query-fn-js.yml

🚀 4. 테스트

배포 완료 후 OpenFaaS Gateway에 테스트 요청:

curl -X POST http://<openfaas-gateway-address>:8080/function/mongo-query-fn-js

→ MongoDB Proxy를 통해 조회된 JSON 데이터가 반환됩니다.


✨ 요약 (JavaScript 버전)

 

항목  내용
함수 언어 JavaScript (Node.js)
HTTP 클라이언트 node-fetch 사용
동작 MongoDB REST Proxy에 GET 요청 → JSON 결과 반환
배포 faas-cli로 빌드/푸시/배포

 


📚 추가 참고사항

  • 만약 MongoDB Proxy가 인증 필요할 경우:이런 식으로 헤더에 인증 추가 가능합니다.
  • headers: { "Authorization": "Basic base64encoded-credentials", "Content-Type": "application/json", "Accept": "application/json" }
  • 만약 특정 쿼리 조건(filter, limit)으로 조회하고 싶으면:URL에 파라미터를 추가해서 요청하면 됩니다.
  • const url = `${MONGO_PROXY_URL}?filter=name:John&limit=10`; const response = await fetch(url, { ... });

 

728x90