Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Exporta os módulos necessários
- module.exports = function (fastify, opts, next) {
- //Cria uma rota para uma requisição POST ,rota definida como /related
- fastify.post('/related', function (request, reply) {
- //Cria uma função search que irá fazer uma busca no elasticsearch
- const search = (index, body) => this.elasticsearch.search({ index, body });
- body(function(body){
- //faz uma busca por publishers
- search('publishers', body).then((results) => {
- resultado(results);
- });
- });
- });
- next();
- };
- function insereArray(urls,titles,images,descriptions,itens,callback){
- for (const i in titles) {
- const url = urls[i];
- const title = titles[i];
- const image = images[i];
- const description = descriptions[i];
- itens.push({
- title,
- link: url,
- image,
- description,
- });
- }
- callback(itens);
- }
- function resultado(results){
- const itens = [];
- const urls = [];
- const titles = [];
- const images = [];
- const descriptions = [];
- for (let i = 0; i < results.hits.hits.length; i++) {
- //Cria uma regex para substituir as palavras More ou Mais
- regexReplace = '/(More|Mais)/';
- //Variavel que recebe os valores vindo de results.hits.hits[indice do for]._source.description
- const description = results.hits.hits[
- i
- ]._source.description.replace(regexReplace, '');
- //verifica se no array titles contém o elemento results.hits.hits
- if (!titles.includes(results.hits.hits[i]._source.title)) {
- //adiciona o valor do resultado da busca aos arrays titles ,,urls ,images e descriptions
- titles.push(results.hits.hits[i]._source.title);
- urls.push(results.hits.hits[i]._source.url);
- images.push(results.hits.hits[i]._source.image);
- descriptions.push(description);
- }
- if (titles.length == 5) {
- break;
- }
- }
- //função para inserir os dados no array itens
- insereArray(urls,titles,images,descriptions,itens,function(itens){
- //retorna os itens
- reply.send(itens);
- });
- }
- function body(callback){
- const body = {
- size: 10,
- from: 0,
- _source: ['title', 'url', 'image', 'description'],
- query: {
- bool: {
- must: [
- {
- query_string: {
- query: `(content:${
- request.body.term
- }) AND (domain:*${request.body.domain}*)`,
- },
- },
- ],
- },
- },
- };
- callback(body);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement