- Go to https://firebase.google.com/
- Login or signup and go to console.
- Add project.
- Enter your project name.
- Create project.
- Open terminal.
- Go to desktop.
cd Desktop
- Make a folder item-list-server.
mkdir item-list-server
- Go to the folder.
cd item-list-server
- Install the Firebase CLI.
npm install -g firebase-tools
If command fails use
sudo npm install -g firebase-tools
- Run firebase login.
firebase login
- Allow firebase to collect anonymous cli usage and error reporting information?
yes
- This will open your browser for login with firebase. Choose your account and login.
- Run firebase init functions.
firebase init functions
- This will show a list of all your projects, use the arrow key to select your project.
- 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?
n
- Do you want to install dependencies with npm now?
y
- This will setup the project and install all the dependencies.
- Now, go to the functions folder
cd functions
- Open the index.js file and insert the following code snippet.
const functions = require("firebase-functions");
const cors = require("cors")({ origin: true });
const admin = require("firebase-admin");
admin.initializeApp();
const database = admin.database().ref("/items");
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from a Severless Database!");
});
const getItemsFromDatabase = res => {
let items = [];
return database.on(
"value",
snapshot => {
snapshot.forEach(item => {
items.push({
id: item.key,
item: item.val().item
});
});
res.status(200).json(items);
},
error => {
res.status(500).json({
message: `Something went wrong. ${error}`
});
}
);
};
exports.addItem = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
if (req.method !== "POST") {
return res.status(500).json({
message: "Not allowed"
});
}
const item = req.body.item;
database.push({ item });
getItemsFromDatabase(res);
});
});
exports.getItems = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
if (req.method !== "GET") {
return res.status(500).json({
message: "Not allowed"
});
}
getItemsFromDatabase(res);
});
});
exports.deleteItem = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
if (req.method !== "DELETE") {
return res.status(500).json({
message: "Not allowed"
});
}
const id = req.query.id;
admin
.database()
.ref(`/items/${id}`)
.remove();
getItemsFromDatabase(res);
});
});
- Run the following command on your terminal.
firebase deploy
If you want to show where it is. Goto the firebase console. Click on functions. This will show you the list of fuctions that you create.