Merge pull request #95 from shocknet/follows-gun-bug-fix

circumvent gun.load() bug
This commit is contained in:
Daniel Lugo 2020-06-27 18:49:28 -04:00 committed by GitHub
commit fc375be37f

View file

@ -1,6 +1,11 @@
/**
* @format
*/
const Common = require('shock-common') const Common = require('shock-common')
const Logger = require('winston') const Logger = require('winston')
const size = require('lodash/size')
const Utils = require('../utils')
const Key = require('../key') const Key = require('../key')
/** /**
@ -8,43 +13,47 @@ const Key = require('../key')
*/ */
/** /**
* @throws {TypeError}
* @returns {Promise<Record<string, Common.Schema.Follow>>} * @returns {Promise<Record<string, Common.Schema.Follow>>}
*/ */
exports.currentFollows = () => { exports.currentFollows = async () => {
const user = require('../../Mediator').getUser() /**
* @type {Record<string, Common.Schema.Follow>}
return new Promise(res => { */
user.get(Key.FOLLOWS).load(data => { const raw = await Utils.tryAndWait(
if (typeof data !== 'object' || data === null) { // @ts-ignore
Logger.warn( (_, user) => new Promise(res => user.get(Key.FOLLOWS).load(res)),
`GunDb -> getters -> currentFollows() -> Current follows data as fetched from gun is not an object but ${typeof data}. This can happen if Gun lost its cache and it's still retrieving data from the network.` v => {
) if (typeof v !== 'object' || v === null) {
res({}) return true
return
} }
const rejected = Object.entries(data).filter( if (size(v) === 0) {
([_, follow]) => !Common.Schema.isFollow(follow) return true
)
rejected.forEach(([key, item]) => {
// expected when unfollowed
if (item !== null) {
Logger.warn(
`GunDb -> getters -> currentFollows() -> Item not conforming to schema found inside follows data. Key: ${key}, item: ${JSON.stringify(
item
)}.`
)
} }
})
const passed = Object.entries(data).filter(([_, follow]) => return false
Common.Schema.isFollow(follow) }
) )
const p = /** @type {unknown} */ (passed) if (typeof raw !== 'object' || raw === null) {
Logger.error(
res(/** @type {Record<string, Follow>} */ (p)) `Expected user.follows to be an object but instead got: ${JSON.stringify(
}) raw
}) )}`
)
throw new TypeError('Could not get follows, not an object')
}
const clean = {
...raw
}
for (const [key, followOrNull] of Object.entries(clean)) {
if (!Common.Schema.isFollow(followOrNull)) {
delete clean[key]
}
}
return clean
} }