From f0d24e479e79172738f7d0724e9f3c019f300f63 Mon Sep 17 00:00:00 2001 From: Sabrina Date: Tue, 14 May 2024 15:58:02 -0300 Subject: [PATCH] =?UTF-8?q?reutiliza=C3=A7=C3=A3o=20de=20fun=C3=A7=C3=A3o?= =?UTF-8?q?=20de=20find=20e=20encadeamento=20de=20promises?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FindOneByCollection.js | 60 +++++++------------ 1 file changed, 20 insertions(+), 40 deletions(-) diff --git a/website/src/services/FindOneByCollection/FindOneByCollection.js b/website/src/services/FindOneByCollection/FindOneByCollection.js index dcb20ab..156dc61 100644 --- a/website/src/services/FindOneByCollection/FindOneByCollection.js +++ b/website/src/services/FindOneByCollection/FindOneByCollection.js @@ -1,45 +1,25 @@ -import { React, Component } from "react"; -import { db, databaseRef, get } from "../../init-firebase"; +import FindAllByCollection from "../../services/FindAllByCollection/FindAllByCollection"; -const dbRef = databaseRef(db); - -//função async ou promise -// Promise: FindOneByCollection('elementsCollection').then(elementsArray) -// async: const elementsArray = await FindOneByCollection('elementsCollection') function FindOneByCollection(collection) { - return new Promise((resolve, reject) => { - try { - get(dbRef, collection).then((response) => { - if (response.exists()) { - let elements = response.val()[collection]; - let elementsArray = []; - - if ( - elements && - elements !== undefined && - elements !== null - ) { - if (typeof elements === "object") { - //loop para objeto - elementsArray = Object.keys(elements).map( - (key) => elements[key].form - ); - } - //console.log("Got data ", collection, elementsArray); - - const lastElement = - elementsArray[elementsArray.length - 1]; - resolve(lastElement); - } - } else { - //console.log("No data available ", collection); - resolve(null); - } - }); - } catch (error) { - reject(error); - } - }); + return FindAllByCollection(collection) + .then(elements => { + return elements[elements.length - 1] + }) + .catch((err) => { + console.error(err); + // throw new Error(); + return null; + }); } +// Async: FindLastOneByCollection +// async function FindLastOneByCollection(collection) { +// try { +// const elements = await FindAllByCollection(collection) +// return elements[elements.length - 1]; +// } catch(err) { +// return null; +// } +// } + export default FindOneByCollection;