From 8c5026d887b3da4ba701114bbf3b8462585d6514 Mon Sep 17 00:00:00 2001 From: Daniel Lugo Date: Tue, 16 Jun 2020 12:56:53 -0400 Subject: [PATCH] user getter --- services/gunDB/contact-api/getters.js | 86 +++++++++++++++++++++++++-- 1 file changed, 81 insertions(+), 5 deletions(-) diff --git a/services/gunDB/contact-api/getters.js b/services/gunDB/contact-api/getters.js index cc1104f7..0fcf9805 100644 --- a/services/gunDB/contact-api/getters.js +++ b/services/gunDB/contact-api/getters.js @@ -1,3 +1,9 @@ +/** + * @format + */ +const Common = require('shock-common') +const Logger = require('winston') + const Key = require('./key') const Utils = require('./utils') @@ -5,8 +11,13 @@ const Utils = require('./utils') * @param {string} pub * @returns {Promise} */ -exports.currentOrderAddress = async (pub) => { - const currAddr = await Utils.tryAndWait((gun) => gun.user(pub).get(Key.CURRENT_ORDER_ADDRESS).then()) +exports.currentOrderAddress = async pub => { + const currAddr = await Utils.tryAndWait(gun => + gun + .user(pub) + .get(Key.CURRENT_ORDER_ADDRESS) + .then() + ) if (typeof currAddr !== 'string') { throw new TypeError('Expected user.currentOrderAddress to be an string') @@ -19,11 +30,76 @@ exports.currentOrderAddress = async (pub) => { * @param {string} pub * @returns {Promise} */ -exports.userToIncomingID = async (pub) => { - const incomingID = await require('../Mediator').getUser().get(Key.USER_TO_INCOMING).get(pub).then() +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 +} -} \ No newline at end of file +/** + * @param {string} publicKey + * @returns {Promise} + */ +const getUser = async publicKey => { + /** + * @type {Common.Schema.User} + */ + const user = { + avatar: null, + bio: null, + displayName: null, + lastSeenApp: 0, + lastSeenNode: 0, + publicKey + } + + /** + * @type {unknown} + */ + const profile = await Utils.tryAndWait( + gun => + new Promise(res => { + const userNode = gun.get(`~${publicKey}`) + + userNode.load(data => res(data)) + }), + v => typeof v === 'object' && v !== null + ) + + if ( + typeof profile === 'object' && + profile !== null && + Common.Schema.isUser({ + ...profile, + publicKey + }) + ) { + Object.assign(user, profile) + Logger.error( + `Invalid profile found for publicKey: ${publicKey}, found: ${JSON.stringify( + profile + )}` + ) + } + + return user +} + +exports.getUser = getUser + +exports.getMyUser = () => { + const user = require('../Mediator').getUser() + const publicKey = user.is && user.is.pub + + if (typeof publicKey !== 'string') { + throw new Error('NOT_AUTH') + } + + return getUser(publicKey) +}