使用node-cache,无法在使用Firebase作为后端设置后获取数据

f5emj3cl  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(119)

我正在构建自己的后端API,使用Firebase作为后端,所以我想使用node-cache缓存,但在我该高速缓存后,应该给予我一个真实的值,让我得到缓存响应,它一直给我未定义。
下面是我的缓存类:

import {injectable} from "inversify";
import * as NodeCache from "node-cache";
import {SearchDataFile} from "../../searching/domain/search_domian";

@injectable()
class Caching {
  private myCache:NodeCache;
  constructor() {
    this.myCache = new NodeCache({stdTTL: 7000, checkperiod: 120});
  }
  public get(key: string): SearchDataFile | undefined {
    return this.myCache.get(key);
  }

  public checkKeyAvailable(keyValue: string): boolean {
    return this.myCache.has(keyValue);
  }
  public set(key: string, data: SearchDataFile): boolean {
    return this.myCache.set(key, data, 3600);
  }
  public delete(key: string): string[] | undefined {
    return this.myCache.take(key);
  }
}

export default Caching;

这就是我使用它的地方:

/* eslint-disable max-len */
/* eslint-disable object-curly-spacing */
import {FirebaseUser} from "../../authentication/domain/userEntity";
import {SearchDataFile} from "../domain/search_domian";
import * as admin from "firebase-admin";
import {SearchServicesRepository} from "./crednetials/searchRepository";
import { injectable, inject } from "inversify";
import Caching from "../../core/application/cache";
import * as logger from "firebase-functions/logger";

@injectable()
export class SearchServiceImplementation implements SearchServicesRepository {
  constructor(@inject(Caching) private caching: Caching ) {}

  async getAlldata(): Promise<SearchDataFile> {
    const valueCheck = this.caching.get("allData");
    logger.debug(`the checking ==== ${valueCheck}`);
    if (valueCheck != undefined) {
      logger.debug(`the checking after check ==== ${valueCheck}`);
      //  const cachedDataFromDB:SearchDataFile = this.caching.get("allData") as SearchDataFile;
      return valueCheck;
    }
    const usersData = await admin.firestore().collection("users").get();
    const firbaseusers:FirebaseUser[] = usersData.docs.map((users)=> {
      const userData = users.data() as FirebaseUser;
      return userData;
    });
    const data:SearchDataFile = {
      users: firbaseusers,
      community: [],
      library: [],
      news: [],
      forum: [],
    };
    const value =this.caching.set("allData", data);
    logger.debug(`getAllData ${value}`);
    return data;
  }

  async search(searchTerm: string): Promise<SearchDataFile> {
    const valueCheck = this.caching.checkKeyAvailable("allData");
    logger.debug(`the checking if data is store in cache ${valueCheck}`);
    if (valueCheck) {
      const cachedDataFromDB:SearchDataFile = this.caching.get("allData") as SearchDataFile;
      logger.debug(`the data is store in cache ${cachedDataFromDB}`);
      const filteredUsers = cachedDataFromDB.users.filter((user) =>
        user.username.toLowerCase().includes(searchTerm.toLowerCase())
      );
      return {
        users: filteredUsers,
        community: [],
        library: [],
        news: [],
        forum: [],
      };
    }
    const usersData = await admin.firestore().collection("users").get();
    const firbaseusers:FirebaseUser[] = usersData.docs.map((users)=> {
      const userData = users.data() as FirebaseUser;
      return userData;
    });
    const filteredUsers = firbaseusers.filter((user) =>
      user.username.toLowerCase().includes(searchTerm.toLowerCase())
    );
    return {
      users: filteredUsers,
      community: [],
      library: [],
      news: [],
      forum: [],
    };
  }
}

我使用类SearchServicesRepository

/* eslint-disable max-len */
import {Request, Response} from "express";
import {myContainer} from "../../core/inversify_config";
import {TYPES} from "../../core/types";
import {SearchServicesRepository} from "../infastructure/crednetials/searchRepository";

export async function getAllFromDB(req: Request, res: Response,) {
  try {
    const getAllData = myContainer.get<SearchServicesRepository>(TYPES.SearchServicesRepository);
    const data = await getAllData.getAlldata();
    return res.status(200).send({message: "Succesfull", data});
  } catch (error) {
    return res.status(400).send(error);
  }
}

以下是相关的函数日志:

lhcgjxsq

lhcgjxsq1#

如果您使用Firebase作为后端,并在使用node-cache设置数据后遇到检索数据的问题,您可以探索一些潜在的原因和解决方案:
验证Firebase数据:确保您尝试从节点缓存中检索的数据已成功存储在Firebase中。您可以通过直接访问Firebase并确认数据的存在来仔细检查这一点。
检查缓存机制:检查节点缓存的实现,以确保缓存机制按预期工作。请确保该高速缓存中正确设置数据并使用适当的键检索数据。
确认缓存过期:node-cache允许您设置缓存项的过期时间。检查您在设置数据时是否指定了过期时间,并确保它与您的预期用途一致。如果该高速缓存在您检索数据之前过期,则它将不可用。
将缓存与Firebase同步:如果您使用Firebase作为主要数据源,使用节点缓存作为缓存层,则必须使它们保持同步。无论何时在Firebase中更新数据,都应该相应地更新该高速缓存以确保一致性。考虑使用Firebase的实时数据库或Cloud Firestore的更改侦听器来侦听更新并相应地更新该高速缓存。
优雅地处理缓存未命中:如果该高速缓存中找不到数据,则使用回退机制直接从Firebase检索数据。这确保了即使该高速缓存是空的或过时的,您仍然可以从后端检索数据。
调试和日志记录:添加适当的日志语句或调试机制来跟踪Firebase和node-cache之间的数据流。这可以帮助您识别数据检索过程中的任何问题或不一致。
通过解决这些问题,您应该能够排除故障并解决您在节点缓存和Firebase集成方面面临的问题。

相关问题