Skip to content

Instantly share code, notes, and snippets.

@danseethaler
Created July 7, 2017 04:55
Show Gist options
  • Save danseethaler/4e6a78d0881eaa57e682fa5e9b5e6eda to your computer and use it in GitHub Desktop.
Save danseethaler/4e6a78d0881eaa57e682fa5e9b5e6eda to your computer and use it in GitHub Desktop.
JS Objects to MySQL
const subscribers = {};
module.exports = subscriptions = {
subscribe: function(clientId, dataId) {
// Add subscribed user/data to the subscriptions object
const user = subscribers[clientId] || {};
user[dataId] = true;
subscribers[clientId] = user;
},
unsubscribe: function(clientId, dataId) {
// If the client isn't subscribed to anything just return
if (!subscribers[clientId]) return [];
// If no data id is specified the entire subscriber is destroyed
if (!dataId) {
var unsubscribedDataIds = Object.keys(subscribers[clientId]);
delete subscribers[clientId];
return unsubscribedDataIds;
}
// Remove individual data point from general subscribers list
if (subscribers[clientId]) {
delete subscribers[clientId][dataId];
return [dataId];
}
// No subscriptions found
return [];
},
getSubscriptions: function(clientId){
if (subscribers[clientId]) {
return subscribers[clientId];
}
return false;
},
}
const { query, esc } = require('./helpers/config.js');
// Add subscriber to db
export function subscribe(clientId, dataId) {
return query(`
INSERT INTO store_subscribers
SET client_id = ${esc(clientId)},
data_id = ${esc(dataId)}
ON DUPLICATE KEY
UPDATE data_id = ${esc(dataId)}
`);
}
// Remove subscriber to db
export async function unsubscribe(clientId, dataId) {
var sql = `
DELETE FROM store_subscribers
WHERE client_id = ${esc(clientId)}
`;
if (dataId) sql = sql.concat(` AND data_id = ${esc(dataId)}`);
return query(sql);
}
// Return the subscriptions for a specific clientId
export function getSubscriptions(clientId) {
return query(`
SELECT * FROM store_subscribers
WHERE client_id = ${esc(clientId)}
`);
}
// Get all the subscribers for a data point
export function getDataSubscriptions(dataId) {
return query(`
SELECT * FROM store_subscribers
WHERE data_id = ${esc(dataId)}
`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment