diff options
author | Florrie <towerofnix@gmail.com> | 2018-11-19 23:18:04 -0400 |
---|---|---|
committer | Florrie <towerofnix@gmail.com> | 2018-11-19 23:18:04 -0400 |
commit | 102254ee49a78464e67140b7cc4592105de8a547 (patch) | |
tree | bb9fc02d0761662ddbcd86c47f7857ef19fb0333 | |
parent | 89a6005e3cf0e1b50cbd953b0884f63ed629a37d (diff) |
Experimental 'explore users' page
-rwxr-xr-x | index.js | 42 |
1 files changed, 42 insertions, 0 deletions
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, '<').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 => `<a href="/users/${username}">${username}</a>`, project: (name, id) => `<a href="/projects/${id}">${filterHTML(name.trim())}</a>`, @@ -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` + <h1>Explore Users</h1> + <p>Here are some randomly picked users to check out:</p> + <p>${users.map(u => templates.user(u.username, u.id)).join(', ')}</p> + <p>(Users are randomly selected from the authors of a variety of recent and trending projects.)</p> + `) + } + } + if (compareArr(urlParts, ['style.css'])) { response.writeHead(200, { 'Content-Type': 'text/css' |