Skip to content

Instantly share code, notes, and snippets.

@cveilleux
Created April 20, 2017 18:43
Show Gist options
  • Save cveilleux/ae1f8b9f6186a1a5150f5826ec5e10b7 to your computer and use it in GitHub Desktop.
Save cveilleux/ae1f8b9f6186a1a5150f5826ec5e10b7 to your computer and use it in GitHub Desktop.
Stanza.io private storage plugin example
/**
* Stanza.io plugin that allows storing private JSON data in private storage on
* the XMPP server (XEP-0049).
*
* Example usage:
*
* ```
* var docs = {doc1: 'some value', doc2: {some: 'value'}, doc3: ['some', 'value']};
* client.setPrivateDocuments(docs, cb);
* client.getPrivateDocuments(cb);
* ```
*/
import { Namespace as NS } from 'xmpp-constants';
import get from 'lodash/get';
import forOwn from 'lodash/forOwn';
module.exports = function (client, stanzas) {
// 1. Create and register our custom stanza type:
// <documents>
// <document key="doc1">JSON encoded value</document>
// <document key="doc2">JSON encoded value</document>
// </documents>
var types = stanzas.utils;
var JsonDocument = stanzas.define({
name: '_document',
element: 'document',
namespace: 'stanza:io:json',
fields: {
key: types.attribute('key'),
value: types.text()
}
});
let JsonDocuments = stanzas.define({
name: 'documents',
namespace: 'stanza:io:json',
element: 'documents'
});
stanzas.extend(JsonDocuments, JsonDocument, 'list');
stanzas.withDefinition('query', NS.PRIVATE, function (PrivateStorage) {
stanzas.extend(PrivateStorage, JsonDocuments);
});
/**
* Query the privateStorage of JSON documents.
* Return an object with a key for each document value: {key: value}.
*/
client.getPrivateDocuments = function (cb) {
this.getPrivateData({documents: true}, (err, res) => {
if (err) {
return cb(err);
}
const rawDocs = get(res, 'privateStorage.documents.list') || [];
const docs = {};
rawDocs.forEach((rawDoc) => {
docs[rawDoc.key] = JSON.parse(rawDoc.value);
});
cb(null, docs);
});
};
/**
* Docs is a Map of key: value.
* This function will do all the necessary XML/JSON encoding.
*/
client.setPrivateDocuments = function (docs, cb) {
const encodedDocs = [];
forOwn(docs, (value, key) => {
encodedDocs.push({
key: key,
value: JSON.stringify(value)
});
});
this.setPrivateData({documents: {list: encodedDocs}}, cb);
};
};
@redisotschek
Copy link

Hey! What is stanzas.withDefinition here and stanzas.extend?

@cveilleux
Copy link
Author

this is super old, dont quite remember.

It should be Stanza.io API functions. See stanza.io API. Its been 3 years, I'm not using it anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment