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

nextjs-firebase-data

v1.0.39

Published

Firebase data handler for Next.js applications with TypeScript. Provides a context provider and a base controllers for data mutation.

Downloads

105

Readme

Integração do pacote nextjs-firebase-data

Passo 1: Instalação

Para começar a utilizar o pacote nextjs-firebase-data, primeiro, instale-o utilizando o seguinte comando:

yarn add nextjs-firebase-data

Passo 2: Configuração Inicial

Após a instalação, execute o comando abaixo para criar arquivos iniciais com configurações básicas:

yarn nfd setup

Este comando realizará as seguintes ações:

2.1 Criação de Arquivos

  • BaseController:

    • O comando cria o arquivo controllers/BaseController.ts, que fornece métodos padrão para manipulação de dados.
  • DataContext Config:

    • O comando também cria os arquivos DataContext/config.ts e DataContext/index.ts.
      • config.ts define a estrutura dos dados e suas configurações.
      • index.ts implementa o provedor de dados utilizando as informações do arquivo de configuração.
  • Controllers Index:

    • O comando cria o arquivo controllers/index.ts que exporta uma variável controllers contendo instâncias de todos os controllers da aplicação. Exemplo:

      // Arquivo: controllers/index.ts
      
      import CustomerController from "./CustomerController";
      import SupplierController from "./SupplierController";
      import UserController from "./UserController";
      
      export const controllers = {
        customer: new CustomerController(),
        supplier: new SupplierController(),
        user: new UserController(),
      };

2.2 Criação Rápida de Controllers

  • Para simplificar a criação de controllers, você pode utilizar a CLI hesto-cli. Após instalá-la globalmente, execute o seguinte comando para criar um novo controller:

    hesto create:controller <NOME_DO_CONTROLLER>

    Substitua <NOME_DO_CONTROLLER> pelo nome desejado para o novo controller. Exemplo: hesto create:controller User

Passo 3: Configuração do Contexto de Dados

No arquivo contexts/DataContext/config.ts, você define a estrutura dos dados que o contexto vai lidar e configura como esses dados serão recuperados e manipulados. Utilize a interface Values para definir os tipos de dados. Exemplo:

// Arquivo: contexts/DataContext/config.ts

import * as NFD from 'nextjs-firebase-data';
import { controllers } from 'controllers';
import { routes } from 'constants/routes';

import { Customer } from 'models/Customer';
import { Supplier } from 'models/Supplier';
import { User } from 'models/User';

export interface Values {
  customers: NFD.Data<Customer>;
  suppliers: NFD.Data<Supplier>;
  users: NFD.Data<User>;
}

export type Payload = {
  storeId: string;
  branchId: string;
};

export const setup: NFD.Setup<Values, Payload> = {
  // Configuração para dados de clientes
  customers: {
    ref: 'customers', // Referência (ilustrativo)
    controller: ({ storeId }) => controllers.customer.store(storeId),
    routes: [routes.from('dashboard.services.orders.order'), routes.from('dashboard.customers')],
  },
  // Configuração para dados de fornecedores
  suppliers: {
    ref: 'suppliers', // Referência (ilustrativo)
    controller: async ({ storeId }) => controllers.supplier.store(storeId),
    routes: [routes.from('dashboard.suppliers')],
  },
  // Configuração para dados de usuários
  users: {
    ref: 'users', // Referência (ilustrativo)
    controller: controllers.user,
    routes: ['*'],
  },
};

Passo 3: Implementação do Provedor de Dados

No arquivo contexts/DataContext/index.tsx, implemente o provedor de dados utilizando as informações configuradas em config.ts. Este provedor utiliza nextjs-firebase-data para gerenciar os dados em tempo real.

// Arquivo: contexts/DataContext/index.tsx

import * as NFD from 'nextjs-firebase-data';
import { useAuth } from '../AuthContext';
import { useStore } from '../StoreContext';
import { Values, Payload, setup } from './config';

interface DataProviderProps {
  children: JSX.Element | React.ReactNode;
}

export function DataProvider(props: DataProviderProps): JSX.Element {
  const auth = useAuth();
  const store = useStore();

  return (
    <NFD.DataProvider<Values, Payload>
      isAllowed={auth.isAuthenticated}
      payload={{
        storeId: store.data?.id ?? '',
        branchId: store.branches.current?.id ?? '',
      }}
      setup={setup}
    >
      {props.children}
    </NFD.DataProvider>
  );
}

export const useData = (): NFD.DataContextData<Values> => NFD.useNFD();

Passo 4: Exemplo de Controller

Crie controllers para manipular os dados. Eles podem estender BaseController que fornece métodos padrão como create, get, index, on, delete, e update. Exemplo:

// Arquivo: controllers/CustomerController.ts

import { BaseController } from './BaseController';
import { Customer } from 'models/Customer';
import { app } from 'config/firebase';

class CustomerController {
  store(storeId: string) {
    const baseDbPath = `customers/${storeId}`;
    return new BaseController.rtdb<Customer>(baseDbPath, app);
  }
}

export default CustomerController;