Firebase Tools

Jun's Coding Journey·2023년 9월 19일
0

[Learn] Firebase

목록 보기
5/7

FireStore


Firestore is a NoSQL, cloud-hosted database service provided by Firebase, which is a comprehensive mobile and web application development platform offered by Google. Firestore is designed to store and synchronize data for applications in real-time, making it a powerful backend database solution for building web and mobile apps.

  • Document-Oriented: Firestore is a document-oriented database, which means it stores data in collections and documents. Each document contains fields and a unique identifier (document ID). Collections are groups of documents.

  • Real-Time Updates: Firestore provides real-time synchronization of data between clients and the database. When data changes in the database, all connected clients are automatically updated, making it suitable for building collaborative and real-time applications.

  • Scalability: Firestore is designed to scale seamlessly as your application grows. It can handle both small-scale and large-scale applications without the need for manual sharding or complex scaling configurations.

  • Offline Support: Firestore offers offline data access, allowing your application to work even when there is no internet connection. Changes made while offline are automatically synchronized when the device is back online.

  • Security Rules: Firestore includes a security rules system that allows you to define access controls and permissions for your data. You can specify who can read, write, and modify data, ensuring that your data remains secure.

  • Querying: Firestore supports powerful querying capabilities, allowing you to filter and retrieve data based on various criteria, such as fields, values, and relationships between documents.

  • Integration: Firestore seamlessly integrates with other Firebase services, such as Firebase Authentication, Firebase Storage, and Firebase Cloud Functions, to build a complete backend for your application.

Firestore is commonly used for a wide range of applications, including mobile apps, web apps, IoT (Internet of Things) devices, and more, where real-time data synchronization and a scalable database solution are required. It is a popular choice among developers for building real-time chat applications, collaborative tools, e-commerce platforms, and various other applications that require dynamic data updates.


 

Storage


"Storage" typically refers to Firebase Cloud Storage, which is a cloud-based object storage service provided by Google as part of the Firebase suite of services. Firebase Cloud Storage is designed to store and serve user-generated content such as images, videos, audio files, and other files for your web or mobile applications.

  • File Storage: Firebase Cloud Storage allows you to securely store and manage files in the cloud. You can think of it as a file repository where you can upload, download, and organize files.

  • Security Rules: Just like Firebase Firestore (the NoSQL database service), Firebase Cloud Storage has security rules that you can define to control who can access and perform operations on files. You can specify rules based on user authentication, file paths, and other conditions.

  • Scalability: Firebase Cloud Storage is designed to scale automatically to accommodate your storage needs, whether you have a small application or a large-scale project.

  • Integration: It seamlessly integrates with other Firebase services, such as Firebase Authentication and Firebase Realtime Database, allowing you to build complete, end-to-end applications with user authentication and real-time features.

  • Direct File Upload and Download: You can upload files directly from a client application (e.g., a mobile app or web app) to Firebase Cloud Storage and then provide public or private download URLs for these files.

  • Versioning: Firebase Cloud Storage supports versioning, allowing you to manage different versions of files and easily roll back to a previous version if needed.

  • Metadata: You can attach metadata to files, such as custom tags or additional information, to help organize and retrieve them more efficiently.

 

Firebase Cloud Storage is commonly used for a variety of purposes in app development, including:

  • User-generated Content: Storing user-uploaded images, videos, and profile pictures.

  • File Sharing: Implementing file sharing features where users can share documents or media files with others.

  • Application Assets: Storing application assets such as fonts, configuration files, and static website content.

  • Backup and Restore: Creating backups of important data and files.

  • File Hosting: Hosting static web content, like HTML, CSS, JavaScript, and media files for web apps.

 

Firebase Cloud Storage provides a reliable and cost-effective solution for managing and serving files in a Firebase-powered application, making it a valuable component for developers building web and mobile apps that require storage and retrieval of user-generated content.


 

Cloud Functions


Overview

Cloud Functions for Firebase is a serverless computing service provided by Google Firebase, which is a mobile and web application development platform. Cloud Functions allows developers to write and deploy server-side code that can respond to various events and triggers within Firebase services or external services. Here are some key aspects of Cloud Functions in Firebase:

  • Serverless Computing: Cloud Functions abstracts away the infrastructure management, allowing developers to focus solely on writing the code that performs specific tasks or responds to events. You don't need to worry about provisioning servers, scaling, or managing server runtime environments.

  • Event-Driven: Cloud Functions are event-driven, meaning they can be triggered by various events. Common triggers include changes to Firebase Realtime Database, Firestore, Cloud Storage, authentication events, HTTP requests, and more. You can also set up custom events to trigger functions.

  • Scalable: Firebase automatically manages the scaling of your functions. When there's a surge in traffic or events, Firebase will scale the execution of your functions as needed to handle the load.

  • Multiple Runtime Environments: Cloud Functions for Firebase supports multiple runtime environments, including Node.js, Python, Go, and others. You can choose the runtime environment that best suits your development needs.

  • Integration: You can easily integrate Cloud Functions with other Firebase services like Firebase Realtime Database, Firestore, Cloud Storage, Authentication, and even third-party services via HTTP requests. This allows you to create complex workflows and automations within your application.

  • Security Rules: Firebase security rules allow you to secure your data and functions. You can specify who has access to trigger your functions and define access control rules for your Firebase services.

  • Monitoring and Logging: Firebase provides monitoring and logging capabilities for your functions. You can view logs and monitor function performance through Firebase Console and integrate it with other monitoring tools.

  • Third-Party Dependencies: You can use npm (Node Package Manager) or other package managers to include third-party dependencies in your functions, allowing you to use external libraries and services as needed.

  • Cost Control: Cloud Functions for Firebase is cost-effective because you pay only for the resources used during the execution of your functions. You are charged based on the number of invocations, execution time, and memory usage.

