UNPKG

giganet_conecta

Version:

Aplicação com o fim de facilitar conexões com APi's e Banco de Dados (MySql & Mongo).

112 lines (98 loc) 2.88 kB
class DocumentsService { constructor(client) { this.client = client; } // Criar um documento async createDocument({ index, body }) { try { if (!index) { throw new Error("É necessário informar o índice do documento"); } return await this.client.index({ index, body, refresh: true }); } catch (error) { throw new Error(`Erro ao criar documento (${index}): ${error}`); } } // Buscar todos os documentos de um índice async getAllDocuments({ index, params, query }) { try { let response = await this.client.search({ index, scroll: "1m", ...(params && { ...params }), ...(query && { body: { query } }), }); let resultados = response.hits.hits.map((doc) => ({ id: doc._id, ...doc._source, })); let scrollId = response._scroll_id; while (response.hits.hits.length > 0) { response = await this.client.scroll({ scroll_id: scrollId, scroll: "1m", }); resultados = resultados.concat( response.hits.hits.map((doc) => ({ id: doc._id, ...doc._source, })) ); scrollId = response._scroll_id; } return resultados; } catch (error) { throw new Error(`Erro ao buscar documentos (${index}): ${error}`); } } async getDocumentById({ index, id }) { try { const response = await this.client.get({ index, id }); return { id: response._id, ...response._source, }; } catch (error) { throw new Error(`Erro ao buscar documento por ID (${index}): ${error}`); } } // Buscar documentos filtrando por chave e valor async getDocumentByKeyValue({ index, key, value }) { try { const response = await this.client.search({ index, body: { query: { match: { [key]: value } }, }, }); return response.hits.hits; } catch (error) { throw new Error( `Erro ao buscar documentos por chave e valor (${index}): ${error}` ); } } // Deletar um documento por ID async deleteDocument({ index, id }) { try { return await this.client.delete({ index, id, refresh: true }); } catch (error) { throw new Error(`Erro ao deletar documento (${index}): ${error}`); } } // Deletar todos os documentos de um índice async deleteAllDocument({ index }) { try { return await this.client.deleteByQuery({ index, body: { query: { match_all: {} } }, refresh: true, }); } catch (error) { throw new Error(`Erro ao deletar documentos (${index}): ${error}`); } } } module.exports = { DocumentsService, };