npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

firecrudnewapi

v1.0.1

Published

A CRUD npm package supporting Firebase.

Downloads

13

Readme


Firebase Auto CRUD API


firecrudnewapi is an NPM package that automatically generates a fully functional CRUD API for Firebase Firestore collections, making backend development fast and efficient. The package provides RESTful endpoints for creating, reading, updating, and deleting data, with support for custom routes.

Features

  • Automatically generate CRUD API for Firebase Firestore collections.
  • Custom routes to extend beyond basic CRUD.
  • Bulk operations for batch updates and deletions.
  • Schema enforcement for structuring data.
  • Easy-to-use and flexible for various Firebase applications.

Installation

npm install firecrudnewapi

Usage

Here’s how you can quickly set up your Firebase-based CRUD API.

1. Initialize Firebase and Create API

const { createFirebaseCrudAPI } = require('firecrudnewapi');
const serviceAccount = require('./serviceAccountKey.json'); // Firebase service account file
const databaseURL = 'https://your-firebase-project.firebaseio.com'; // Your Firebase database URL

// Define your schema for the Firestore collection
const productSchema = {
  name: '',
  price: 0,
  category: '',
};

// Initialize the CRUD API for Firebase with the collection name "products"
const app = createFirebaseCrudAPI(serviceAccount, databaseURL, 'products', productSchema);

// Start your Express app
app.listen(3000, () => {
  console.log('Firebase CRUD API is running on port 3000');
});

2. Schema Definition

Define a schema for structuring your collection's documents:

const productSchema = {
  name: '',       // Default value for name
  price: 0,       // Default value for price
  category: '',   // Default value for category
};

The schema helps in structuring the documents with default values when creating or updating data.

3. Custom Routes

You can add custom routes to extend the functionality of the basic CRUD API. For example, to get expensive products:

const customRoutes = [
  {
    method: 'get',
    path: '/api/products/expensive',
    handler: async (req, res) => {
      try {
        const expensiveProducts = await firestore.collection('products').where('price', '>', 1000).get();
        const results = expensiveProducts.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        res.status(200).send(results);
      } catch (error) {
        res.status(500).send(error);
      }
    },
  },
];

Pass customRoutes when initializing the CRUD API:

const app = createFirebaseCrudAPI(serviceAccount, databaseURL, 'products', productSchema, customRoutes);

API Endpoints

The package auto-generates the following endpoints for each collection:

1. Create: POST /api

  • Creates a new document in the Firestore collection.
  • Example:
    {
      "name": "Product A",
      "price": 100,
      "category": "Electronics"
    }

2. Read All: GET /api

  • Retrieves all documents from the Firestore collection.
  • Supports filtering, sorting, and pagination.

3. Read One: GET /api/:id

  • Retrieves a specific document by its ID.

4. Update: PUT /api/:id

  • Updates a specific document by its ID.

5. Delete: DELETE /api/:id

  • Deletes a specific document by its ID.

6. Bulk Update: POST /api/bulk-update

  • Updates multiple documents at once.
  • Example request:
    {
      "updates": [
        { "id": "docId1", "data": { "name": "Updated Product A" } },
        { "id": "docId2", "data": { "price": 200 } }
      ]
    }

7. Bulk Delete: POST /api/bulk-delete

  • Deletes multiple documents at once.
  • Example request:
    {
      "ids": ["docId1", "docId2", "docId3"]
    }

How to Use Custom Libraries

You can use any additional libraries in your custom routes, such as moment for date handling:

const moment = require('moment');

const customRoutes = [
  {
    method: 'get',
    path: '/api/products/recent',
    handler: async (req, res) => {
      const now = moment().subtract(30, 'days').toDate();  // Get products from last 30 days
      const recentProducts = await firestore.collection('products').where('createdAt', '>', now).get();
      const results = recentProducts.docs.map(doc => ({ id: doc.id, ...doc.data() }));
      res.status(200).send(results);
    },
  },
];

Dependencies

  • express: Used to create the server and handle routes.
  • body-parser: Middleware to parse incoming request bodies.
  • firebase-admin: The official Firebase Admin SDK to interact with Firestore.

License

This project is licensed under the ISC license.