From 90f53478eb3abcbede48a0105e73d6415d85f54f Mon Sep 17 00:00:00 2001 From: Raymond Rutjes Date: Fri, 26 May 2017 23:27:52 +0200 Subject: [PATCH] feat(store): add serializing capabilities --- src/helper-serializer.js | 34 ++++++++++++++++++++++++++++++++++ src/instantsearch.js | 2 ++ src/store.js | 14 ++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 src/helper-serializer.js diff --git a/src/helper-serializer.js b/src/helper-serializer.js new file mode 100644 index 000000000..f370997ae --- /dev/null +++ b/src/helper-serializer.js @@ -0,0 +1,34 @@ +import algoliaClient from 'algoliasearch'; +import algoliaHelper from 'algoliasearch-helper'; + +export const serialize = function(helper) { + if (!(helper instanceof algoliaHelper.AlgoliaSearchHelper)) { + throw new TypeError('Serialize expects an algolia helper instance.'); + } + + const client = helper.getClient(); + + const serialized = { + searchParameters: Object.assign({}, helper.state), + appId: client.applicationID, + apiKey: client.apiKey, + response: helper.lastResults._rawResults, + }; + + return serialized; +}; + +export const unserialize = function(data) { + const client = algoliaClient(data.appId, data.apiKey); + const helper = algoliaHelper( + client, + data.searchParameters.index, + data.searchParameters + ); + helper.lastResults = new algoliaHelper.SearchResults( + helper.state, + data.response + ); + + return helper; +}; diff --git a/src/instantsearch.js b/src/instantsearch.js index 9b87c0858..96abe6619 100644 --- a/src/instantsearch.js +++ b/src/instantsearch.js @@ -6,6 +6,7 @@ import { HIGHLIGHT_POST_TAG, createFromAlgoliaCredentials, createFromAlgoliaClient, + createFromSerialized, Store, } from './store'; @@ -85,6 +86,7 @@ export { HIGHLIGHT_POST_TAG, createFromAlgoliaCredentials, createFromAlgoliaClient, + createFromSerialized, Store, Index, Highlight, diff --git a/src/store.js b/src/store.js index 51e70ebec..5c2f8e3c4 100644 --- a/src/store.js +++ b/src/store.js @@ -1,6 +1,10 @@ import algolia from 'algoliasearch'; import algoliaHelper from 'algoliasearch-helper'; import { version } from '../package.json'; +import { + serialize as serializeHelper, + unserialize as unserializeHelper, +} from './helper-serializer'; export const FACET_AND = 'and'; export const FACET_OR = 'or'; @@ -30,6 +34,12 @@ export const createFromAlgoliaClient = client => { return new Store(helper); }; +export const createFromSerialized = data => { + const helper = unserializeHelper(data); + + return new Store(helper); +}; + const onHelperChange = function() { if (this._stoppedCounter === 0) { this.refresh(); @@ -319,6 +329,10 @@ export class Store { this._helper.setState(newSearchParameters); } + serialize() { + return serializeHelper(this._helper); + } + // Todo: find a better name for this function. refresh() { this._helper.search();