Skip to content

Instantly share code, notes, and snippets.

@elijahmanor
Created September 24, 2020 12:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save elijahmanor/ecca498b76f885887e87a5ced0342d26 to your computer and use it in GitHub Desktop.
Firebase Code inside a Next.js API Function
const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");
const firebaseConfig = { /* ... */ };
try {
firebase.initializeApp(firebaseConfig);
} catch (error) {
/*
* We skip the "already exists" message which is
* not an actual error when we're hot-reloading.
*/
if (!/already exists/u.test(error.message)) {
// eslint-disable-next-line no-console
console.error("Firebase initialization error", error.stack);
}
}
export default firebase;
import firebase from "../../lib/firebase";
export default async (req, res) => {
try {
if (!req.query.id) {
return res.status(400).json({
error: 'Missing "id" query parameter'
});
}
const db = firebase.firestore();
const doc = await db.collection("views").doc(req.query.id).get();
let count = 0;
if (doc.exists) {
count = doc.data().count + 1;
} else {
console.log("document does not exist");
}
await db.collection("views").doc(req.query.id).set({
id: req.query.id,
count
});
return res.status(200);
} catch (error) {
console.error(error);
return res.status(error.status || 500).end(error.message);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment