Created
June 6, 2018 14:35
-
-
Save Charpell/0aac65235ed44ce74ecb5bd56c5e2865 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
}); | |
exports.addItem = functions.https.onRequest((req, res) => { | |
return cors(req, res, () => { | |
if(req.method !== 'POST') { | |
return res.status(401).json({ | |
message: 'Not allowed' | |
}) | |
} | |
console.log(req.query) | |
const item = req.query.item | |
database.push({ item }); | |
let items = []; | |
return database.on('value', (snapshot) => { | |
snapshot.forEach((item) => { | |
items.push({ | |
id: item.key, | |
items: item.val().item | |
}); | |
}); | |
res.status(200).json(items) | |
}, (error) => { | |
res.status(error.code).json({ | |
message: `Something went wrong. ${error.message}` | |
}) | |
}) | |
}) | |
}) | |
exports.getItems = functions.https.onRequest((req, res) => { | |
return cors(req, res, () => { | |
if(req.method !== 'GET') { | |
return res.status(401).json({ | |
message: 'Not allowed' | |
}) | |
} | |
let items = []; | |
return database.on('value', (snapshot) => { | |
snapshot.forEach((item) => { | |
items.push({ | |
id: item.key, | |
items: item.val().item | |
}); | |
}); | |
res.status(200).json(items) | |
}, (error) => { | |
res.status(error.code).json({ | |
message: `Something went wrong. ${error.message}` | |
}) | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment