Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
2.4 kB
2
Indexable
Never
  async getCoinsList(req, res, next) {
    try {
      const page = req.query.page || 1;
      const limit = req.query.limit || 10;
      const searchParam = req.query.search;
      const result = await handleGetCoinList(page, limit, searchParam);
      return res.status(200).json(result);
    } catch (error) {
      next(error);
    }
  }


// model
  async handleGetCoinList(page, limit, searchParam) {
    console.log("Received page:", page);
    console.log("Received limit:", limit);
    console.log("Received searchParam:", searchParam);
    console.log("coin ->> test");

    // Convert page and limit to integers
    page = parseInt(page);
    limit = parseInt(limit);

    if (isNaN(page) || isNaN(limit)) {
      throw new Error("Page and limit must be valid numbers.");
    }

    return new Promise(async (resolve, reject) => {
      const client = await getAerospikeClient();
      var arr = [];
      let query = client.query(
        process.env.CLUSTER_NAME,
        process.env.SET_CRYPTO_COIN
      );
      const stream = query.foreach();

      stream.on("data", function (record) {
        arr.push(record.bins);
      });

      stream.on("error", function (error) {
        reject(error.message);
      });

      stream.on("end", function () {
        // Filter the array based on searchParam
        if (searchParam && searchParam.trim() !== "") {
          const lowercasedSearchParam = searchParam.trim().toLowerCase();
          arr = arr.filter(
            (coin) =>
              coin.name.toLowerCase().includes(lowercasedSearchParam) ||
              coin.symbol.toLowerCase().includes(lowercasedSearchParam)
          );
        }

        // Sort the array by market_cap_rank
        arr = arr.sort((a, b) => a.market_cap_rank - b.market_cap_rank);

        // Adjust the page index and calculate start and end indices
        var start = (page - 1) * limit; // Adjusted for user-friendly page indexing
        var noPages = Math.ceil(arr.length / limit);
        var end = start + limit;
        console.log(`Start: ${start}, End: ${end}, Total Pages: ${noPages}`);

        // Slice the array to get only the desired page
        arr = arr.slice(start, end);

        // Resolve the promise with the sliced array
        resolve(arr);
      });
    });
  }
Leave a Comment