Skip to content

dannyblv/fastify-firebase

Repository files navigation

fastify-firebase

CI status NPM version Weekly downloads

Fastify firebase-admin plugin, adds firebase object into fastify's instance with typescript support. Firebase modules are presented in suggestions window

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

License

Licensed under MIT.