From f19f04a97cc83b76be296a968961cb2a1d8af0ef Mon Sep 17 00:00:00 2001 From: Daniel Lugo Date: Mon, 18 Jan 2021 15:42:59 -0400 Subject: [PATCH] basic coordinates --- services/coordinates.js | 63 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 services/coordinates.js diff --git a/services/coordinates.js b/services/coordinates.js new file mode 100644 index 00000000..79031940 --- /dev/null +++ b/services/coordinates.js @@ -0,0 +1,63 @@ +/** + * @format + */ + +const Common = require('shock-common') +const mapValues = require('lodash/mapValues') +const pickBy = require('lodash/pickBy') +const Bluebird = require('bluebird') +const Logger = require('winston') +const Key = require('../services/gunDB/contact-api/key') + +const { getUser, getMySecret, mySEA } = require('./gunDB/Mediator') + +/** + * @param {string} coordID + * @param {Common.Coordinate} data + * @returns {Promise} + */ +export const writeCoordinate = async (coordID, data) => { + if (coordID !== data.id) { + throw new Error('CoordID must be equal to data.id') + } + + try { + const gunNode = getUser() + .get(Key.COORDINATES) + .get(coordID) + + /** + * Because there are optional properties, typescript can also allow them + * to be specified but with a value of `undefined`. Filter out these. + * @type {Record} + */ + const sanitizedData = pickBy(data, v => typeof v !== 'undefined') + + const encData = await Bluebird.props( + mapValues(sanitizedData, v => { + return mySEA.encrypt(v, getMySecret()) + }) + ) + gunNode.put(encData, ack => { + if (ack.err && typeof ack.err !== 'number') { + Logger.info( + `Error writting corrdinate, coordinate id: ${coordID}, data: ${JSON.stringify( + data, + null, + 2 + )}` + ) + Logger.error(ack.err) + } + }) + } catch (e) { + Logger.info( + `Error writing coordinate, coordinate id: ${coordID}, data: ${JSON.stringify( + data, + null, + 2 + )}` + ) + Logger.error(e.message) + } +}