Skip to content
This repository has been archived by the owner on Dec 30, 2022. It is now read-only.

Commit

Permalink
feat(store): add serializing capabilities
Browse files Browse the repository at this point in the history
  • Loading branch information
rayrutjes committed May 26, 2017
1 parent 63f8679 commit 90f5347
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/helper-serializer.js
Original file line number Diff line number Diff line change
@@ -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;
};
2 changes: 2 additions & 0 deletions src/instantsearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
HIGHLIGHT_POST_TAG,
createFromAlgoliaCredentials,
createFromAlgoliaClient,
createFromSerialized,
Store,
} from './store';

Expand Down Expand Up @@ -85,6 +86,7 @@ export {
HIGHLIGHT_POST_TAG,
createFromAlgoliaCredentials,
createFromAlgoliaClient,
createFromSerialized,
Store,
Index,
Highlight,
Expand Down
14 changes: 14 additions & 0 deletions src/store.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit 90f5347

Please sign in to comment.