English 中文(简体)
store data in memory with nestjs
原标题:

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests.

I have created a products.service.ts file with the function getAllData() that fetch some data and creates a new array that is asigned to the variable products (wich is the data I m trying to persist). This function is called when the app is initialized (I know this works becouse when I run the app the console.log(this.products) inside the function shows data.

This is my products.service.ts code:

import { Injectable } from  @nestjs/common ;

@Injectable()
export class ProductsService {
  private products: any[] = [];

  getProducts(): any[] {
    //empty
    console.log(this.products); 
    return this.products;
  }

  async getAllProducts(): Promise<any[]> {
    const categories = await this.getProductsCategories();
    const productsPromises = categories.categories.map(async (category) => {
        const products = await this.getProductsByCategory(category.strCategory);
        const modifiedProducts = products.meals.map((product) => {
            ....
        });
        return modifiedProducts;
      });
      
      const products = await Promise.all(productsPromises);
      const flattenedProducts = products.flat();

      this.products = flattenedProducts;
      //shows data
      console.log(this.products) 
      
      return flattenedProducts;
    }

  async getProductsCategories(): Promise<any>{
    try{
      const apiURL =  https://www.themealdb.com/api/json/v1/1/categories.php ;
      const apiResponse = await fetch(apiURL);
      const categories = await apiResponse.json(); 

      return categories;
    }
    catch(e){
      throw new Error( Error while fetching products );
    }
  }
  async getProductsByCategory(category: string): Promise<any> {
    try {
      const apiURL = `https://www.themealdb.com/api/json/v1/1/filter.php?c=${category}`;
      const apiResponse = await fetch(apiURL);
      const products = await apiResponse.json();

      return products;
    } catch (e) {
      throw new Error( Error while fetching products by category );
    }
  }
}

The function getProducts() is called in my products.controller.ts file when an http request is done in the route /products but the products array is empty:

import { Controller, Get, Param } from  @nestjs/common ;
import { ProductsService } from  ./products.service ;

@Controller( products )
export class ProductsController {
    constructor(private readonly ProductsService: ProductsService) {}

 @Get( / )
    async getAllProducts(): Promise<any[]> {
        const products = await this.ProductsService.getProducts();

        return products;
     }
 }

Any idea why the products variable is empty when I make the request ? It should have the data created with getAllProducts() as this function is called onModuleInit

问题回答

暂无回答




相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签