React 引入 firebase 埋点数据

1,140 阅读2分钟

1.引入方式:

https://firebase.google.com/docs/web/setup?authuser=1 
参照官方提供文档:

image.png

image.png

示例教学都在如图位置:firebase.google.com/docs/refere…

2.firebase的config配置

image.png

引用配置时,需要先创建自己的项目,创建的过程就不再介绍了。

将配置资料copy到1步骤的中初始化,就用可已连接到firebase了。这是其中的一种引入方式,还有一种可以在public下的index.html中 直接使用script 引入第三方cdn。

当项目引入完firebase之后,可以直接在分析页面看到一些默认就存在的分析报告:

image.png

上述三个模块就是对于页面事件的一个简易分析,其中streamView只会记入30分种的数据。

默认事件是由谷歌提供,我们同时可以定制自己的事件,以及使用谷歌提供的三种数据库(实时数据库,存储桶文件库,文档库)类似mongodb的数据格式。

文档中都有一些基础的使用方法,这里我简单的摘取部分。

import { initializeApp } from 'firebase/app'
import { EmailAuthProvider } from 'firebase/auth'
import { getStorage, ref, uploadBytes } from 'firebase/storage'
import {
  getFirestore,
  collection,
  getDocs,
  addDoc,
} from 'firebase/firestore/lite'
import {
  getAuth,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  onAuthStateChanged,
  signInWithCustomToken,
  signInAnonymously,
} from 'firebase/auth'
import { getPerformance } from 'firebase/performance'
import { trace } from 'firebase/performance'
import { getAnalytics, logEvent } from 'firebase/analytics'

//这里的firebaseConfig使用自己项目的配置

// firebase实例对象
export const firebaseApp = initializeApp(firebaseConfig)

// 邮件校验方式
export const loginByEmail = (email: string, password: string) => {
  EmailAuthProvider.credential(email, password)
}

// 文档记录库 cloudFirebase
const db = getFirestore(firebaseApp)

/* @params db firebase对象
   @params string 文档key
   function 获取cloudFirebase数据
*/
export const getCities = async () => {
  const citiesCol = collection(db, 'users')
  const citySnapshot = await getDocs(citiesCol)
  const cityList = citySnapshot.docs.map((doc) => doc.data())
  return cityList
}

// 添加数据☞ cloud Firebase
export const addDataToCFirebase = async () => {
  try {
    const docRef = await addDoc(collection(db, 'users'), {
      name: 'bbbb',
      country: 'Japan',
    })
    console.log('Document written with ID: ', docRef.id)
  } catch (e) {
    console.error('Error adding document: ', e)
  }
}

// 性能监控
const perf = getPerformance(firebaseApp)

// 插入代码 监控时间
const t = trace(perf, 'CUSTOM_TRACE_NAME')
// t.start()
// t.stop()

// 文件存储桶 cloud storage
export const FileStore = getStorage(firebaseApp)

// 应用指向存储桶的目录
export const imagesRef1 = ref(FileStore, 'file')

// 文件上传
export const uploadFileToBucket = (file: File) => {
  t.start()

  // Code that you want to trace
  // ...
  uploadBytes(imagesRef1, file).then((snapshot) => {
    console.log('Uploaded a blob or file!')
  })
  t.stop()
}

const auth = getAuth()
// 登录获取权限   创建用户的方法:createUserWithEmailAndPassword
export const loginAuth = (email: string, password: string) => {
  signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user
      console.log(user)
    })
    .catch((error) => {
      const errorCode = error.code
      const errorMessage = error.message
    })
}

// 注册账号
export const register = (email: string, password: string) => {
  createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user
      console.log(user)
      // ...
    })
    .catch((error) => {
      const errorCode = error.code
      const errorMessage = error.message
      // ..
    })
}
// 使用token登录
export const loginFirebaseByToken = (token: string) => {
  signInWithCustomToken(auth, token)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user
      console.log(user)

      // ...
    })
    .catch((error) => {
      const errorCode = error.code
      const errorMessage = error.message
      // ...
    })
}

// 获得监视对象
export const analytics = getAnalytics(firebaseApp)

// 上报事件
export class LogEvevtClass {
  static logEventTest = (
    EventName: string,
    sreenName: string,
    userDeatil?: string | undefined,
    extra?: object
  ) => {
    logEvent(analytics, EventName as string, {
      firebase_screen: sreenName,
      userDeatil: userDeatil,
      ...extra,
    })
  }
}

// 客户端检索token
export const auth2 = async () => {
  await getAuth()
    .currentUser?.getIdToken(true)
    .then((idToken) => {
      console.log(idToken)
    })
    .catch(function (error) {
      // Handle error
      console.log(error)
    })
}

//  匿名登录
export const loginBynoName = () => {
  signInAnonymously(auth)
    .then(() => {
      // Signed in..
      console.log('kkk')
    })
    .catch((error) => {
      const errorCode = error.code
      const errorMessage = error.message
      // ...
    })
}

// 获取匿名登录者信息
export const getnoNameDeatil = () => {
  onAuthStateChanged(auth, (user) => {
    if (user) {
      const uid = user.uid
    } else {
      // User is signed out
    }
  })
}