From a0d602bcabfafef202a80d2dcdb1bf4296679aec Mon Sep 17 00:00:00 2001 From: Daniel Lugo Date: Thu, 22 Jul 2021 17:00:21 -0400 Subject: [PATCH] Remove unused code/routes --- services/gunDB/contact-api/getters/feed.js | 89 --------- services/gunDB/contact-api/getters/index.js | 22 --- services/gunDB/contact-api/getters/wall.js | 208 -------------------- src/routes.js | 119 ----------- 4 files changed, 438 deletions(-) delete mode 100644 services/gunDB/contact-api/getters/feed.js delete mode 100644 services/gunDB/contact-api/getters/wall.js diff --git a/services/gunDB/contact-api/getters/feed.js b/services/gunDB/contact-api/getters/feed.js deleted file mode 100644 index ba4704ce..00000000 --- a/services/gunDB/contact-api/getters/feed.js +++ /dev/null @@ -1,89 +0,0 @@ -/** - * @format - */ -//@ts-ignore -const Common = require('shock-common') -const isFinite = require('lodash/isFinite') -const shuffle = require('lodash/shuffle') -const R = require('ramda') - -const { asyncFilter } = require('../../../../utils') - -const Follows = require('./follows') -const Wall = require('./wall') - -/** - * @param {number} numberOfPublicKeyGroups - * @param {number} pageRequested - * @returns {[ number , number ]} - */ -const calculateWallRequest = (numberOfPublicKeyGroups, pageRequested) => { - // thanks to sebassdc - - return [ - (pageRequested - 1) % numberOfPublicKeyGroups, - Math.ceil(pageRequested / numberOfPublicKeyGroups) - ] -} - -/** - * @param {number} page - * @throws {TypeError} - * @throws {RangeError} - * @returns {Promise} - */ -//@returns {Promise} -const getFeedPage = async page => { - if (!isFinite(page)) { - throw new TypeError(`Please provide an actual number for [page]`) - } - - if (page <= 0) { - throw new RangeError(`Please provide only positive numbers for [page]`) - } - - const subbedPublicKeys = Object.values(await Follows.currentFollows()).map( - f => f.user - ) - - if (subbedPublicKeys.length === 0) { - return [] - } - - // say there are 20 public keys total - // page 1: page 1 from first 10 public keys - // page 2: page 1 from second 10 public keys - // page 3: page 2 from first 10 public keys - // page 4: page 2 from first 10 public keys - // etc - // thanks to sebassdc (github) - - const pagedPublicKeys = R.splitEvery(10, shuffle(subbedPublicKeys)) - - const [publicKeyGroupIdx, pageToRequest] = calculateWallRequest( - pagedPublicKeys.length, - page - ) - - const publicKeysRaw = pagedPublicKeys[publicKeyGroupIdx] - const publicKeys = await asyncFilter( - publicKeysRaw, - // reject public keys for which the page to request would result in an out - // of bounds error - async pk => pageToRequest <= (await Wall.getWallTotalPages(pk)) - ) - - const fetchedPages = await Promise.all( - publicKeys.map(pk => Wall.getWallPage(pageToRequest, pk)) - ) - - const fetchedPostsGroups = fetchedPages.map(wp => Object.values(wp.posts)) - const fetchedPosts = R.flatten(fetchedPostsGroups) - const sortered = R.sort((a, b) => b.date - a.date, fetchedPosts) - - return sortered -} - -module.exports = { - getFeedPage -} diff --git a/services/gunDB/contact-api/getters/index.js b/services/gunDB/contact-api/getters/index.js index 81ea8dc2..3f0cdba6 100644 --- a/services/gunDB/contact-api/getters/index.js +++ b/services/gunDB/contact-api/getters/index.js @@ -6,8 +6,6 @@ const Common = require('shock-common') const Key = require('../key') const Utils = require('../utils') -const Wall = require('./wall') -const Feed = require('./feed') const User = require('./user') const { size } = require('lodash') @@ -30,22 +28,6 @@ exports.currentOrderAddress = async pub => { return currAddr } -/** - * @param {string} pub - * @returns {Promise} - */ -exports.userToIncomingID = async pub => { - const incomingID = await require('../../Mediator') - .getUser() - .get(Key.USER_TO_INCOMING) - .get(pub) - .then() - - if (typeof incomingID === 'string') return incomingID - - return null -} - /** * @returns {Promise} */ @@ -139,8 +121,4 @@ module.exports.getMyUser = getMyUser module.exports.getUserInfo = getUserInfo module.exports.Follows = require('./follows') -module.exports.getWallPage = Wall.getWallPage -module.exports.getWallTotalPages = Wall.getWallTotalPages - -module.exports.getFeedPage = Feed.getFeedPage module.exports.getAnUser = User.getAnUser diff --git a/services/gunDB/contact-api/getters/wall.js b/services/gunDB/contact-api/getters/wall.js deleted file mode 100644 index 96c7fd70..00000000 --- a/services/gunDB/contact-api/getters/wall.js +++ /dev/null @@ -1,208 +0,0 @@ -/** - * @format - */ -const Common = require('shock-common') -const pickBy = require('lodash/pickBy') -const size = require('lodash/size') -const mapValues = require('lodash/mapValues') - -const Utils = require('../utils') -const Key = require('../key') - -const User = require('./user') - -/** - * @param {string=} publicKey - * @returns {Promise} - */ -const getWallTotalPages = async publicKey => { - const totalPages = await Utils.tryAndWait( - (gun, u) => { - /** - * @type {import('../SimpleGUN').GUNNode} - */ - let user = u - - if (publicKey && u._.sea.pub !== publicKey) { - user = gun.user(publicKey) - } - - return user - .get(Key.WALL) - .get(Key.NUM_OF_PAGES) - .then() - }, - v => typeof v !== 'number' - ) - - return typeof totalPages === 'number' ? totalPages : 0 -} - -/** - * @param {number} page - * @param {string=} publicKey - * @throws {TypeError} - * @throws {RangeError} - * @returns {Promise} - */ -////@returns {Promise} -const getWallPage = async (page, publicKey) => { - const totalPages = await getWallTotalPages(publicKey) - - if (page === 0) { - throw new RangeError( - `Page number cannot be zero, only positive and negative integers are allowed.` - ) - } - - const empty = { - count: 0, - posts: {} - } - - if (totalPages === 0) { - return empty - } - - const actualPageIdx = page < 0 ? totalPages + page : page - 1 - - if (actualPageIdx > totalPages - 1) { - throw new RangeError(`Requested a page out of bounds`) - } - - /** - * @type {number} - */ - // @ts-ignore - const count = await Utils.tryAndWait( - (g, u) => { - /** - * @type {import('../SimpleGUN').GUNNode} - */ - let user = u - - if (publicKey && u._.sea.pub !== publicKey) { - user = g.user(publicKey) - } - - return user - .get(Key.WALL) - .get(Key.PAGES) - .get(actualPageIdx.toString()) - .get(Key.COUNT) - .then() - }, - v => typeof v !== 'number' - ) - - if (count === 0) { - return empty - } - - /** - * We just use it so Common.Schema.isWallPage passes. - */ - const mockUser = await User.getMyUser() - - /* - * @type {Common.SchemaTypes.WallPage} - */ - //@ts-ignore - const thePage = await Utils.tryAndWait( - (g, u) => { - /** - * @type {import('../SimpleGUN').GUNNode} - */ - let user = u - - if (publicKey && u._.sea.pub !== publicKey) { - user = g.user(publicKey) - } - - return new Promise(res => { - // forces data fetch - user - .get(Key.WALL) - .get(Key.PAGES) - .get(actualPageIdx.toString()) - // @ts-ignore - .load(() => {}) - - process.nextTick(() => { - user - .get(Key.WALL) - .get(Key.PAGES) - .get(actualPageIdx.toString()) - // @ts-ignore - .load(res) - }) - }) - }, - maybePage => { - // sometimes load() returns an empty object on the first call - if (size(/** @type {any} */ (maybePage)) === 0) { - return true - } - - const page = /** @type {Common.Schema.WallPage} */ (maybePage) - - if (typeof page.count !== 'number') { - return true - } - - // removes 'unused' initializer and aborted writes - page.posts = pickBy(page.posts, v => v !== null) - - // .load() sometimes doesn't load all data on first call - if (size(page.posts) === 0) { - return true - } - - // Give ids based on keys - page.posts = mapValues(page.posts, (v, k) => ({ - ...v, - id: k - })) - - page.posts = mapValues(page.posts, v => ({ - ...v, - // isWallPage() would otherwise not pass - author: mockUser - })) - - return !Common.Schema.isWallPage(page) - } - ) - - const clean = { - ...thePage - } - - for (const [key, post] of Object.entries(clean.posts)) { - // delete unsuccessful writes - if (post === null) { - delete clean.posts[key] - clean.count-- - } else { - post.author = publicKey - ? // eslint-disable-next-line no-await-in-loop - await User.getAnUser(publicKey) - : // eslint-disable-next-line no-await-in-loop - await User.getMyUser() - post.id = key - } - } - - if (!Common.Schema.isWallPage(clean)) { - throw new Error( - `Fetched page not a wall page, instead got: ${JSON.stringify(clean)}` - ) - } - - return clean -} - -module.exports = { - getWallTotalPages, - getWallPage -} diff --git a/src/routes.js b/src/routes.js index 27879828..ac04a05a 100644 --- a/src/routes.js +++ b/src/routes.js @@ -2248,41 +2248,6 @@ module.exports = async ( } }) - app.get(`/api/gun/wall/:publicKey?`, async (req, res) => { - try { - const { page } = req.query - const { publicKey } = req.params - - const pageNum = Number(page) - - if (!isARealUsableNumber(pageNum)) { - return res.status(400).json({ - field: 'page', - errorMessage: 'Not a number' - }) - } - - if (pageNum === 0) { - return res.status(400).json({ - field: 'page', - errorMessage: 'Page must be a non-zero integer' - }) - } - - const totalPages = await GunGetters.getWallTotalPages(publicKey) - const fetchedPage = await GunGetters.getWallPage(pageNum, publicKey) - - return res.status(200).json({ - ...fetchedPage, - totalPages - }) - } catch (err) { - return res.status(500).json({ - errorMessage: err.message - }) - } - }) - app.post(`/api/gun/wall/`, async (req, res) => { try { const { tags, title, contentItems, enableTipsOverlay } = req.body @@ -2438,90 +2403,6 @@ module.exports = async ( ap.put(`/api/gun/follows/:publicKey`, apiGunFollowsPut) ap.delete(`/api/gun/follows/:publicKey`, apiGunFollowsDelete) - /** - * @type {RequestHandler<{}>} - */ - const apiGunFeedGet = async (req, res) => { - try { - const MAX_PAGES_TO_FETCH_FOR_TRY_UNTIL = 4 - - const { page: pageStr } = req.query - - /** - * Similar to a "before" query param in cursor based pagination. We call - * it "try" because it is likely that this item lies beyond - * MAX_PAGES_TO_FETCH_FOR_TRY_UNTIL in which case we gracefully just send - * 2 pages and 205 response. - */ - // eslint-disable-next-line prefer-destructuring - const before = req.query.before - - if (pageStr) { - const page = Number(pageStr) - - if (!isARealUsableNumber(page)) { - return res.status(400).json({ - field: 'page', - errorMessage: 'page must be a number' - }) - } - - if (page < 1) { - return res.status(400).json({ - field: page, - errorMessage: 'page must be a positive number' - }) - } - - return res.status(200).json({ - posts: await GunGetters.getFeedPage(page), - page - }) - } - - if (before) { - const pages = range(1, MAX_PAGES_TO_FETCH_FOR_TRY_UNTIL) - const promises = pages.map(p => GunGetters.getFeedPage(p)) - - let results = await Promise.all(promises) - - const idxIfFound = results.findIndex(pp => - pp.some(p => p.id === before) - ) - - if (idxIfFound > -1) { - results = results.slice(0, idxIfFound + 1) - - const posts = flatten(results) - - return res.status(200).json({ - posts, - page: idxIfFound - }) - } - - // we couldn't find the posts leading up to the requested post - // (try_until) Let's just return the ones we found with together with a - // 205 code (client should refresh UI) - - return res.status(205).json({ - posts: results[0] || [], - page: 1 - }) - } - - return res.status(400).json({ - errorMessage: `Must provide at least a page or a try_until query param.` - }) - } catch (err) { - return res.status(500).json({ - errorMessage: err.message || 'Unknown error inside /api/gun/follows/' - }) - } - } - - ap.get(`/api/gun/feed`, apiGunFeedGet) - /** * @type {RequestHandler<{}>} */