From 102254ee49a78464e67140b7cc4592105de8a547 Mon Sep 17 00:00:00 2001 From: Florrie Date: Mon, 19 Nov 2018 23:18:04 -0400 Subject: Experimental 'explore users' page --- index.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'index.js') diff --git a/index.js b/index.js index 361803b..24e8454 100755 --- a/index.js +++ b/index.js @@ -88,6 +88,19 @@ const compareArr = (a1, a2) => a1.length === a2.length && a1.every((x, i) => typ const filterHTML = text => text.replace(//g, '>') const pluralize = (word, n) => n === 1 ? word : word + 's' +function shuffle(array) { + // Stolen :) https://stackoverflow.com/a/2450976/4633828 + let currentIndex = array.length + while (currentIndex !== 0) { + const randomIndex = Math.floor(Math.random() * currentIndex) + currentIndex -= 1 + const temporaryValue = array[currentIndex] + array[currentIndex] = array[randomIndex] + array[randomIndex] = temporaryValue + } + return array +} + const templates = { user: username => `${username}`, project: (name, id) => `${filterHTML(name.trim())}`, @@ -295,6 +308,22 @@ const getData = function(request) { }) } +const explore = { + users: async () => { + const getUrl = mode => { + const limit = Math.ceil(Math.random() * 40) + const offset = Math.floor(Math.random() * 400) + return `https://api.scratch.mit.edu/explore/projects?mode=${mode}&limit=${limit}&offset=${offset}` + } + + const fetchResults = await Promise.all(['recent', 'trending', 'popular'].map(m => fetch(getUrl(m)).then(res => res.json()))) + console.log(fetchResults) + const projects = fetchResults.reduce((acc, arr) => acc.concat(arr), []) + const selected = shuffle(projects).slice(0, 15) + return selected.map(project => project.author) + } +} + const handleRequest = async (request, response) => { const { pathname, query } = url.parse(request.url) const queryData = qs.parse(query) @@ -558,6 +587,19 @@ const handleRequest = async (request, response) => { } } + if (urlParts[0] === 'explore') { + if (compareArr(urlParts.slice(1), ['users'])) { + const users = await explore.users() + + return page(request, response, fixWS` +

Explore Users

+

Here are some randomly picked users to check out:

+

${users.map(u => templates.user(u.username, u.id)).join(', ')}

+

(Users are randomly selected from the authors of a variety of recent and trending projects.)

+ `) + } + } + if (compareArr(urlParts, ['style.css'])) { response.writeHead(200, { 'Content-Type': 'text/css' -- cgit 1.3.0-6-gf8a5