Common use cases for Cloud Functions for Firebase include sending notifications, processing and transforming data, automating tasks, and integrating with external services. It's a powerful tool for extending the functionality of your Firebase-powered applications and automating various backend tasks without the need for managing servers.

// deploying functions on changes
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

admin.initializeApp();

export const onVideoCreated = functions.firestore
  .document("videos/{videoId}")
  .onCreate(async (snapshot, context) => {
    snapshot.ref.update({ hello: "from functions" });
  });

 

ffmpeg

ffmpeg is a versatile tool to handle multimedia data; it can be used for tasks such as converting between video and audio formats, extracting metadata, manipulating media files, and many more.

In the context of Cloud Functions (for Firebase or other cloud platforms), ffmpeg can be used for on-the-fly multimedia processing. For example, when a user uploads a video to Firebase Storage, a Cloud Function could be triggered to use ffmpeg to process this video, perhaps to create a compressed version, generate a thumbnail, or extract audio.

// extracting thumbnail from ffmpeg
export const onVideoCreated = functions.firestore
  .document("videos/{videoId}")
  .onCreate(async (snapshot, context) => {
    const spawn = require("child-process-promise").spawn;
    const video = snapshot.data();
    await spawn("ffmpeg", [
      "-i",
      video.fileUrl,
      "-ss",
      "00:00:01.000",
      "-vframes",
      "1",
      "-vf",
      "scale=150:-1",
      `/tmp/${snapshot.id}.jpg`,
    ]);
    const storage = admin.storage();
    await storage.bucket().upload(`/tmp/${snapshot.id}.jpg`, {
      destination: `thumbnails/${snapshot.id}.jpg`,
    });
  });

 

publicUrl

A "public URL" often refers to the endpoint URL through which an HTTP-triggered Cloud Function can be accessed.

// creating a separte document for uploaded videos on firebase
const [file, _] = await storage.bucket().upload(`/tmp/${snapshot.id}.jpg`, {
      destination: `thumbnails/${snapshot.id}.jpg`,
    });
    await file.makePublic();
    await snapshot.ref.update({ thumbnailUrl: file.publicUrl() });
    const db = admin.firestore();
    await db
      .collection("users")
      .doc(video.creatorUid)
      .collection("videos")
      .doc(snapshot.id)
      .set({
        thumbnailUrl: file.publicUrl(),
        videoId: snapshot.id,
      });

 

Infinite Scrolling


Infinite scrolling is a listing-page design approach which loads content continuously as the user scrolls down. It eliminates the need for pagination and breaks content up into multiple pages.

This method can be used in apps like Instagram and TikTok, where users can infinitely scroll through contents without interruptions.

class BeerListView extends StatefulWidget {
  
  _BeerListViewState createState() => _BeerListViewState();
}

class _BeerListViewState extends State<BeerListView> {
  static const _pageSize = 20;

  final PagingController<int, BeerSummary> _pagingController =
      PagingController(firstPageKey: 0);

  
  void initState() {
    _pagingController.addPageRequestListener((pageKey) {
      _fetchPage(pageKey);
    });
    super.initState();
  }

  Future<void> _fetchPage(int pageKey) async {
    try {
      final newItems = await RemoteApi.getBeerList(pageKey, _pageSize);
      final isLastPage = newItems.length < _pageSize;
      if (isLastPage) {
        _pagingController.appendLastPage(newItems);
      } else {
        final nextPageKey = pageKey + newItems.length;
        _pagingController.appendPage(newItems, nextPageKey);
      }
    } catch (error) {
      _pagingController.error = error;
    }
  }

  
  Widget build(BuildContext context) => 
      PagedListView<int, BeerSummary>(
        pagingController: _pagingController,
        builderDelegate: PagedChildBuilderDelegate<BeerSummary>(
          itemBuilder: (context, item, index) => BeerListItem(
            beer: item,
          ),
        ),
      );

  
  void dispose() {
    _pagingController.dispose();
    super.dispose();
  }
}

profile
Greatness From Small Beginnings

0개의 댓글