Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/scrape #17

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 1 addition & 19 deletions .env-template
Original file line number Diff line number Diff line change
@@ -1,26 +1,8 @@
# lista de eventos que no queremos que aparezcan (separados por coma)
# 19155277 = Infobyte (https://www.meetup.com/infobyte/)
BLACK_LIST=19155277

# 15 minutos de tiempo de vida para los pedidos cacheados
CACHE_EXPIRATION=900000

# 34 = Tecnología
# en el caso de querer usar más de 1, separarlos por coma
CATEGORIES=34

# latitud y longitud que apuntan a Cabildo y Juan B. Justo
LAT=-34.578175
LON=-58.426516

# https://secure.meetup.com/meetup_api/key/
MEETUP_API_KEY=1234567890

NODE_ENV=development

# rango en millas (partiendo desde latitud y longitud) que se va a tener en cuenta
# para buscar meetups
RADIUS=10

# lista de eventos a buscar que sabemos que no entran en el rango (separados por coma)
# WHITE_LIST=
RADIUS=10
24 changes: 2 additions & 22 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,39 +8,19 @@ const cache = require('memory-cache')
const microCors = require('micro-cors')
const { send } = require('micro')

const getEvents = require('./lib/get-events')
const getMeetups = require('./lib/get-meetups')
const scrapeEvents = require('./lib/scrape-events')

const blackList = process.env.BLACK_LIST ? process.env.BLACK_LIST.split(',') : []
durancristhian marked this conversation as resolved.
Show resolved Hide resolved
const cacheExpiration = parseInt(process.env.CACHE_EXPIRATION)
const cors = microCors({
allowMethods: ['GET']
})
const whiteList = process.env.WHITE_LIST ? process.env.WHITE_LIST.split(',') : []
durancristhian marked this conversation as resolved.
Show resolved Hide resolved

async function handler(req, res) {
try {
// si el resultado del API no fue previamente cacheado
if (!cache.get('data')) {
// obtenemos un array de meetups que corresponden al rango es búsqueda
const data = await getMeetups()
// filtramos los eventos que no queremos que aparezcan
.then(eventsList =>
eventsList.filter(event => !blackList.includes(event.id.toString()))
)
// agregamos los meetups que queremos que aparezcan que no entran en el rango de búsqueda
.then(meetups => meetups.concat(whiteList.map(m => ({ urlname: m }))))
// buscamos los eventos de esos meetups
.then(meetups => meetups.map(m => getEvents(m.urlname)))
// cuando obtengamos toda la información, vamos a tener un array de arrays,
// donde cada uno es una lista de eventos
.then(eventsProms => Promise.all(eventsProms))
// generamos un array de 1 solo nivel por medio de un reduce
// que solo concatena todos los eventos de los diferentes meetups
.then(eventsLists =>
eventsLists.reduce((output, events) => output.concat(events), [])
)

const data = await scrapeEvents()
// guardamos los datos en cache por el tiempo indicado por configuración
cache.put('data', data, cacheExpiration)
}
Expand Down
19 changes: 0 additions & 19 deletions lib/format-events.js

This file was deleted.

7 changes: 0 additions & 7 deletions lib/get-events.js

This file was deleted.

17 changes: 0 additions & 17 deletions lib/get-meetups.js

This file was deleted.

5 changes: 0 additions & 5 deletions lib/make-request.js

This file was deleted.

65 changes: 65 additions & 0 deletions lib/scrape-events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const cheerio = require('cheerio')
const got = require('got')
const moment = require('moment')
let yup = require('yup')

let schema = yup.array().of(
yup.object().shape({
date: yup.date().required(),
eventName: yup.string().required(),
eventLink: yup.string().url().required(),
place: yup.string()
})
)

module.exports = async function scrapeEvents() {
durancristhian marked this conversation as resolved.
Show resolved Hide resolved
try {
const { RADIUS } = process.env
const { body } = await got(
`https://www.meetup.com/es-ES/find/events/tech/?allMeetups=false&radius=${RADIUS}&userFreeform=buenos+ai&mcId=c1000296&mcName=Buenos+Aires%2C+AR`
)
const $ = cheerio.load(body)
const days = $('li.event-listing-container-li')
const dayInfo = $('li.date-indicator')
const eventsArray = []
days.each((dayIndex, li) => {
const events = $(li).find('ul.event-listing-container > li')
events.each((_, li) => {
$(li).each((_, e) => {
const eventDateElement = dayInfo.get(dayIndex)
let eventDate
if (eventDateElement) {
const {
'data-year': year,
'data-month': month,
'data-day': day
} = dayInfo.get(dayIndex).attribs
eventDate = `${year}-${month}-${day}`
} else {
eventDate = moment().format('YYYY-MM-DD')
}
eventsArray.push({
date:
moment.utc(
`${eventDate} ${$(e).find('div a').first().text().trim()}`,
'YYYY-MM-DD HH:mm'
),
eventName:
`${$(e).find('div[itemprop="location"]').text().trim()} - ${$(e).find('a.event span[itemprop="name"]').text().trim()}`,
eventLink: $(e).find('a.event').prop('href'),
place: ''
})
})
})
})
const isValid = schema.isValidSync(eventsArray)
console.log('schema valido: ', isValid)
if (isValid) {
return eventsArray
} else {
return []
}
} catch (e) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hagamos un console.error con el error, además de devolver el array vacío

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sino no vamos a saber por que rompe, que van a ser la mayoría de los casos

return []
}
}
Loading