Datastore 모드로 Cloud Firestore 사용

Firestore는 자동 확장, 고성능, 간편한 애플리케이션 개발을 위해 설계된 NoSQL 문서 데이터베이스입니다. Datastore의 최신 버전이며 Datastore에 비해 여러 가지 부분이 개선되었습니다.

Datastore 모드의 Firestore는 서버 사용 사례 및 App Engine에 최적화되어 있으므로 App Engine 앱에서 주로 사용하는 데이터베이스에는 Datastore 모드의 Firestore를 사용하는 것이 좋습니다. 기본 모드의 Firestore는 모바일 및 실시간 알림 사용 사례에 가장 유용합니다. Firestore 모드에 대한 자세한 내용은 Native 모드와 Datastore 모드 중 선택을 참조하세요.

이 문서에서는 Google Cloud 클라이언트 라이브러리를 사용하여 Datastore 모드 데이터베이스에서 데이터를 저장하고 검색하는 방법을 설명합니다.

기본 요건 및 설정

App Engine에서 Node.js용 'Hello, World!'의 안내에 따라 환경 및 프로젝트를 설정하고 App Engine에서 Node.js 앱이 구조화되는 방식을 알아봅니다. 이 문서에 설명된 샘플 애플리케이션을 실행할 때 필요하므로 프로젝트 ID를 기록해 둡니다.

저장소 복제

샘플을 다운로드(복제)합니다.

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
cd nodejs-docs-samples/appengine/datastore

프로젝트 구성 수정 및 종속 항목 설정

package.json에서 @google-cloud/datastore를 종속 항목으로 설정합니다. 이 종속 항목은 Datastore 모드를 사용하기 위한 함수를 제공합니다.

{
  "name": "appengine-datastore",
  "description": "Sample for Google Cloud Datastore on Google App Engine.",
  "version": "0.0.1",
  "private": true,
  "license": "Apache-2.0",
  "author": "Google Inc.",
  "repository": {
    "type": "git",
    "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
  },
  "engines": {
    "node": "16.x.x"
  },
  "scripts": {
    "start": "node app.js",
    "system-test": "mocha --exit test/*.test.js",
    "test": "npm run system-test"
  },
  "dependencies": {
    "@google-cloud/datastore": "^7.0.0",
    "express": "^4.16.4"
  },
  "devDependencies": {
    "mocha": "^9.0.0",
    "supertest": "^6.0.0"
  }
}

애플리케이션 코드

샘플 애플리케이션은 방문자 IP를 로깅, 검색, 표시합니다. 로그 항목은 visit 유형이 지정된 2개 필드로 구성된 간단한 클래스이며 데이터 세트 save 명령어를 사용하여 Datastore 모드에 저장됩니다. 이후 데이터 세트 runQuery 명령어를 사용하여 10개의 최근 방문이 내림차순으로 검색됩니다.

'use strict';

const express = require('express');
const crypto = require('crypto');

const app = express();
app.enable('trust proxy');

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GOOGLE_CLOUD_PROJECT environment variable. See
// https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// These environment variables are set automatically on Google App Engine
const {Datastore} = require('@google-cloud/datastore');

// Instantiate a datastore client
const datastore = new Datastore({
  projectId: 'long-door-651',
});

/**
 * Insert a visit record into the database.
 *
 * @param {object} visit The visit record to insert.
 */
const insertVisit = visit => {
  return datastore.save({
    key: datastore.key('visit'),
    data: visit,
  });
};

/**
 * Retrieve the latest 10 visit records from the database.
 */
const getVisits = () => {
  const query = datastore
    .createQuery('visit')
    .order('timestamp', {descending: true})
    .limit(10);

  return datastore.runQuery(query);
};

app.get('/', async (req, res, next) => {
  // Create a visit record to be stored in the database
  const visit = {
    timestamp: new Date(),
    // Store a hash of the visitor's ip address
    userIp: crypto
      .createHash('sha256')
      .update(req.ip)
      .digest('hex')
      .substr(0, 7),
  };

  try {
    await insertVisit(visit);
    const [entities] = await getVisits();
    const visits = entities.map(
      entity => `Time: ${entity.timestamp}, AddrHash: ${entity.userIp}`
    );
    res
      .status(200)
      .set('Content-Type', 'text/plain')
      .send(`Last 10 visits:\n${visits.join('\n')}`)
      .end();
  } catch (error) {
    next(error);
  }
});

const PORT = parseInt(parseInt(process.env.PORT)) || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

index.yaml 파일 사용

샘플 앱에서는 간단한 쿼리를 수행합니다. 보다 정교한 Datastore 모드 쿼리를 실행하려면 색인이 한 개 이상 필요하며 앱과 함께 업로드하는 index.yaml 파일에서 색인을 지정해야 합니다. 이 파일은 수동으로 만들거나 로컬에서 앱을 테스트하는 동안 자동으로 생성될 수 있습니다.

로컬 테스트

로컬에서 애플리케이션을 개발하고 테스트해야 하는 경우 Datastore 모드 에뮬레이터를 사용할 수 있습니다.

추가 정보

최적화와 개념을 비롯하여 Datastore 모드에 대한 자세한 내용은 Datastore 모드 문서의 Firestore를 참조하세요.