API Demo Code

mail@pastecode.io avatar
unknown
javascript
3 years ago
1.5 kB
2
Indexable
Never
const functions = require("firebase-functions");
const express = require("express");
const admin = require("firebase-admin");

const handleError = (err, res) => {
    console.log(err);
    res.status(500).send({errMsg: err});
};

// Set up a database
admin.initializeApp();
const db = admin.firestore();
const roomDB = db.collection("rooms");

// Set up an Express Application
const app = express();

// --- GET ---
app.get("/rooms", async (req, res) => {
    try {
        const rooms = await roomDB.get();
        const roomJsons = rooms.docs.map(room => room.data());
        res.json({result: roomJsons});
    } catch (err) {
        handleError(err, res)
    }
});

// --- POST ---
app.post("/rooms", async (req, res) => {
    try {
        const room = req.body;
        const writeResult = await roomDB.add(room);
        res.json({result: `Room with ID: ${writeResult.id} added.`});

    } catch (err) {
        handleError(err, res)
    }
});

// --- PUT ---
app.put("/rooms", async (req, res) => {
    try {
        const newRoom = req.body
        const roomID = req.body.roomID;
        await roomDB.doc(roomID).set(newRoom);
        res.status(200).send();

    } catch (err) {
        handleError(err, res)
    }
});

// --- DELETE ---
app.delete("/rooms", async (req, res) => {
    try {
        const roomID = req.query.roomID;
        await roomDB.doc(roomID).delete();
        res.status(200).send();

    } catch (err) {
        handleError(err, res)
    }
});

exports.app = functions.https.onRequest(app);