1.1.1 • Published 4 months ago
fastify-firebase v1.1.1
fastify-firebase
Fastify firebase-admin plugin, adds firebase object into fastify's instance with typescript support.
Install
npm i fastify-firebase
yarn add fastify-firebase
pnpm add fastify-firebase
Usage
Add the plugin into your project using the register
function, provide the cert file from firebase console and you are done!
This plugin will add the firebase namespace in your fastify instance.
Example:
import Fastify from 'fastify';
import fastifyFirebase from 'fastify-firebase';
import firebasePrivateKeyJson from '../firebase.json'; // <-- private key file can be downloaded from firebase console (aka cert file).
const server = Fastify({logger: true});
server.register(fastifyFirebase, firebasePrivateKeyJson); // simply hook the plugin with the cert file.
server.get('/getAllUsers', async (request, reply) => {
// both request and reply contains server object
// means we can find firebase object on both
// request.server.firebase | reply.server.firebase
const firebase = request.server.firebase;
try {
const snapshot = await firebase.firestore().collection('Users').get();
const arrayOfUsers = snapshot.docs.map((doc) => doc.data());
reply.send(arrayOfUsers);
} catch (error) {
throw new Error(error);
}
});
(async () => {
try {
const address = await server.listen({port: 3000});
console.log(`Server listening at ${address}`);
} catch (err) {
server.log.error(err);
process.exit(1);
}
})();
Useful links
- How to generate a private key file for your service account
- Firebase's Settings > Service Accounts.
- Fastify
- fastify-plugin NPM
- firebase-admin NPM
- fastify-firebase NPM
License
Licensed under MIT.