[참고] Cloud Functions + Node.js로 빨리 API 개발

가끔은 firebase 에서 API를 만들고 싶어졌기 때문에 만들어 보았습니다.
다음 마음이 향했을 때, 빨리 만들 수 있도록.
firebase --version 
9.1.0

프로젝트 만들기



우선 GUI로 프로젝트를 작성해, 과금 모드로 해 두는 것이 편하다.
https://console.firebase.google.com/u/0/
cd desktop
mkdir api
cd api

연계/초기화



필요한 경우 활성화합니다. 일단 Functions만 유효화해 본다.


$ mkdir api 
$ cd api
$ firebase init

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  /Users/user/Desktop/api

? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices. 
 ◯ Database: Configure Firebase Realtime Database and deploy rules
 ◯ Firestore: Deploy rules and create indexes for Firestore
❯◉ Functions: Configure and deploy Cloud Functions
 ◯ Hosting: Configure and deploy Firebase Hosting sites
 ◯ Storage: Deploy Cloud Storage security rules
 ◯ Emulators: Set up local emulators for Firebase features
 ◯ Remote Config: Get, deploy, and rollback configurations for Remote Config
=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add, 
but for now we'll just set up a default project.

? Please select an option: (Use arrow keys)
❯ Use an existing project 
  Create a new project 
  Add Firebase to an existing Google Cloud Platform project 
  Don't set up a default project 

? Please select an option: Use an existing project
? Select a default Firebase project for this directory: 
  xxxxxxxx (yyyy) 
❯ api-189bf (api) 
  xxxxxxxx (yyyyy) 
  xxxxxxxx (yyyyy) 
=== Functions Setup

A functions directory will be created in your project with a Node.js
package pre-configured. Functions can be deployed with firebase deploy.

? What language would you like to use to write Cloud Functions? (Use arrow keys)
❯ JavaScript 
  TypeScript 
? What language would you like to use to write Cloud Functions? JavaScript
? Do you want to use ESLint to catch probable bugs and enforce style? Yes
✔  Wrote functions/package.json
✔  Wrote functions/.eslintrc.json
✔  Wrote functions/index.js
✔  Wrote functions/.gitignore
? Do you want to install dependencies with npm now? Yes

> [email protected] postinstall /Users/inoueyousuke/Desktop/api/functions/node_modules/protobufjs
> node scripts/postinstall

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...
i  Writing gitignore file to .gitignore...

✔  Firebase initialization complete!

helloWorld 배포



/functions/index.js

const functions = require('firebase-functions');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//   functions.logger.info("Hello logs!", {structuredData: true});
//   response.send("Hello from Firebase!");
// });

댓글 아웃 삭제



/functions/index.js

const functions = require('firebase-functions');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
 exports.helloWorld = functions.https.onRequest((request, response) => {
   functions.logger.info("Hello logs!", {structuredData: true});
   response.send("Hello from Firebase!");
 });

배포! !


firebase deploy

=== Deploying to 'api-189bf'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> functions@ lint /Users/user/Desktop/api/functions
> eslint .

✔  functions: Finished running predeploy script.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
⚠  functions: missing required API cloudbuild.googleapis.com. Enabling now...
✔  functions: required API cloudfunctions.googleapis.com is enabled
✔  functions: required API cloudbuild.googleapis.com is enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (33.28 KB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: creating Node.js 12 function helloWorld(us-central1)...
✔  functions[helloWorld(us-central1)]: Successful create operation. 
Function URL (helloWorld): https://us-central1-api-189bf.cloudfunctions.net/helloWorld

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/api-189bf/overview

생성된 엔드포인트에 액세스








완성



앞에서 두드리는 POSTAPI 만들기



CORS가 번거롭기 때문에 아래 참조로 회피



functions/index.js
const functions = require("firebase-functions");

exports.post = functions.https.onRequest(async (request, response) => {

  //CORS用にAccess-Control-Allow系ヘッダを追加
  response.set("Access-Control-Allow-Origin", "https://xxxxxx.com");
  //DELETEだけは拒否
  response.set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST");
  //Content-Typeのみを許可
  response.set("Access-Control-Allow-Headers", "Content-Type");
  // dataフィールドに渡したい値は入れる
  response.json({ data: "hello!!" });
});

Cloud Functions에서 npm 모듈 사용



./functions


npm install xxx

그리고는 보통 index.js를 쓸 뿐.

Fire Store라든지 사용하고 싶다



위 장을 참고로 도입.
이 기사 참조
npm i firebase-admin --save

/functions/index.js
const functions = require('firebase-functions')
// cloud functionでfirestoreを使うのに必要な設定は以下の2行
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)

// データベースの参照を作成
var fireStore = admin.firestore()

exports.helloWorld = functions.https.onRequest((request, response) => {
  // 動作確認のため適当なデータをデータベースに保存
  var citiesRef = fireStore.collection('cities');
  citiesRef.doc('SF').set({
    name: 'San Francisco', state: 'CA', country: 'USA',
    capital: false, population: 860000 })

  var cityRef = fireStore.collection('cities').doc('SF')
  cityRef.get()
  .then(doc => {
    if (!doc.exists) {
      response.send('No such document!')
    } else {
      response.send(doc.data())
      }
    })
    .catch(err => {
      response.send('not found')
    })
})

일단 이런 느낌으로 행복할 수 있습니다!
에뮬레이터라든지 쓰고 싶었지만, 또 마음이 향했을 때 해 보자.

바이바이!

참조



cloud functions에서 firestore 사용
Markdown 이미지에 테두리 추가
Firebase의 Cloud Functions에서 CORS가 ~라든지 Access-Control-Allow-Origin이 ~라고 말하면

좋은 웹페이지 즐겨찾기