LoginSignup
1
0

More than 3 years have passed since last update.

Firebase FunctionsでRealtime databaseにdataを送信する

Posted at

恒例

https://firebase.google.com/docs/functions ドキュメントを読んでください

Firebase CLI をインストールする

npm install -g firebase-tools

Coding

mkdir test
cd test
mkdir functions
cd functions
vi package.json
{
  "name": "mytest",
  "description": "mytest",
  "dependencies": {
    "firebase-admin": "~7.1.1",
    "firebase-functions": "^2.2.1"
  },
  "devDependencies": {
    "chai": "^3.5.0",
    "chai-as-promised": "^6.0.0",
    "firebase-functions-test": "0.1.6",
    "mocha": "^5.0.5",
    "sinon": "^4.1.3"
  },
  "scripts": {
    "ci-test": "npm install && npm run test",
    "serve": "firebase serve --only functions",
    "shell": "firebase experimental:functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "8"
  },
  "private": true
}
vi index.js
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.send_data = functions.https.onRequest(async (req, res) => {

  const time = req.query.time;
  const text = req.query.temp;

  const snapshot = await admin.database().ref('/test').push({time:time,text:text});

  res.redirect(303, snapshot.ref.toString());
});

exports.read_data = functions.https.onRequest((req, res) => {

    var ref = admin.database().ref("test");
    return ref.orderByChild("time").limitToLast(10).once('value').then(function(snapshot) {
      res.send(snapshot.val());
    });

});

Deploy

cd functions && npm install && cd ..
firebase deploy

送信方法

https://us-central1-[MY_PROJECT].cloudfunctions.net/send_data?time=20200218&text=uppercaseme をアクセスする

DATAを読み取る方法

https://us-central1-[MY_PROJECT].cloudfunctions.net/read_data をアクセスする

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0