diff --git a/.eslintrc b/.eslintrc
index 7a40575865..7e33486757 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -1,39 +1,6 @@
{
- "env" : {
- "node": true,
- "browser": true
- },
- "rules" : {
- "brace-style": [2, "stroustrup", { "allowSingleLine": true }],
- "camelcase" : 1,
- "comma-spacing": [2, {"before": false, "after": true}],
- "comma-style": [2, "last"],
- "consistent-return" : 2,
- "consistent-this": [1, "self"],
- "curly" : [2,"multi-line"],
- "default-case": 1,
- "eqeqeq": [2, "smart"],
- "global-strict" : 0,
- "indent": [2, 2],
- "key-spacing" : [1, { "beforeColon" : true, "afterColon" : true }],
- "new-cap" : 2,
- "no-extra-bind" : 1,
- "no-multiple-empty-lines" : 1,
- "no-multi-spaces": 1,
- "no-spaced-func": 1,
- "no-trailing-spaces" : 2,
- "no-underscore-dangle": 0,
- "quotes" : [1, "double"],
- "semi": 2,
- "space-before-blocks": 1,
- "space-before-function-parentheses": [1, "never"],
- "space-infix-ops": 1,
- "space-in-parens": [1, "always"],
- "strict" : [2, "global"],
- "valid-jsdoc": [2, { "requireReturnDescription": false }]
- },
- "globals" : {
- "module" : true,
- "require" : true
- }
+ "extends": [
+ "eslint-config-airbnb",
+ "eslint-config-algolia"
+ ]
}
diff --git a/.jsdoc b/.jsdoc
index 043010dd62..f93eb8890b 100644
--- a/.jsdoc
+++ b/.jsdoc
@@ -1,9 +1,9 @@
{
"plugins": ["plugins/markdown"],
- "opts" : {
- "template" : "node_modules/minami"
+ "opts": {
+ "template": "node_modules/minami"
},
- "markdown" : {
- "anchorInHeadings" : true
+ "markdown": {
+ "anchorInHeadings": true
}
}
diff --git a/CHANGELOG b/CHANGELOG
index bf992e29be..3c5e133ee5 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -4,85 +4,85 @@ UNRELEASED
* test: add CI testing (browsers, phantom, node, io)
2.1.2 - 2015-06-26
- * FIX : #113 support for attributes hightlightPreTag and hightlighPostTag
- * FIX : #112 distinct = undefined sent to the server
- * FIX : #110 helper.hasRefinements() now checks for numerics
- * FIX : #106 convert refinements to string
- * DOC : Update theme + fix (github.com/algolia/minami)
- * DOC : Fix misc links and descrition and added samples of objects
- * DOC : Added a cheat sheet in the generated documentation
+ * FIX: #113 support for attributes hightlightPreTag and hightlighPostTag
+ * FIX: #112 distinct = undefined sent to the server
+ * FIX: #110 helper.hasRefinements() now checks for numerics
+ * FIX: #106 convert refinements to string
+ * DOC: Update theme + fix (github.com/algolia/minami)
+ * DOC: Fix misc links and descrition and added samples of objects
+ * DOC: Added a cheat sheet in the generated documentation
2.1.1 - 2015-06-19
- * FIX : #107 Apply rules to distinct to prevent the API to return an error
- * FIX : make algoliasearch-helper requireable + browserifyable by removing the global envify transform
+ * FIX: #107 Apply rules to distinct to prevent the API to return an error
+ * FIX: make algoliasearch-helper requireable + browserifyable by removing the global envify transform
2.1.0 - 2015-06-15
- * FIX : #29 Avoid callback for outdated queries
- * FIX : #64 Sum up the processing time of all queries
- * FIX : #92 Parameters that can be set in the dashboard shouldn't have
+ * FIX: #29 Avoid callback for outdated queries
+ * FIX: #64 Sum up the processing time of all queries
+ * FIX: #92 Parameters that can be set in the dashboard shouldn't have
defaults
- * FIX : #62 Make sure disctinct is set to false when it's not possible to
+ * FIX: #62 Make sure disctinct is set to false when it's not possible to
use distinct in Algolia
- * FEATURE : #91 Support for tags (with support for the raw format #98)
- * FEATURE : #70 Ability to get all refined values : helper.getRefinements(
+ * FEATURE: #91 Support for tags (with support for the raw format #98)
+ * FEATURE: #70 Ability to get all refined values: helper.getRefinements(
facetname )
- * FEATURE : #51 multiple filters for a single conjunctive facet (tests)
- * FEATURE : Ability to modify any parameter of the state easily (#76 #84 #12)
- * FEATURE : #69 Ability to know if a facet is refined, whatever the value
- * FEATURE : #86 Expose SearchParameters, AlgoliaSearchHelper, SearchResults to
+ * FEATURE: #51 multiple filters for a single conjunctive facet (tests)
+ * FEATURE: Ability to modify any parameter of the state easily (#76 #84 #12)
+ * FEATURE: #69 Ability to know if a facet is refined, whatever the value
+ * FEATURE: #86 Expose SearchParameters, AlgoliaSearchHelper, SearchResults to
users directly in the builds
- * FEATURE : #25 let the user do a clearRefinement with a function as a filter
- * REFACTORING : SearchParameters is immutable (#14)
- * REFACTORING : Ensure SearchParameters is totally frozen (#14)
- * LIB : Update lodash version to 3.9.x
+ * FEATURE: #25 let the user do a clearRefinement with a function as a filter
+ * REFACTORING: SearchParameters is immutable (#14)
+ * REFACTORING: Ensure SearchParameters is totally frozen (#14)
+ * LIB: Update lodash version to 3.9.x
2.0.4
- * FIX : #82 Fix facet count on records with multiple values for a single
+ * FIX: #82 Fix facet count on records with multiple values for a single
facet
* FEATURE: Add exhaustive attribute to a facet and removed useless timeout
(#80)
2.0.3 - 2015-05-13
- * FIX : #72 add back the ability to do multiple disjunctive facetting on a
+ * FIX: #72 add back the ability to do multiple disjunctive facetting on a
single attribute
- * FEATURE : #73 method to replace the state, without triggering a change
- event : overrideStateWithoutTriggeringChangeEvent (use wisely)
- * FEATURE : #66 add setTypoTolerance to SearchParameters
+ * FEATURE: #73 method to replace the state, without triggering a change
+ event: overrideStateWithoutTriggeringChangeEvent (use wisely)
+ * FEATURE: #66 add setTypoTolerance to SearchParameters
2.0.2 - 2015-05-06
- * FIX : setHitsPerPage was creating a new property HitsPerPage instead of
+ * FIX: setHitsPerPage was creating a new property HitsPerPage instead of
updating the currently available hitsPerPage
2.0.1
- * MEH : because of jsDelivr
+ * MEH: because of jsDelivr
2.0.0
- * FIX : set page to 0 if it might change the number of pages returned
- * FIX : handle distinct parameter automatically
- * FIX : batch response handler gets the proper search state
- * FEATURE : (breaking) Now peer depend on algoliasearch v3.1
- * FEATURE : (breaking) Facets stats and timeout infos are consistently
+ * FIX: set page to 0 if it might change the number of pages returned
+ * FIX: handle distinct parameter automatically
+ * FIX: batch response handler gets the proper search state
+ * FEATURE: (breaking) Now peer depend on algoliasearch v3.1
+ * FEATURE: (breaking) Facets stats and timeout infos are consistently
grouped in the facet object in the SearchResults
- * FEATURE : (breaking) no more extra queries
- * FEATURE : (breaking) Facets results are stored in an array with an order
+ * FEATURE: (breaking) no more extra queries
+ * FEATURE: (breaking) Facets results are stored in an array with an order
that reflects their definition.
- * FEATURE : Search results explicit definition
- * FEATURE : (breaking) Search parameters as a separate object
- * FEATURE : (breaking) Move callback style to a event based API
- * FEATURE : change and results events return the state and the results (if any)
- * FEATURE : SearchRefults.getFacetByName to retrieve a facet object from its
+ * FEATURE: Search results explicit definition
+ * FEATURE: (breaking) Search parameters as a separate object
+ * FEATURE: (breaking) Move callback style to a event based API
+ * FEATURE: change and results events return the state and the results (if any)
+ * FEATURE: SearchRefults.getFacetByName to retrieve a facet object from its
name
- * FEATURE : SearchParameters.getNumericRefinement : get back the value of a specific numeric
+ * FEATURE: SearchParameters.getNumericRefinement: get back the value of a specific numeric
refinement
- * FEATURE : clear refinements by name
- * FEATURE : isDisjunctiveRefined to check if a disjunctive facet is refined
- * FEATURE : basic support for numeric filters
- * FEATURE : version number on the main helper factory
- * TESTS : defaults test
+ * FEATURE: clear refinements by name
+ * FEATURE: isDisjunctiveRefined to check if a disjunctive facet is refined
+ * FEATURE: basic support for numeric filters
+ * FEATURE: version number on the main helper factory
+ * TESTS: defaults test
1.1.0
- * REFACTORING : constructor, now expose the defaults
- * TESTS : defaults test
+ * REFACTORING: constructor, now expose the defaults
+ * TESTS: defaults test
* FEATURE: Allow .search(q, params, cb) "callback always last" convention
introduced by JavaScript client, also on the helper
diff --git a/README.md b/README.md
index 6669355855..eb75861757 100644
--- a/README.md
+++ b/README.md
@@ -33,24 +33,24 @@ This is the library you will need to easily build a good search UX like our [ins
A small example that uses Browserify to manage modules.
```javascript
-var algoliasearch = require( "algoliasearch" );
-var algoliasearchHelper = require( "algoliasearch-helper" );
+var algoliasearch = require('algoliasearch');
+var algoliasearchHelper = require('algoliasearch-helper');
-var client = algoliasearch( "app_id", "secret" );
+var client = algoliasearch('app_id', 'secret');
-var helper = algoliasearchHelper( client, "myMainIndex", {
- facets : [ "mainCharacterFirstName", "year" ],
- disjunctiveFacets : [ "director" ]
+var helper = algoliasearchHelper(client, 'myMainIndex', {
+ facets: ['mainCharacterFirstName', 'year'],
+ disjunctiveFacets: ['director']
});
-helper.on( "result", function( data ){
- console.log( data.hits );
-} );
+helper.on('result', function(data){
+ console.log(data.hits);
+});
-helper.addDisjunctiveRefine( "director", "Clint Eastword" );
-helper.addDisjunctiveRefine( "director", "Sofia Coppola" );
+helper.addDisjunctiveRefine('director', 'Clint Eastword');
+helper.addDisjunctiveRefine('director', 'Sofia Coppola');
-helper.addNumericRefinement( "year", "=", 2003 );
+helper.addNumericRefinement('year', '=', 2003);
// Search for any movie filmed in 2003 and directed by either C. Eastwood or S. Coppola
helper.search();
@@ -62,19 +62,19 @@ helper.search();
[See the examples in action](http://algolia.github.io/algoliasearch-helper-js/)
-### Use with NPM
+### With NPM
`npm install algoliasearch-helper`
-### Use with bower
+### With bower
`bower install algoliasearch-helper`
-### Use the CDN
+### Regular ``
+``
## How to contribute?
diff --git a/examples/instantsearch+helper+angular.html b/examples/instantsearch+helper+angular.html
index 1afaa6e553..a5b9453b3c 100644
--- a/examples/instantsearch+helper+angular.html
+++ b/examples/instantsearch+helper+angular.html
@@ -1,3 +1,4 @@
+
@@ -64,7 +65,7 @@ Results
disjunctiveFacets: ['category', 'manufacturer'],
hitsPerPage: 5,
maxValuesPerFacet: 5,
- getRankingInfo : true
+ getRankingInfo: true
});
$scope.helper.on('result', function(content) {
diff --git a/examples/instantsearch+helper+excludes.html b/examples/instantsearch+helper+excludes.html
index 96856ac300..92cf025d6f 100644
--- a/examples/instantsearch+helper+excludes.html
+++ b/examples/instantsearch+helper+excludes.html
@@ -1,3 +1,4 @@
+
@@ -52,8 +53,8 @@ Results
maxValuesPerFacet: 5
});
- helper.on( "result", searchCallback );
- $inputfield.keyup( search );
+ helper.on("result", searchCallback);
+ $inputfield.keyup(search);
window.toggleRefine = function(facet, value) {
helper.toggleRefine(facet, value).search();
@@ -68,11 +69,11 @@ Results
//Functions
function search() {
- helper.setQuery( $inputfield.val() ).search();
+ helper.setQuery($inputfield.val()).search();
}
- function searchCallback( content ) {
- console.log( content );
+ function searchCallback(content) {
+ console.log(content);
if (content.query != $inputfield.val()) {
// do not consider out-dated queries
return;
@@ -103,8 +104,8 @@ Results
// Scan all disjunctive facets and display them
var facets = '';
- for ( var i = 0; i < content.disjunctiveFacets.length; i++ ){
- var facet = content.disjunctiveFacets[ i ];
+ for (var i = 0; i < content.disjunctiveFacets.length; i++){
+ var facet = content.disjunctiveFacets[i];
facets += '' + facet.name + '
';
var values = facet.data;
for (var value in values) {
@@ -118,8 +119,8 @@ Results
// Scan all facets and display them
facets = '';
- for( var i = 0; i < content.facets.length; i++ ){
- var facet = content.facets[ i ];
+ for(var i = 0; i < content.facets.length; i++){
+ var facet = content.facets[i];
facets += '' + facet.name + '
';
facets += '';
var values = facet.data;
diff --git a/examples/instantsearch+helper.html b/examples/instantsearch+helper.html
index 166738f2ea..d60efc3a08 100644
--- a/examples/instantsearch+helper.html
+++ b/examples/instantsearch+helper.html
@@ -1,3 +1,4 @@
+
@@ -43,13 +44,13 @@ Results
disjunctiveFacets: ['category', 'manufacturer'],
hitsPerPage: 5,
maxValuesPerFacet: 5,
- getRankingInfo : true
+ getRankingInfo: true
});
- helper.on( "result", searchCallback);
+ helper.on("result", searchCallback);
- $inputfield.keyup( function( e ){
- helper.setQuery( $inputfield.val() ).search();
+ $inputfield.keyup(function(e){
+ helper.setQuery($inputfield.val()).search();
} );
window.toggleRefine = function(facet, value) {
@@ -58,7 +59,7 @@ Results
helper.search();
- function searchCallback( content ) {
+ function searchCallback(content) {
if (content.query != $inputfield.val()) {
// do not consider out-dated queries
return;
@@ -88,8 +89,8 @@ Results
// Scan all disjunctive facets and display them
var facets = '';
- for( var i = 0; i < content.disjunctiveFacets.length; i++ ){
- var facet = content.disjunctiveFacets[ i ];
+ for(var i = 0; i < content.disjunctiveFacets.length; i++){
+ var facet = content.disjunctiveFacets[i];
facets += '' + facet.name + '
';
var values = facet.data;
for (var value in values) {
@@ -102,8 +103,8 @@ Results
// Scan all facets and display them
facets = '';
- for( var i = 0; i < content.facets.length ; i++ ){
- var facet = content.facets[ i ];
+ for(var i = 0; i < content.facets.length ; i++){
+ var facet = content.facets[i];
facets += '' + facet.name + '
';
facets += '';
var values = facet.data;
diff --git a/examples/style.css b/examples/style.css
index da0481681b..a2ecab9289 100644
--- a/examples/style.css
+++ b/examples/style.css
@@ -1,17 +1,17 @@
.search {
- text-align : center;
- background : lightblue;
+ text-align: center;
+ background: lightblue;
}
#q {
width: 500px;
margin: 10px auto;
- padding : 5px;
+ padding: 5px;
}
.code{
- font-family : 'inconsolata', monospace;
- background : #eee;
+ font-family: 'inconsolata', monospace;
+ background: #eee;
}
em{
diff --git a/index.html b/index.html
index 6a1896ce59..8c0c89255a 100644
--- a/index.html
+++ b/index.html
@@ -16,7 +16,7 @@ Getting started with the examples
- Negative facetting with the helper
Play with the examples locally
- To get you started with the helper examples on your machine, follow these steps :
+ To get you started with the helper examples on your machine, follow these steps:
- Checkout the project with git clone https://github.com/algolia/algoliasearch-helper-js.git
- In your command line, do npm install
diff --git a/index.js b/index.js
index 3f8c74b8e1..415e253c22 100644
--- a/index.js
+++ b/index.js
@@ -1,8 +1,8 @@
-"use strict";
-var AlgoliaSearchHelper = require( "./src/algoliasearch.helper" );
+'use strict'
+var AlgoliaSearchHelper = require('./src/algoliasearch.helper')
-var SearchParameters = require( "./src/SearchParameters" );
-var SearchResults = require( "./src/SearchResults" );
+var SearchParameters = require('./src/SearchParameters')
+var SearchResults = require('./src/SearchResults')
/**
* The algoliasearchHelper module contains everything needed to use the Algoliasearch
@@ -11,15 +11,15 @@ var SearchResults = require( "./src/SearchResults" );
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
- * var helper = algoliasearchHelper( client, "bestbuy", {
- * facets : [ "shipping" ],
- * disjunctiveFacets : [ "category" ]
- * } );
- * helper.on( "result", function( result ) {
- * console.log( result );
- * } );
- * helper.toggleRefine( "Movies & TV Shows" )
- * .toggleRefine( "Free shipping" )
+ * var helper = algoliasearchHelper(client, 'bestbuy', {
+ * facets: ['shipping'],
+ * disjunctiveFacets: ['category']
+ * });
+ * helper.on('result', function(result) {
+ * console.log(result);
+ * });
+ * helper.toggleRefine('Movies & TV Shows')
+ * .toggleRefine('Free shipping')
* .search();
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
@@ -27,8 +27,8 @@ var SearchResults = require( "./src/SearchResults" );
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
-function algoliasearchHelper( client, index, opts ) {
- return new AlgoliaSearchHelper( client, index, opts );
+function algoliasearchHelper(client, index, opts) {
+ return new AlgoliaSearchHelper(client, index, opts)
}
/**
@@ -36,27 +36,27 @@ function algoliasearchHelper( client, index, opts ) {
* @member module:algoliasearchHelper.version
* @type {number}
*/
-algoliasearchHelper.version = "2.1.2";
+algoliasearchHelper.version = '2.1.2'
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
-algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper;
+algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
-algoliasearchHelper.SearchParameters = SearchParameters;
+algoliasearchHelper.SearchParameters = SearchParameters
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
-algoliasearchHelper.SearchResults = SearchResults;
+algoliasearchHelper.SearchResults = SearchResults
-module.exports = algoliasearchHelper;
+module.exports = algoliasearchHelper
diff --git a/package.json b/package.json
index 1ea2b8dd02..cf2489ad78 100644
--- a/package.json
+++ b/package.json
@@ -9,7 +9,7 @@
"minify-build": "uglifyjs dist/algoliasearch.helper.js --mangle --compress=warnings=false > dist/algoliasearch.helper.min.js",
"dev": "DEBUG=zuul* zuul --no-coverage --local 8090 test/run.js",
"dev-coverage": "DEBUG=zuul* zuul --local 8090 test/run.js",
- "watch-lint": " onchange '.eslintrc' 'src/**/*.js' 'index.js' -- script/lint.sh",
+ "lint": "scripts/lint.sh",
"open": "sleep 1 && opn http://localhost:8080/examples",
"examples": "npm run build & npm run open & http-server .",
"doc": "npm run doc:toc && npm run doc:jsdoc",
@@ -35,6 +35,11 @@
"type": "git",
"url": "https://github.com/algolia/algoliasearch-helper-js.git"
},
+ "standard": {
+ "ignore": [
+ "dist/"
+ ]
+ },
"devDependencies": {
"algoliasearch": "latest",
"browserify": "10.2.4",
@@ -43,8 +48,11 @@
"doctoc": "0.14.1",
"envify": "3.4.0",
"eslint": "0.24.0",
+ "eslint-config-airbnb": "0.0.6",
+ "eslint-config-algolia": "2.0.3",
"gh-pages-deploy": "0.3.0",
"http-server": "0.8.0",
+ "jscs": "1.13.1",
"jsdoc": "bobylito/jsdoc",
"minami": "algolia/minami",
"onchange": "1.0.0",
diff --git a/scripts/lint.sh b/scripts/lint.sh
index 60a4fca202..1d472f072d 100755
--- a/scripts/lint.sh
+++ b/scripts/lint.sh
@@ -5,4 +5,4 @@ set -x # debug messages
echo "Lint"
-eslint --quiet .
+eslint . --quiet
diff --git a/src/SearchParameters/RefinementList.js b/src/SearchParameters/RefinementList.js
index 0764483b44..cb58b622ff 100644
--- a/src/SearchParameters/RefinementList.js
+++ b/src/SearchParameters/RefinementList.js
@@ -10,17 +10,18 @@
* @typedef {Object.} SearchParameters.refinementList.RefinementList
*/
-"use strict";
-var extend = require( "../functions/extend" );
+'use strict'
-var isUndefined = require( "lodash/lang/isUndefined" );
-var isString = require( "lodash/lang/isString" );
-var isFunction = require( "lodash/lang/isFunction" );
-var isEmpty = require( "lodash/lang/isEmpty" );
+var extend = require('../functions/extend')
-var reduce = require( "lodash/collection/reduce" );
-var filter = require( "lodash/collection/filter" );
-var omit = require( "lodash/object/omit" );
+var isUndefined = require('lodash/lang/isUndefined')
+var isString = require('lodash/lang/isString')
+var isFunction = require('lodash/lang/isFunction')
+var isEmpty = require('lodash/lang/isEmpty')
+
+var reduce = require('lodash/collection/reduce')
+var filter = require('lodash/collection/filter')
+var omit = require('lodash/object/omit')
var lib = {
/**
@@ -30,22 +31,25 @@ var lib = {
* @param {string} value the value of the refinement, if the value is not a string it will be converted
* @return {RefinementList} a new and updated prefinement list
*/
- addRefinement : function addRefinement( refinementList, attribute, value ) {
- if( lib.isRefined( refinementList, attribute, value ) ) {
- return refinementList;
+ addRefinement: function addRefinement(refinementList, attribute, value) {
+ if (lib.isRefined(refinementList, attribute, value)) {
+ return refinementList
}
- var valueAsString = "" + value;
+ var valueAsString = '' + value
+
+ var facetRefinement = !refinementList[attribute] ?
+ [valueAsString] :
+ refinementList[attribute].concat(valueAsString)
- var facetRefinement = !refinementList[ attribute ] ? [ valueAsString ] : refinementList[ attribute ].concat( valueAsString );
+ var mod = {}
- var mod = {};
- mod[ attribute ] = facetRefinement;
+ mod[attribute] = facetRefinement
- return extend( {}, refinementList, mod );
+ return extend({}, refinementList, mod)
},
/**
- * Removes refinement(s) for an attribute :
+ * Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
@@ -53,16 +57,16 @@ var lib = {
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
- removeRefinement : function removeRefinement( refinementList, attribute, value ) {
- if( isUndefined( value ) ) {
- return lib.clearRefinement( refinementList, attribute );
+ removeRefinement: function removeRefinement(refinementList, attribute, value) {
+ if (isUndefined(value)) {
+ return lib.clearRefinement(refinementList, attribute)
}
- var valueAsString = "" + value;
+ var valueAsString = '' + value
- return lib.clearRefinement( refinementList, function( v, f ) {
- return attribute === f && valueAsString === v;
- } );
+ return lib.clearRefinement(refinementList, function(v, f) {
+ return attribute === f && valueAsString === v
+ })
},
/**
* Toggles the refinement value for an attribute.
@@ -71,42 +75,41 @@ var lib = {
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
- toggleRefinement : function toggleRefinement( refinementList, attribute, value ) {
- if( isUndefined( value ) ) throw new Error( "toggleRefinement should be used with a value" );
+ toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
+ if (isUndefined(value)) throw new Error('toggleRefinement should be used with a value')
- if( lib.isRefined( refinementList, attribute, value ) ) {
- return lib.removeRefinement( refinementList, attribute, value );
+ if (lib.isRefined(refinementList, attribute, value)) {
+ return lib.removeRefinement(refinementList, attribute, value)
}
- return lib.addRefinement( refinementList, attribute, value );
+ return lib.addRefinement(refinementList, attribute, value)
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
- * behaviors can happen :
- * - if no attribute is provided : clears the whole list
- * - if an attribute is provided as a string : clears the list for the specific attribute
- * - if an attribute is provided as a function : discards the elements for which the function returns true
+ * behaviors can happen:
+ * - if no attribute is provided: clears the whole list
+ * - if an attribute is provided as a string: clears the list for the specific attribute
+ * - if an attribute is provided as a function: discards the elements for which the function returns true
* @param {RefinementList} refinementList the initial list
* @param {string} [attribute] the attribute or function to discard
* @param {string} [refinementType] optionnal parameter to give more context to the attribute function
* @return {RefinementList} a new and updated refinement list
*/
- clearRefinement : function clearRefinement( refinementList, attribute, refinementType ) {
- if ( isUndefined( attribute ) ) {
- return {};
- }
- else if ( isString( attribute ) ) {
- return omit( refinementList, attribute );
- }
- else if ( isFunction( attribute ) ) {
- return reduce( refinementList, function( memo, values, key ) {
- var facetList = filter( values, function( value ) {
- return !attribute( value, key, refinementType );
- } );
-
- if( !isEmpty( facetList ) ) memo[ key ] = facetList;
- return memo;
- }, {} );
+ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
+ if (isUndefined(attribute)) {
+ return {}
+ } else if (isString(attribute)) {
+ return omit(refinementList, attribute)
+ } else if (isFunction(attribute)) {
+ return reduce(refinementList, function(memo, values, key) {
+ var facetList = filter(values, function(value) {
+ return !attribute(value, key, refinementType)
+ })
+
+ if (!isEmpty(facetList)) memo[key] = facetList
+
+ return memo
+ }, {})
}
},
/**
@@ -118,19 +121,19 @@ var lib = {
* @param {string} refinementValue value of the filter/refinement
* @return {boolean}
*/
- isRefined : function isRefined( refinementList, attribute, refinementValue ) {
- var containsRefinements = refinementList[ attribute ] &&
- refinementList[ attribute ].length > 0;
+ isRefined: function isRefined(refinementList, attribute, refinementValue) {
+ var containsRefinements = refinementList[attribute] &&
+ refinementList[attribute].length > 0
- if( isUndefined( refinementValue ) ) {
- return containsRefinements;
+ if (isUndefined(refinementValue)) {
+ return containsRefinements
}
- var refinementValueAsString = "" + refinementValue;
+ var refinementValueAsString = '' + refinementValue
return containsRefinements &&
- refinementList[ attribute ].indexOf( refinementValueAsString ) !== -1;
+ refinementList[attribute].indexOf(refinementValueAsString) !== -1
}
-};
+}
-module.exports = lib;
+module.exports = lib
diff --git a/src/SearchParameters/index.js b/src/SearchParameters/index.js
index 77888e7707..32ab86092d 100644
--- a/src/SearchParameters/index.js
+++ b/src/SearchParameters/index.js
@@ -1,19 +1,19 @@
-"use strict";
-var keys = require( "lodash/object/keys" );
-var intersection = require( "lodash/array/intersection" );
-var forEach = require( "lodash/collection/forEach" );
-var reduce = require( "lodash/collection/reduce" );
-var filter = require( "lodash/collection/filter" );
-var omit = require( "lodash/object/omit" );
-var isEmpty = require( "lodash/lang/isEmpty" );
-var isUndefined = require( "lodash/lang/isUndefined" );
-var isString = require( "lodash/lang/isString" );
-var isFunction = require( "lodash/lang/isFunction" );
-
-var extend = require( "../functions/extend" );
-var deepFreeze = require( "../functions/deepFreeze" );
-
-var RefinementList = require( "./RefinementList" );
+'use strict'
+var keys = require('lodash/object/keys')
+var intersection = require('lodash/array/intersection')
+var forEach = require('lodash/collection/forEach')
+var reduce = require('lodash/collection/reduce')
+var filter = require('lodash/collection/filter')
+var omit = require('lodash/object/omit')
+var isEmpty = require('lodash/lang/isEmpty')
+var isUndefined = require('lodash/lang/isUndefined')
+var isString = require('lodash/lang/isString')
+var isFunction = require('lodash/lang/isFunction')
+
+var extend = require('../functions/extend')
+var deepFreeze = require('../functions/deepFreeze')
+
+var RefinementList = require('./RefinementList')
/**
* @typedef {string[]} SearchParameters.FacetList
@@ -40,73 +40,73 @@ var RefinementList = require( "./RefinementList" );
* @see SearchParameters.make
* @example SearchParameters of the first query in the instant search demo
{
- "query" : "",
- "disjunctiveFacets" : [
+ "query": "",
+ "disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
- ],
- "maxValuesPerFacet" : 30,
- "page" : 0,
- "hitsPerPage" : 10,
- "facets" : [
+ ],
+ "maxValuesPerFacet": 30,
+ "page": 0,
+ "hitsPerPage": 10,
+ "facets": [
"type",
"shipping"
- ]
+ ]
}
*/
-var SearchParameters = function( newParameters ) {
-
- var params = newParameters || {};
+function SearchParameters(newParameters) {
+ var params = newParameters || {}
- //Query
+ // Query
/**
* Query string of the instant search. The empty string is a valid query.
* @member {string}
* @see https://www.algolia.com/doc#query
*/
- this.query = params.query || "";
+ this.query = params.query || ''
- //Facets
+ // Facets
/**
* All the facets that will be requested to the server
* @member {string[]}
*/
- this.facets = params.facets || [];
+ this.facets = params.facets || []
/**
* All the declared disjunctive facets
* @member {string[]}
*/
- this.disjunctiveFacets = params.disjunctiveFacets || [];
- //Refinements
+ this.disjunctiveFacets = params.disjunctiveFacets || []
+
+ // Refinements
/**
* @private
* @member {Object.}
*/
- this.facetsRefinements = params.facetsRefinements || {};
+ this.facetsRefinements = params.facetsRefinements || {}
/**
* @private
* @member {Object.}
*/
- this.facetsExcludes = params.facetsExcludes || {};
+ this.facetsExcludes = params.facetsExcludes || {}
/**
* @private
* @member {Object.}
*/
- this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
+ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}
/**
* @private
* @member {Object.}
*/
- this.numericRefinements = params.numericRefinements || {};
+ this.numericRefinements = params.numericRefinements || {}
/**
* Contains the tags used to refine the query
- * Associated property in the query : tagFilters
+ * Associated property in the query: tagFilters
* @private
* @member {string[]}
*/
- this.tagRefinements = params.tagRefinements || [];
+ this.tagRefinements = params.tagRefinements || []
/**
* Contains the tag filters in the raw format of the Algolia API. Setting this
@@ -115,197 +115,198 @@ var SearchParameters = function( newParameters ) {
* @see https://www.algolia.com/doc#tagFilters
* @member {string}
*/
- this.tagFilters = params.tagFilters;
+ this.tagFilters = params.tagFilters
- //Misc. parameters
+ // Misc. parameters
/**
* Number of hits to be returned by the search API
* @member {number}
* @see https://www.algolia.com/doc#hitsPerPage
*/
- this.hitsPerPage = params.hitsPerPage;
+ this.hitsPerPage = params.hitsPerPage
/**
* Number of values for each facetted attribute
* @member {number}
* @see https://www.algolia.com/doc#maxValuesPerFacet
*/
- this.maxValuesPerFacet = params.maxValuesPerFacet;
+ this.maxValuesPerFacet = params.maxValuesPerFacet
/**
* The current page number
* @member {number}
* @see https://www.algolia.com/doc#page
*/
- this.page = params.page || 0;
+ this.page = params.page || 0
/**
* How the query should be treated by the search engine.
- * Possible values : prefixAll, prefixLast, prefixNone
+ * Possible values: prefixAll, prefixLast, prefixNone
* @see https://www.algolia.com/doc#queryType
* @member {string}
*/
- this.queryType = params.queryType;
+ this.queryType = params.queryType
/**
* How the typo tolerance behave in the search engine.
- * Possible values : true, false, min, strict
+ * Possible values: true, false, min, strict
* @see https://www.algolia.com/doc#typoTolerance
* @member {string}
*/
- this.typoTolerance = params.typoTolerance;
+ this.typoTolerance = params.typoTolerance
/**
* Number of characters to wait before doing one character replacement.
* @see https://www.algolia.com/doc#minWordSizefor1Typo
* @member {number}
*/
- this.minWordSizefor1Typo = params.minWordSizefor1Typo;
+ this.minWordSizefor1Typo = params.minWordSizefor1Typo
/**
* Number of characters to wait before doing a second character replacement.
* @see https://www.algolia.com/doc#minWordSizefor2Typos
* @member {number}
*/
- this.minWordSizefor2Typos = params.minWordSizefor2Typos;
+ this.minWordSizefor2Typos = params.minWordSizefor2Typos
/**
* Should the engine allow typos on numerics.
* @see https://www.algolia.com/doc#allowTyposOnNumericTokens
* @member {boolean}
*/
- this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens;
+ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens
/**
* Should the plurals be ignored
* @see https://www.algolia.com/doc#ignorePlurals
* @member {boolean}
*/
- this.ignorePlurals = params.ignorePlurals;
+ this.ignorePlurals = params.ignorePlurals
/**
* Restrict which attribute is searched.
* @see https://www.algolia.com/doc#restrictSearchableAttributes
* @member {string}
*/
- this.restrictSearchableAttributes = params.restrictSearchableAttributes;
+ this.restrictSearchableAttributes = params.restrictSearchableAttributes
/**
* Enable the advanced syntax.
* @see https://www.algolia.com/doc#advancedSyntax
* @member {boolean}
*/
- this.advancedSyntax = params.advancedSyntax;
+ this.advancedSyntax = params.advancedSyntax
/**
* Enable the analytics
* @see https://www.algolia.com/doc#analytics
* @member {boolean}
*/
- this.analytics = params.analytics;
+ this.analytics = params.analytics
/**
* Tag of the query in the analytics.
* @see https://www.algolia.com/doc#analyticsTags
* @member {string}
*/
- this.analyticsTags = params.analyticsTags;
+ this.analyticsTags = params.analyticsTags
/**
* Enable the synonyms
* @see https://www.algolia.com/doc#synonyms
* @member {boolean}
*/
- this.synonyms = params.synonyms;
+ this.synonyms = params.synonyms
/**
* Should the engine replace the synonyms in the highlighted results.
* @see https://www.algolia.com/doc#replaceSynonymsInHighlight
* @member {boolean}
*/
- this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight;
+ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight
/**
* Add some optional words to those defined in the dashboard
* @see https://www.algolia.com/doc#optionalWords
* @member {string}
*/
- this.optionalWords = params.optionalWords;
+ this.optionalWords = params.optionalWords
/**
* Possible values are "lastWords" "firstWords" "allOptionnal" "none" (default)
* @see https://www.algolia.com/doc#removeWordsIfNoResults
* @member {string}
*/
- this.removeWordsIfNoResults = params.removeWordsIfNoResults;
+ this.removeWordsIfNoResults = params.removeWordsIfNoResults
/**
* List of attributes to retrieve
* @see https://www.algolia.com/doc#attributesToRetrieve
* @member {string}
*/
- this.attributesToRetrieve = params.attributesToRetrieve;
+ this.attributesToRetrieve = params.attributesToRetrieve
/**
* List of attributes to highlight
* @see https://www.algolia.com/doc#attributesToHighlight
* @member {string}
*/
- this.attributesToHighlight = params.attributesToHighlight;
+ this.attributesToHighlight = params.attributesToHighlight
/**
* Code to be embedded on the left part of the highlighted results
* @see https://www.algolia.com/doc#highlightPreTag
* @member {string}
*/
- this.highlightPreTag = params.highlightPreTag;
+ this.highlightPreTag = params.highlightPreTag
/**
* Code to be embedded on the right part of the highlighted results
* @see https://www.algolia.com/doc#highlightPostTag
* @member {string}
*/
- this.highlightPostTag = params.highlightPostTag;
+ this.highlightPostTag = params.highlightPostTag
/**
* List of attributes to snippet
* @see https://www.algolia.com/doc#attributesToSnippet
* @member {string}
*/
- this.attributesToSnippet = params.attributesToSnippet;
+ this.attributesToSnippet = params.attributesToSnippet
/**
* Enable the ranking informations in the response
* @see https://www.algolia.com/doc#getRankingInfo
* @member {integer}
*/
- this.getRankingInfo = params.getRankingInfo;
+ this.getRankingInfo = params.getRankingInfo
/**
* Remove duplicates based on the index setting attributeForDistinct
* @see https://www.algolia.com/doc#distinct
* @member {boolean}
*/
- this.distinct = params.distinct;
+ this.distinct = params.distinct
/**
* Center of the geo search.
* @see https://www.algolia.com/doc#aroundLatLng
* @member {string}
*/
- this.aroundLatLng = params.aroundLatLng;
+ this.aroundLatLng = params.aroundLatLng
/**
* Center of the search, retrieve from the user IP.
* @see https://www.algolia.com/doc#aroundLatLngViaIP
* @member {boolean}
*/
- this.aroundLatLngViaIP = params.aroundLatLngViaIP;
+ this.aroundLatLngViaIP = params.aroundLatLngViaIP
/**
* Radius of the geo search.
* @see https://www.algolia.com/doc#aroundRadius
* @member {number}
*/
- this.aroundRadius = params.aroundRadius;
+ this.aroundRadius = params.aroundRadius
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc#aroundPrecision
* @member {number}
*/
- this.aroundPrecision = params.aroundPrecision;
+ this.aroundPrecision = params.aroundPrecision
/**
* Geo search inside a box.
* @see https://www.algolia.com/doc#insideBoundingBox
* @member {string}
*/
- this.insideBoundingBox = params.insideBoundingBox;
-};
+ this.insideBoundingBox = params.insideBoundingBox
+}
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
-SearchParameters.make = function makeSearchParameters( newParameters ) {
- var instance = new SearchParameters( newParameters );
- return deepFreeze( instance );
-};
+SearchParameters.make = function makeSearchParameters(newParameters) {
+ var instance = new SearchParameters(newParameters)
+
+ return deepFreeze(instance)
+}
/**
* Validates the new parameters based on the previous state
@@ -313,29 +314,30 @@ SearchParameters.make = function makeSearchParameters( newParameters ) {
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
-SearchParameters.validate = function( currentState, parameters ) {
- var params = parameters || {};
-
- var ks = keys( params );
- var unknownKeys = filter( ks, function( k ) {
- return !currentState.hasOwnProperty( k );
- } );
- if( unknownKeys.length === 1 ) return new Error( "Property " + unknownKeys[0] + " is not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html )" );
- if( unknownKeys.length > 1 ) return new Error( "Properties " + unknownKeys.join( " " ) + " are not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html )" );
-
- if( currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0 ) {
- return new Error( "[Tags] Can't switch from the managed tag API to the advanced API. It is probably an error, if it's really what you want, you should first clear the tags with clearTags method." );
+SearchParameters.validate = function(currentState, parameters) {
+ var params = parameters || {}
+
+ var ks = keys(params)
+ var unknownKeys = filter(ks, function(k) {
+ return !currentState.hasOwnProperty(k)
+ })
+
+ if (unknownKeys.length === 1) return new Error('Property ' + unknownKeys[0] + ' is not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)')
+ if (unknownKeys.length > 1) return new Error('Properties ' + unknownKeys.join(' ') + ' are not defined on SearchParameters (see http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)')
+
+ if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
+ return new Error("[Tags] Can't switch from the managed tag API to the advanced API. It is probably an error, if it's really what you want, you should first clear the tags with clearTags method.")
}
- if( currentState.tagRefinements.length > 0 && params.tagFilters ) {
- return new Error( "[Tags] Can't switch from the advanced tag API to the managed API. It is probably an error, if it's not, you should first clear the tags with clearTags method." );
+ if (currentState.tagRefinements.length > 0 && params.tagFilters) {
+ return new Error("[Tags] Can't switch from the advanced tag API to the managed API. It is probably an error, if it's not, you should first clear the tags with clearTags method.")
}
- return null;
-};
+ return null
+}
SearchParameters.prototype = {
- constructor : SearchParameters,
+ constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
@@ -346,28 +348,28 @@ SearchParameters.prototype = {
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
- clearRefinements : function clearRefinements( attribute ) {
- return this.setQueryParameters( {
- page : 0,
- numericRefinements : this._clearNumericRefinements( attribute ),
- facetsRefinements : RefinementList.clearRefinement( this.facetsRefinements, attribute, "conjunctiveFacet" ),
- facetsExcludes : RefinementList.clearRefinement( this.facetsExcludes, attribute, "exclude" ),
- disjunctiveFacetsRefinements : RefinementList.clearRefinement( this.disjunctiveFacetsRefinements, attribute, "disjunctiveFacet" )
- } );
+ clearRefinements: function clearRefinements(attribute) {
+ return this.setQueryParameters({
+ page: 0,
+ numericRefinements: this._clearNumericRefinements(attribute),
+ facetsRefinements: RefinementList.clearRefinement(this.facetsRefinements, attribute, 'conjunctiveFacet'),
+ facetsExcludes: RefinementList.clearRefinement(this.facetsExcludes, attribute, 'exclude'),
+ disjunctiveFacetsRefinements: RefinementList.clearRefinement(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet')
+ })
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
- clearTags : function clearTags() {
- if( this.tagFilters === undefined && this.tagRefinements.length === 0 ) return this;
+ clearTags: function clearTags() {
+ if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this
- return this.setQueryParameters( {
- page : 0,
- tagFilters : undefined,
- tagRefinements : []
- } );
+ return this.setQueryParameters({
+ page: 0,
+ tagFilters: undefined,
+ tagRefinements: []
+ })
},
/**
* Query setter
@@ -375,13 +377,13 @@ SearchParameters.prototype = {
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
- setQuery : function setQuery( newQuery ) {
- if( newQuery === this.query ) return this;
+ setQuery: function setQuery(newQuery) {
+ if (newQuery === this.query) return this
- return this.setQueryParameters( {
- query : newQuery,
- page : 0
- } );
+ return this.setQueryParameters({
+ query: newQuery,
+ page: 0
+ })
},
/**
* Page setter
@@ -389,12 +391,12 @@ SearchParameters.prototype = {
* @param {number} newPage new page number
* @return {SearchParameters}
*/
- setPage : function setPage( newPage ) {
- if( newPage === this.page ) return this;
+ setPage: function setPage(newPage) {
+ if (newPage === this.page) return this
- return this.setQueryParameters( {
- page : newPage
- } );
+ return this.setQueryParameters({
+ page: newPage
+ })
},
/**
* Facets setter
@@ -403,10 +405,10 @@ SearchParameters.prototype = {
* @param {string[]} facets all the attributes of the algolia records used for conjunctive facetting
* @return {SearchParameters}
*/
- setFacets : function setFacets( facets ) {
- return this.setQueryParameters( {
- facets : facets
- } );
+ setFacets: function setFacets(facets) {
+ return this.setQueryParameters({
+ facets: facets
+ })
},
/**
* Disjunctive facets setter
@@ -415,10 +417,10 @@ SearchParameters.prototype = {
* @param {string[]} facets all the attributes of the algolia records used for disjunctive facetting
* @return {SearchParameters}
*/
- setDisjunctiveFacets : function setDisjunctiveFacets( facets ) {
- return this.setQueryParameters( {
- disjunctiveFacets : facets
- } );
+ setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
+ return this.setQueryParameters({
+ disjunctiveFacets: facets
+ })
},
/**
* HitsPerPage setter
@@ -427,13 +429,13 @@ SearchParameters.prototype = {
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
- setHitsPerPage : function setHitsPerPage( n ) {
- if( this.hitsPerPage === n ) return this;
+ setHitsPerPage: function setHitsPerPage(n) {
+ if (this.hitsPerPage === n) return this
- return this.setQueryParameters( {
- hitsPerPage : n,
- page : 0
- } );
+ return this.setQueryParameters({
+ hitsPerPage: n,
+ page: 0
+ })
},
/**
* typoTolerance setter
@@ -442,94 +444,95 @@ SearchParameters.prototype = {
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
- setTypoTolerance : function setTypoTolerance( typoTolerance ) {
- if( this.typoTolerance === typoTolerance ) return this;
+ setTypoTolerance: function setTypoTolerance(typoTolerance) {
+ if (this.typoTolerance === typoTolerance) return this
- return this.setQueryParameters( {
- typoTolerance : typoTolerance,
- page : 0
- } );
+ return this.setQueryParameters({
+ typoTolerance: typoTolerance,
+ page: 0
+ })
},
/**
* Add or update a numeric filter for a given attribute
- * Current limitation of the numeric filters : you can't have more than one value
+ * Current limitation of the numeric filters: you can't have more than one value
* filtered for each (attribute, oprator). It means that you can't have a filter
- * for ( "attribute", "=", 3 ) and ( "attribute", "=", 8 )
+ * for ("attribute", "=", 3 ) and ("attribute", "=", 8)
* @method
* @param {string} attribute attribute to set the filter on
- * @param {string} operator operator of the filter ( possible values : =, >, >=, <, <=, != )
+ * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number} value value of the filter
* @return {SearchParameters}
*/
- addNumericRefinement : function( attribute, operator, value ) {
- if( this.isNumericRefined( attribute, operator, value ) ) return this;
+ addNumericRefinement: function(attribute, operator, value) {
+ if (this.isNumericRefined(attribute, operator, value)) return this
+
+ var mod = extend({}, this.numericRefinements)
- var mod = extend( {}, this.numericRefinements );
- mod[ attribute ] = extend( {}, mod[ attribute ] );
- mod[ attribute ][ operator ] = value;
+ mod[attribute] = extend({}, mod[attribute])
+ mod[attribute][operator] = value
- return this.setQueryParameters( {
- page : 0,
- numericRefinements : mod
- } );
+ return this.setQueryParameters({
+ page: 0,
+ numericRefinements: mod
+ })
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
- getConjunctiveRefinements : function( facetName ) {
- return this.facetsRefinements[ facetName ] || [];
+ getConjunctiveRefinements: function(facetName) {
+ return this.facetsRefinements[facetName] || []
},
/**
* Get the list of disjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
- getDisjunctiveRefinements : function( facetName ) {
- return this.disjunctiveFacetsRefinements[ facetName ] || [];
+ getDisjunctiveRefinements: function(facetName) {
+ return this.disjunctiveFacetsRefinements[facetName] || []
},
/**
* Get the list of exclude refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
- getExcludeRefinements : function( facetName ) {
- return this.facetsExcludes[ facetName ] || [];
+ getExcludeRefinements: function(facetName) {
+ return this.facetsExcludes[facetName] || []
},
/**
* Remove a numeric filter
* @method
* @param {string} attribute attribute to set the filter on
- * @param {string} operator operator of the filter ( possible values : =, >, >=, <, <=, != )
+ * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @return {SearchParameters}
*/
- removeNumericRefinement : function( attribute, operator ) {
- if( !this.isNumericRefined( attribute, operator ) ) return this;
+ removeNumericRefinement: function(attribute, operator) {
+ if (!this.isNumericRefined(attribute, operator)) return this
- return this.setQueryParameters( {
- page : 0,
- numericRefinements : this._clearNumericRefinements( function( value, key ) {
- return key === attribute && value.op === operator;
- } )
- } );
+ return this.setQueryParameters({
+ page: 0,
+ numericRefinements: this._clearNumericRefinements(function(value, key) {
+ return key === attribute && value.op === operator
+ })
+ })
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
- getNumericRefinements : function( facetName ) {
- return this.numericRefinements[ facetName ] || [];
+ getNumericRefinements: function(facetName) {
+ return this.numericRefinements[facetName] || []
},
/**
- * Return the current refinement for the ( attribute, operator )
+ * Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
- getNumericRefinement : function( attribute, operator ) {
- return this.numericRefinements[ attribute ] && this.numericRefinements[ attribute ][ operator ];
+ getNumericRefinement: function(attribute, operator) {
+ return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]
},
/**
* Clear numeric filters.
@@ -541,22 +544,21 @@ SearchParameters.prototype = {
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.}
*/
- _clearNumericRefinements : function _clearNumericRefinements( attribute ) {
- if ( isUndefined( attribute ) ) {
- return {};
- }
- else if ( isString( attribute ) ) {
- return omit( this.numericRefinements, attribute );
- }
- else if ( isFunction( attribute ) ) {
- return reduce( this.numericRefinements, function( memo, operators, key ) {
- var operatorList = omit( operators, function( value, operator ) {
- return attribute( { val : value, op : operator }, key, "numeric" );
- } );
-
- if( !isEmpty( operatorList ) ) memo[ key ] = operatorList;
- return memo;
- }, {} );
+ _clearNumericRefinements: function _clearNumericRefinements(attribute) {
+ if (isUndefined(attribute)) {
+ return {}
+ } else if (isString(attribute)) {
+ return omit(this.numericRefinements, attribute)
+ } else if (isFunction(attribute)) {
+ return reduce(this.numericRefinements, function(memo, operators, key) {
+ var operatorList = omit(operators, function(value, operator) {
+ return attribute({val: value, op: operator}, key, 'numeric')
+ })
+
+ if (!isEmpty(operatorList)) memo[key] = operatorList
+
+ return memo
+ }, {})
}
},
/**
@@ -566,12 +568,13 @@ SearchParameters.prototype = {
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
- addFacetRefinement : function addFacetRefinement( facet, value ) {
- if( RefinementList.isRefined( this.facetsRefinements, facet, value ) ) return this;
- return this.setQueryParameters( {
- page : 0,
- facetsRefinements : RefinementList.addRefinement( this.facetsRefinements, facet, value )
- } );
+ addFacetRefinement: function addFacetRefinement(facet, value) {
+ if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this
+
+ return this.setQueryParameters({
+ page: 0,
+ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)
+ })
},
/**
* Exclude a value from a "normal" facet
@@ -580,12 +583,13 @@ SearchParameters.prototype = {
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
- addExcludeRefinement : function addExcludeRefinement( facet, value ) {
- if( RefinementList.isRefined( this.facetsExcludes, facet, value ) ) return this;
- return this.setQueryParameters( {
- page : 0,
- facetsExcludes : RefinementList.addRefinement( this.facetsExcludes, facet, value )
- } );
+ addExcludeRefinement: function addExcludeRefinement(facet, value) {
+ if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this
+
+ return this.setQueryParameters({
+ page: 0,
+ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)
+ })
},
/**
* Adds a refinement on a disjunctive facet.
@@ -594,27 +598,28 @@ SearchParameters.prototype = {
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
- addDisjunctiveFacetRefinement : function addDisjunctiveFacetRefinement( facet, value ) {
- if( RefinementList.isRefined( this.disjunctiveFacetsRefinements, facet, value ) ) return this;
- return this.setQueryParameters( {
- page : 0,
- disjunctiveFacetsRefinements : RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value )
- } );
+ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
+ if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this
+
+ return this.setQueryParameters({
+ page: 0,
+ disjunctiveFacetsRefinements: RefinementList.addRefinement(this.disjunctiveFacetsRefinements, facet, value)
+ })
},
/**
* addTagRefinement adds a tag to the list used to filter the results
* @param {string} tag tag to be added
* @return {SearchParameters}
*/
- addTagRefinement : function addTagRefinement( tag ) {
- if( this.isTagRefined( tag ) ) return this;
+ addTagRefinement: function addTagRefinement(tag) {
+ if (this.isTagRefined(tag)) return this
var modification = {
- page : 0,
- tagRefinements : this.tagRefinements.concat( tag )
- };
+ page: 0,
+ tagRefinements: this.tagRefinements.concat(tag)
+ }
- return this.setQueryParameters( modification );
+ return this.setQueryParameters(modification)
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
@@ -625,13 +630,13 @@ SearchParameters.prototype = {
* @param {string} value value used to filter
* @return {SearchParameters}
*/
- removeFacetRefinement : function removeFacetRefinement( facet, value ) {
- if( !RefinementList.isRefined( this.facetsRefinements, facet, value ) ) return this;
+ removeFacetRefinement: function removeFacetRefinement(facet, value) {
+ if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this
- return this.setQueryParameters( {
- page : 0,
- facetsRefinements : RefinementList.removeRefinement( this.facetsRefinements, facet, value )
- } );
+ return this.setQueryParameters({
+ page: 0,
+ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)
+ })
},
/**
* Remove a negative refinement on a facet
@@ -640,13 +645,13 @@ SearchParameters.prototype = {
* @param {string} value value used to filter
* @return {SearchParameters}
*/
- removeExcludeRefinement : function removeExcludeRefinement( facet, value ) {
- if( !RefinementList.isRefined( this.facetsExcludes, facet, value ) ) return this;
+ removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
+ if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this
- return this.setQueryParameters( {
- page : 0,
- facetsExcludes : RefinementList.removeRefinement( this.facetsExcludes, facet, value )
- } );
+ return this.setQueryParameters({
+ page: 0,
+ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)
+ })
},
/**
* Remove a refinement on a disjunctive facet
@@ -655,13 +660,13 @@ SearchParameters.prototype = {
* @param {string} value value used to filter
* @return {SearchParameters}
*/
- removeDisjunctiveFacetRefinement : function removeDisjunctiveFacetRefinement( facet, value ) {
- if( !RefinementList.isRefined( this.disjunctiveFacetsRefinements, facet, value ) ) return this;
+ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
+ if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this
- return this.setQueryParameters( {
- page : 0,
- disjunctiveFacetsRefinements : RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value )
- } );
+ return this.setQueryParameters({
+ page: 0,
+ disjunctiveFacetsRefinements: RefinementList.removeRefinement(this.disjunctiveFacetsRefinements, facet, value)
+ })
},
/**
* Remove a tag from the list of tag refinements
@@ -669,15 +674,15 @@ SearchParameters.prototype = {
* @param {string} tag the tag to remove
* @return {SearchParameters}
*/
- removeTagRefinement : function removeTagRefinement( tag ) {
- if( !this.isTagRefined( tag ) ) return this;
+ removeTagRefinement: function removeTagRefinement(tag) {
+ if (!this.isTagRefined(tag)) return this
var modification = {
- page : 0,
- tagRefinements : filter( this.tagRefinements, function( t ) { return t !== tag; } )
- };
+ page: 0,
+ tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag })
+ }
- return this.setQueryParameters( modification );
+ return this.setQueryParameters(modification)
},
/**
* Switch the refinement applied over a facet/value
@@ -686,11 +691,11 @@ SearchParameters.prototype = {
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
- toggleFacetRefinement : function toggleFacetRefinement( facet, value ) {
- return this.setQueryParameters( {
- page : 0,
- facetsRefinements : RefinementList.toggleRefinement( this.facetsRefinements, facet, value )
- } );
+ toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
+ return this.setQueryParameters({
+ page: 0,
+ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value)
+ })
},
/**
* Switch the refinement applied over a facet/value
@@ -699,11 +704,11 @@ SearchParameters.prototype = {
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
- toggleExcludeFacetRefinement : function toggleExcludeFacetRefinement( facet, value ) {
- return this.setQueryParameters( {
- page : 0,
- facetsExcludes : RefinementList.toggleRefinement( this.facetsExcludes, facet, value )
- } );
+ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
+ return this.setQueryParameters({
+ page: 0,
+ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value)
+ })
},
/**
* Switch the refinement applied over a facet/value
@@ -712,11 +717,11 @@ SearchParameters.prototype = {
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
- toggleDisjunctiveFacetRefinement : function toggleDisjunctiveFacetRefinement( facet, value ) {
- return this.setQueryParameters( {
- page : 0,
- disjunctiveFacetsRefinements : RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value )
- } );
+ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
+ return this.setQueryParameters({
+ page: 0,
+ disjunctiveFacetsRefinements: RefinementList.toggleRefinement(this.disjunctiveFacetsRefinements, facet, value)
+ })
},
/**
* Switch the tag refinement
@@ -724,13 +729,12 @@ SearchParameters.prototype = {
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
- toggleTagRefinement : function toggleTagRefinement( tag ) {
- if( this.isTagRefined( tag ) ) {
- return this.removeTagRefinement( tag );
- }
- else {
- return this.addTagRefinement( tag );
+ toggleTagRefinement: function toggleTagRefinement(tag) {
+ if (this.isTagRefined(tag)) {
+ return this.removeTagRefinement(tag)
}
+
+ return this.addTagRefinement(tag)
},
/**
* Test if the facet name is from one of the disjunctive facets
@@ -738,8 +742,8 @@ SearchParameters.prototype = {
* @param {string} facet facet name to test
* @return {boolean}
*/
- isDisjunctiveFacet : function( facet ) {
- return this.disjunctiveFacets.indexOf( facet ) > -1;
+ isDisjunctiveFacet: function(facet) {
+ return this.disjunctiveFacets.indexOf(facet) > -1
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
@@ -747,8 +751,8 @@ SearchParameters.prototype = {
* @param {string} facet facet name to test
* @return {boolean}
*/
- isConjunctiveFacet : function( facet ) {
- return this.facets.indexOf( facet ) > -1;
+ isConjunctiveFacet: function(facet) {
+ return this.facets.indexOf(facet) > -1
},
/**
* Returns true if the facet is refined, either for a specific value or in
@@ -759,8 +763,8 @@ SearchParameters.prototype = {
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
- isFacetRefined : function isFacetRefined( facet, value ) {
- return RefinementList.isRefined( this.facetsRefinements, facet, value );
+ isFacetRefined: function isFacetRefined(facet, value) {
+ return RefinementList.isRefined(this.facetsRefinements, facet, value)
},
/**
* Returns true if the facet contains exclusions or if a specific value is
@@ -771,8 +775,8 @@ SearchParameters.prototype = {
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
- isExcludeRefined : function isExcludeRefined( facet, value ) {
- return RefinementList.isRefined( this.facetsExcludes, facet, value );
+ isExcludeRefined: function isExcludeRefined(facet, value) {
+ return RefinementList.isRefined(this.facetsExcludes, facet, value)
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
@@ -783,8 +787,8 @@ SearchParameters.prototype = {
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
- isDisjunctiveFacetRefined : function isDisjunctiveFacetRefined( facet, value ) {
- return RefinementList.isRefined( this.disjunctiveFacetsRefinements, facet, value );
+ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
+ return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)
},
/**
* Test if the triple (attribute, operator, value) is already refined.
@@ -796,15 +800,15 @@ SearchParameters.prototype = {
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
- isNumericRefined : function isNumericRefined( attribute, operator, value ) {
- if( isUndefined( value ) ) {
- return this.numericRefinements[ attribute ] &&
- !isUndefined( this.numericRefinements[ attribute ][ operator ] );
+ isNumericRefined: function isNumericRefined(attribute, operator, value) {
+ if (isUndefined(value)) {
+ return this.numericRefinements[attribute] &&
+ !isUndefined(this.numericRefinements[attribute][operator])
}
- return this.numericRefinements[ attribute ] &&
- !( isUndefined( this.numericRefinements[ attribute ][ operator ] ) ) &&
- this.numericRefinements[ attribute ][ operator ] === value;
+ return this.numericRefinements[attribute] &&
+ !isUndefined(this.numericRefinements[attribute][operator]) &&
+ this.numericRefinements[attribute][operator] === value
},
/**
* Returns true if the tag refined, false otherwise
@@ -812,8 +816,8 @@ SearchParameters.prototype = {
* @param {string} tag the tag to check
* @return {boolean}
*/
- isTagRefined : function isTagRefined( tag ) {
- return this.tagRefinements.indexOf( tag ) !== -1;
+ isTagRefined: function isTagRefined(tag) {
+ return this.tagRefinements.indexOf(tag) !== -1
},
/**
* Returns the list of all disjunctive facets refined
@@ -822,49 +826,54 @@ SearchParameters.prototype = {
* @param {value} value value used for filtering
* @return {string[]}
*/
- getRefinedDisjunctiveFacets : function getRefinedDisjunctiveFacets() {
+ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
// attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection(
- keys( this.numericRefinements ),
+ keys(this.numericRefinements),
this.disjunctiveFacets
- );
- return keys( this.disjunctiveFacetsRefinements ).concat( disjunctiveNumericRefinedFacets );
+ )
+
+ return keys(this.disjunctiveFacetsRefinements).concat(disjunctiveNumericRefinedFacets)
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
- getUnrefinedDisjunctiveFacets : function() {
- var refinedFacets = this.getRefinedDisjunctiveFacets();
- return filter( this.disjunctiveFacets, function( f ) {
- return refinedFacets.indexOf( f ) === -1;
- } );
+ getUnrefinedDisjunctiveFacets: function() {
+ var refinedFacets = this.getRefinedDisjunctiveFacets()
+
+ return filter(this.disjunctiveFacets, function(f) {
+ return refinedFacets.indexOf(f) === -1
+ })
},
- managedParameters : [
- "facets", "disjunctiveFacets", "facetsRefinements",
- "facetsExcludes", "disjunctiveFacetsRefinements",
- "numericRefinements", "tagRefinements"
- ],
- getQueryParams : function getQueryParams() {
- var managedParameters = this.managedParameters;
- return reduce( this, function( memo, value, parameter, parameters ) {
- if( managedParameters.indexOf( parameter ) === -1 &&
- parameters[ parameter ] !== undefined ) {
- memo[ parameter ] = value;
+
+ managedParameters: [
+ 'facets', 'disjunctiveFacets', 'facetsRefinements',
+ 'facetsExcludes', 'disjunctiveFacetsRefinements',
+ 'numericRefinements', 'tagRefinements'
+ ],
+ getQueryParams: function getQueryParams() {
+ var managedParameters = this.managedParameters
+
+ return reduce(this, function(memo, value, parameter, parameters) {
+ if (managedParameters.indexOf(parameter) === -1 &&
+ parameters[parameter] !== undefined) {
+ memo[parameter] = value
}
- return memo;
- }, {} );
+
+ return memo
+ }, {})
},
/**
* Let the user retrieve any parameter value from the SearchParameters
* @param {string} paramName name of the parameter
* @return {any} the value of the parameter
*/
- getQueryParameter : function getQueryParameter( paramName ) {
- if( !this.hasOwnProperty( paramName ) ) throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters (http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)" );
+ getQueryParameter: function getQueryParameter(paramName) {
+ if (!this.hasOwnProperty(paramName)) throw new Error("Parameter '" + paramName + "' is not an attribute of SearchParameters (http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)")
- return this[ paramName ];
+ return this[paramName]
},
/**
* Let the user set a specific value for a given parameter. Will return the
@@ -875,12 +884,14 @@ SearchParameters.prototype = {
* @param {any} value the value to be set, must be compliant with the definition of the attribute on the object
* @return {SearchParameters} the updated state
*/
- setQueryParameter : function setParameter( parameter, value ) {
- if( this[ parameter ] === value ) return this;
+ setQueryParameter: function setParameter(parameter, value) {
+ if (this[parameter] === value) return this
+
+ var modification = {}
- var modification = {};
- modification[ parameter ] = value;
- return this.setQueryParameters( modification );
+ modification[parameter] = value
+
+ return this.setQueryParameters(modification)
},
/**
* Let the user set any of the parameters with a plain object.
@@ -889,19 +900,22 @@ SearchParameters.prototype = {
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
- setQueryParameters : function setQueryParameters( params ) {
- var error = SearchParameters.validate( this, params );
- if( error ) {
- throw error;
+ setQueryParameters: function setQueryParameters(params) {
+ var error = SearchParameters.validate(this, params)
+
+ if (error) {
+ throw error
}
- return this.mutateMe( function merge( newInstance ) {
- var ks = keys( params );
- forEach( ks, function( k ) {
- newInstance[ k ] = params[ k ];
- } );
- return newInstance;
- } );
+ return this.mutateMe(function merge(newInstance) {
+ var ks = keys(params)
+
+ forEach(ks, function(k) {
+ newInstance[k] = params[k]
+ })
+
+ return newInstance
+ })
},
/**
* Helper function to make it easier to build new instances from a mutating
@@ -911,12 +925,13 @@ SearchParameters.prototype = {
* change the value of the newMutable to the desired state
* @return {SearchParameters} a new instance with the specified modifications applied
*/
- mutateMe : function mutateMe( fn ) {
- var newState = new ( this.constructor )( this );
- fn( newState, this );
- return deepFreeze( newState );
+ mutateMe: function mutateMe(fn) {
+ var newState = new this.constructor(this)
+
+ fn(newState, this)
+ return deepFreeze(newState)
}
-};
+}
/**
* Callback used for clearRefinement method
@@ -927,4 +942,4 @@ SearchParameters.prototype = {
* depending on the type of facet
* @return {boolean}
*/
-module.exports = SearchParameters;
+module.exports = SearchParameters
diff --git a/src/SearchResults/index.js b/src/SearchResults/index.js
index d2a777f2b4..4dc5ef9258 100644
--- a/src/SearchResults/index.js
+++ b/src/SearchResults/index.js
@@ -1,28 +1,30 @@
-"use strict";
-var forEach = require( "lodash/collection/forEach" );
-var compact = require( "lodash/array/compact" );
-var sum = require( "lodash/collection/sum" );
-var find = require( "lodash/collection/find" );
+'use strict'
+var forEach = require('lodash/collection/forEach')
+var compact = require('lodash/array/compact')
+var sum = require('lodash/collection/sum')
+var find = require('lodash/collection/find')
-var extend = require( "../functions/extend" );
+var extend = require('../functions/extend')
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
- * @property {object.} data the facetting data : value, number of entries
+ * @property {object.} data the facetting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
-function getIndices( obj ) {
- var indices = {};
- forEach( obj, function( val, idx ) { indices[ val ] = idx; } );
- return indices;
+function getIndices(obj) {
+ var indices = {}
+
+ forEach(obj, function(val, idx) { indices[val] = idx })
+
+ return indices
}
-function assignFacetStats( dest, facetStats, key ) {
- if ( facetStats && facetStats[key] ) {
- dest.stats = facetStats[key];
+function assignFacetStats(dest, facetStats, key) {
+ if (facetStats && facetStats[key]) {
+ dest.stats = facetStats[key]
}
}
@@ -35,268 +37,272 @@ function assignFacetStats( dest, facetStats, key ) {
* @param {object} algoliaResponse the response from algolia client
* @example SearchResults of the first query in the instant search demo
{
- "hitsPerPage" : 10,
- "processingTimeMS" : 2,
- "facets" : [
+ "hitsPerPage": 10,
+ "processingTimeMS": 2,
+ "facets": [
{
- "name" : "type",
- "data" : {
- "HardGood" : 6627,
- "BlackTie" : 550,
- "Music" : 665,
- "Software" : 131,
- "Game" : 456,
- "Movie" : 1571
+ "name": "type",
+ "data": {
+ "HardGood": 6627,
+ "BlackTie": 550,
+ "Music": 665,
+ "Software": 131,
+ "Game": 456,
+ "Movie": 1571
},
- "exhaustive" : false
+ "exhaustive": false
},
{
- "exhaustive" : false,
- "data" : {
- "Free shipping" : 5507
+ "exhaustive": false,
+ "data": {
+ "Free shipping": 5507
},
- "name" : "shipping"
+ "name": "shipping"
}
- ],
- "hits" : [
+ ],
+ "hits": [
{
- "thumbnailImage" : "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
- "_highlightResult" : {
- "shortDescription" : {
- "matchLevel" : "none",
- "value" : "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
- "matchedWords" : []
+ "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
+ "_highlightResult": {
+ "shortDescription": {
+ "matchLevel": "none",
+ "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
+ "matchedWords": []
},
- "category" : {
- "matchLevel" : "none",
- "value" : "Computer Security Software",
- "matchedWords" : []
+ "category": {
+ "matchLevel": "none",
+ "value": "Computer Security Software",
+ "matchedWords": []
},
- "manufacturer" : {
- "matchedWords" : [],
- "value" : "Webroot",
- "matchLevel" : "none"
+ "manufacturer": {
+ "matchedWords": [],
+ "value": "Webroot",
+ "matchLevel": "none"
},
- "name" : {
- "value" : "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
- "matchedWords" : [],
- "matchLevel" : "none"
+ "name": {
+ "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
+ "matchedWords": [],
+ "matchLevel": "none"
}
},
- "image" : "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
- "shipping" : "Free shipping",
- "bestSellingRank" : 4,
- "shortDescription" : "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
- "url" : "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
- "name" : "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
- "category" : "Computer Security Software",
- "salePrice_range" : "1 - 50",
- "objectID" : "1688832",
- "type" : "Software",
- "customerReviewCount" : 5980,
- "salePrice" : 49.99,
- "manufacturer" : "Webroot"
+ "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
+ "shipping": "Free shipping",
+ "bestSellingRank": 4,
+ "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
+ "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
+ "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
+ "category": "Computer Security Software",
+ "salePrice_range": "1 - 50",
+ "objectID": "1688832",
+ "type": "Software",
+ "customerReviewCount": 5980,
+ "salePrice": 49.99,
+ "manufacturer": "Webroot"
},
....
- ],
- "nbHits" : 10000,
- "disjunctiveFacets" : [
+ ],
+ "nbHits": 10000,
+ "disjunctiveFacets": [
{
- "exhaustive" : false,
- "data" : {
- "5" : 183,
- "12" : 112,
- "7" : 149,
+ "exhaustive": false,
+ "data": {
+ "5": 183,
+ "12": 112,
+ "7": 149,
...
},
- "name" : "customerReviewCount",
- "stats" : {
- "max" : 7461,
- "avg" : 157.939,
- "min" : 1
+ "name": "customerReviewCount",
+ "stats": {
+ "max": 7461,
+ "avg": 157.939,
+ "min": 1
}
},
{
- "data" : {
- "Printer Ink" : 142,
- "Wireless Speakers" : 60,
- "Point & Shoot Cameras" : 48,
+ "data": {
+ "Printer Ink": 142,
+ "Wireless Speakers": 60,
+ "Point & Shoot Cameras": 48,
...
},
- "name" : "category",
- "exhaustive" : false
+ "name": "category",
+ "exhaustive": false
},
{
- "exhaustive" : false,
- "data" : {
- "> 5000" : 2,
- "1 - 50" : 6524,
- "501 - 2000" : 566,
- "201 - 500" : 1501,
- "101 - 200" : 1360,
- "2001 - 5000" : 47
+ "exhaustive": false,
+ "data": {
+ "> 5000": 2,
+ "1 - 50": 6524,
+ "501 - 2000": 566,
+ "201 - 500": 1501,
+ "101 - 200": 1360,
+ "2001 - 5000": 47
},
- "name" : "salePrice_range"
+ "name": "salePrice_range"
},
{
- "data" : {
- "Dynex™" : 202,
- "Insignia™" : 230,
- "PNY" : 72,
+ "data": {
+ "Dynex™": 202,
+ "Insignia™": 230,
+ "PNY": 72,
...
},
- "name" : "manufacturer",
- "exhaustive" : false
+ "name": "manufacturer",
+ "exhaustive": false
}
- ],
- "query" : "",
- "nbPages" : 100,
- "page" : 0,
- "index" : "bestbuy"
+ ],
+ "query": "",
+ "nbPages": 100,
+ "page": 0,
+ "index": "bestbuy"
}
**/
-var SearchResults = function( state, algoliaResponse ) {
- var mainSubResponse = algoliaResponse.results[ 0 ];
+function SearchResults(state, algoliaResponse) {
+ var mainSubResponse = algoliaResponse.results[0]
/**
* query used to generate the results
* @member {string}
*/
- this.query = mainSubResponse.query;
+ this.query = mainSubResponse.query
/**
* all the records that match the search parameters. It also contains _highlightResult,
* which describe which and how the attributes are matched.
* @member {object[]}
*/
- this.hits = mainSubResponse.hits;
+ this.hits = mainSubResponse.hits
/**
* index where the results come from
* @member {string}
*/
- this.index = mainSubResponse.index;
+ this.index = mainSubResponse.index
/**
* number of hits per page requested
* @member {number}
*/
- this.hitsPerPage = mainSubResponse.hitsPerPage;
+ this.hitsPerPage = mainSubResponse.hitsPerPage
/**
* total number of hits of this query on the index
* @member {number}
*/
- this.nbHits = mainSubResponse.nbHits;
+ this.nbHits = mainSubResponse.nbHits
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
- this.nbPages = mainSubResponse.nbPages;
+ this.nbPages = mainSubResponse.nbPages
/**
* current page
* @member {number}
*/
- this.page = mainSubResponse.page;
+ this.page = mainSubResponse.page
/**
* sum of the processing time of all the queries
* @member {number}
*/
- this.processingTimeMS = sum( algoliaResponse.results, "processingTimeMS" );
+ this.processingTimeMS = sum(algoliaResponse.results, 'processingTimeMS')
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
- this.disjunctiveFacets = [];
+ this.disjunctiveFacets = []
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
- this.facets = [];
+ this.facets = []
- var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
+ var disjunctiveFacets = state.getRefinedDisjunctiveFacets()
- var facetsIndices = getIndices( state.facets );
- var disjunctiveFacetsIndices = getIndices( state.disjunctiveFacets );
+ var facetsIndices = getIndices(state.facets)
+ var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets)
- //Since we send request only for disjunctive facets that have been refined,
- //we get the facets informations from the first, general, response.
- forEach( mainSubResponse.facets, function( facetValueObject, facetKey ) {
- var isFacetDisjunctive = state.disjunctiveFacets.indexOf( facetKey ) !== -1;
- var position = isFacetDisjunctive ? disjunctiveFacetsIndices[ facetKey ] :
- facetsIndices[ facetKey ];
- if( isFacetDisjunctive ) {
- this.disjunctiveFacets[ position ] = {
- name : facetKey,
- data : facetValueObject,
- exhaustive : mainSubResponse.exhaustiveFacetsCount
- };
- assignFacetStats( this.disjunctiveFacets[ position ], mainSubResponse.facets_stats, facetKey );
- }
- else {
- this.facets[ position ] = {
- name : facetKey,
- data : facetValueObject,
- exhaustive : mainSubResponse.exhaustiveFacetsCount
- };
- assignFacetStats( this.facets[ position ], mainSubResponse.facets_stats, facetKey );
+ // Since we send request only for disjunctive facets that have been refined,
+ // we get the facets informations from the first, general, response.
+ forEach(mainSubResponse.facets, function(facetValueObject, facetKey) {
+ var isFacetDisjunctive = state.disjunctiveFacets.indexOf(facetKey) !== -1
+ var position = isFacetDisjunctive ? disjunctiveFacetsIndices[facetKey] :
+ facetsIndices[facetKey]
+
+ if (isFacetDisjunctive) {
+ this.disjunctiveFacets[position] = {
+ name: facetKey,
+ data: facetValueObject,
+ exhaustive: mainSubResponse.exhaustiveFacetsCount
+ }
+ assignFacetStats(this.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey)
+ } else {
+ this.facets[position] = {
+ name: facetKey,
+ data: facetValueObject,
+ exhaustive: mainSubResponse.exhaustiveFacetsCount
+ }
+ assignFacetStats(this.facets[position], mainSubResponse.facets_stats, facetKey)
}
- }, this );
+ }, this)
// aggregate the refined disjunctive facets
- forEach( disjunctiveFacets, function( disjunctiveFacet, idx ) {
- var result = algoliaResponse.results[ idx + 1 ];
+ forEach(disjunctiveFacets, function(disjunctiveFacet, idx) {
+ var result = algoliaResponse.results[idx + 1]
// There should be only item in facets.
- forEach( result.facets, function( facetResults, dfacet ) {
- var position = disjunctiveFacetsIndices[ dfacet ];
+ forEach(result.facets, function(facetResults, dfacet) {
+ var position = disjunctiveFacetsIndices[dfacet]
+
+ var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}
- var dataFromMainRequest = ( mainSubResponse.facets && mainSubResponse.facets[ dfacet ] ) || {};
- this.disjunctiveFacets[ position ] = {
- name : dfacet,
- data : extend( {}, dataFromMainRequest, facetResults ),
- exhaustive : result.exhaustiveFacetsCount
- };
- assignFacetStats( this.disjunctiveFacets[ position ], result.facets_stats, dfacet );
+ this.disjunctiveFacets[position] = {
+ name: dfacet,
+ data: extend({}, dataFromMainRequest, facetResults),
+ exhaustive: result.exhaustiveFacetsCount
+ }
+ assignFacetStats(this.disjunctiveFacets[position], result.facets_stats, dfacet)
- if ( state.disjunctiveFacetsRefinements[dfacet] ) {
- forEach( state.disjunctiveFacetsRefinements[ dfacet ], function( refinementValue ) {
+ if (state.disjunctiveFacetsRefinements[dfacet]) {
+ forEach(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
- if ( !this.disjunctiveFacets[position].data[refinementValue] &&
- state.disjunctiveFacetsRefinements[dfacet].indexOf( refinementValue ) > -1 ) {
- this.disjunctiveFacets[position].data[refinementValue] = 0;
+ if (!this.disjunctiveFacets[position].data[refinementValue] &&
+ state.disjunctiveFacetsRefinements[dfacet].indexOf(refinementValue) > -1) {
+ this.disjunctiveFacets[position].data[refinementValue] = 0
}
- }, this );
+ }, this)
}
- }, this );
- }, this );
+ }, this)
+ }, this)
// add the excludes
- forEach( state.facetsExcludes, function( excludes, facetName ) {
- var position = facetsIndices[ facetName ];
- this.facets[ position ] = {
- name : facetName,
- data : mainSubResponse.facets[ facetName ],
- exhaustive : mainSubResponse.exhaustiveFacetsCount
- };
- forEach( excludes, function( facetValue ) {
- this.facets[ position ] = this.facets[ position ] || { name : facetName };
- this.facets[ position ].data = this.facets[ position ].data || {};
- this.facets[ position ].data[ facetValue ] = 0;
- }, this );
- }, this );
+ forEach(state.facetsExcludes, function(excludes, facetName) {
+ var position = facetsIndices[facetName]
+
+ this.facets[position] = {
+ name: facetName,
+ data: mainSubResponse.facets[facetName],
+ exhaustive: mainSubResponse.exhaustiveFacetsCount
+ }
+ forEach(excludes, function(facetValue) {
+ this.facets[position] = this.facets[position] || {name: facetName}
+ this.facets[position].data = this.facets[position].data || {}
+ this.facets[position].data[facetValue] = 0
+ }, this)
+ }, this)
- this.facets = compact( this.facets );
- this.disjunctiveFacets = compact( this.disjunctiveFacets );
+ this.facets = compact(this.facets)
+ this.disjunctiveFacets = compact(this.disjunctiveFacets)
- this._state = state;
-};
+ this._state = state
+}
/**
* Get a facet object with its name
* @param {string} name name of the attribute facetted
* @return {SearchResults.Facet} the facet object
*/
-SearchResults.prototype.getFacetByName = function( name ) {
- var isName = function( facet ) { return facet.name === name; };
- var indexInFacets = find( this.facets, isName );
- return indexInFacets || find( this.disjunctiveFacets, isName );
-};
+SearchResults.prototype.getFacetByName = function(name) {
+ var isName = function(facet) { return facet.name === name }
+
+ var indexInFacets = find(this.facets, isName)
+
+ return indexInFacets || find(this.disjunctiveFacets, isName)
+}
-module.exports = SearchResults;
+module.exports = SearchResults
diff --git a/src/algoliasearch.helper.js b/src/algoliasearch.helper.js
index 53a57b6105..e6a3bdb1ed 100644
--- a/src/algoliasearch.helper.js
+++ b/src/algoliasearch.helper.js
@@ -1,78 +1,78 @@
-"use strict";
-var SearchParameters = require( "./SearchParameters" );
-var SearchResults = require( "./SearchResults" );
-var extend = require( "./functions/extend" );
-var util = require( "util" );
-var events = require( "events" );
-var forEach = require( "lodash/collection/forEach" );
-var isEmpty = require( "lodash/lang/isEmpty" );
-var bind = require( "lodash/function/bind" );
+'use strict'
+var SearchParameters = require('./SearchParameters')
+var SearchResults = require('./SearchResults')
+var extend = require('./functions/extend')
+var util = require('util')
+var events = require('events')
+var forEach = require('lodash/collection/forEach')
+var isEmpty = require('lodash/lang/isEmpty')
+var bind = require('lodash/function/bind')
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
- * search. It provides an event based interface for search callbacks :
- * - change : when the internal search state is changed.
+ * search. It provides an event based interface for search callbacks:
+ * - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the {@link SearchResults} of the last result if any.
- * - result : when the response is retrieved from Algolia and is processed.
+ * - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the {@link SearchParameters} corresponding to this answer.
- * - error : when the response is an error. This event contains the error returned by the server.
+ * - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
*/
-function AlgoliaSearchHelper( client, index, options ) {
- this.client = client;
- this.index = index;
- this.state = SearchParameters.make( options );
- this.lastResults = null;
- this._queryId = 0;
- this._lastQueryIdReceived = -1;
+function AlgoliaSearchHelper(client, index, options) {
+ this.client = client
+ this.index = index
+ this.state = SearchParameters.make(options)
+ this.lastResults = null
+ this._queryId = 0
+ this._lastQueryIdReceived = -1
}
-util.inherits( AlgoliaSearchHelper, events.EventEmitter );
+util.inherits(AlgoliaSearchHelper, events.EventEmitter)
/**
* Start the search with the parameters set in the state.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.search = function() {
- this._search();
- return this;
-};
+ this._search()
+ return this
+}
/**
* Sets the query. Also sets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.setQuery = function( q ) {
- this.state = this.state.setQuery( q );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.setQuery = function(q) {
+ this.state = this.state.setQuery(q)
+ this._change()
+ return this
+}
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @param {string} [name] - If given, name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.clearRefinements = function( name ) {
- this.state = this.state.clearRefinements( name );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
+ this.state = this.state.clearRefinements(name)
+ this._change()
+ return this
+}
/**
* Remove all the tag filtering
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
- this.state = this.state.clearTags();
- this._change();
- return this;
-};
+ this.state = this.state.clearTags()
+ this._change()
+ return this
+}
/**
* Ensure a facet refinement exists
@@ -80,11 +80,11 @@ AlgoliaSearchHelper.prototype.clearTags = function() {
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function( facet, value ) {
- this.state = this.state.addDisjunctiveFacetRefinement( facet, value );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function(facet, value) {
+ this.state = this.state.addDisjunctiveFacetRefinement(facet, value)
+ this._change()
+ return this
+}
/**
* Add a numeric refinement on the given attribute
@@ -93,11 +93,11 @@ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function( facet, value ) {
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.addNumericRefinement = function( attribute, operator, value ) {
- this.state = this.state.addNumericRefinement( attribute, operator, value );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
+ this.state = this.state.addNumericRefinement(attribute, operator, value)
+ this._change()
+ return this
+}
/**
* Ensure a facet refinement exists
@@ -105,11 +105,11 @@ AlgoliaSearchHelper.prototype.addNumericRefinement = function( attribute, operat
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.addRefine = function( facet, value ) {
- this.state = this.state.addFacetRefinement( facet, value );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.addRefine = function(facet, value) {
+ this.state = this.state.addFacetRefinement(facet, value)
+ this._change()
+ return this
+}
/**
* Ensure a facet exclude exists
@@ -117,22 +117,22 @@ AlgoliaSearchHelper.prototype.addRefine = function( facet, value ) {
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.addExclude = function( facet, value ) {
- this.state = this.state.addExcludeRefinement( facet, value );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.addExclude = function(facet, value) {
+ this.state = this.state.addExcludeRefinement(facet, value)
+ this._change()
+ return this
+}
/**
* Add a tag refinement
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.addTag = function( tag ) {
- this.state = this.state.addTagRefinement( tag );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.addTag = function(tag) {
+ this.state = this.state.addTagRefinement(tag)
+ this._change()
+ return this
+}
/**
* Remove a numeric filter.
@@ -141,11 +141,11 @@ AlgoliaSearchHelper.prototype.addTag = function( tag ) {
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.removeNumericRefinement = function( attribute, operator, value ) {
- this.state = this.state.removeNumericRefinement( attribute, operator, value );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
+ this.state = this.state.removeNumericRefinement(attribute, operator, value)
+ this._change()
+ return this
+}
/**
* Ensure a facet refinement does not exist
@@ -153,11 +153,11 @@ AlgoliaSearchHelper.prototype.removeNumericRefinement = function( attribute, ope
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function( facet, value ) {
- this.state = this.state.removeDisjunctiveFacetRefinement( facet, value );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function(facet, value) {
+ this.state = this.state.removeDisjunctiveFacetRefinement(facet, value)
+ this._change()
+ return this
+}
/**
* Ensure a facet refinement does not exist
@@ -165,11 +165,11 @@ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function( facet, value )
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.removeRefine = function( facet, value ) {
- this.state = this.state.removeFacetRefinement( facet, value );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.removeRefine = function(facet, value) {
+ this.state = this.state.removeFacetRefinement(facet, value)
+ this._change()
+ return this
+}
/**
* Ensure a facet exclude does not exist
@@ -177,22 +177,22 @@ AlgoliaSearchHelper.prototype.removeRefine = function( facet, value ) {
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.removeExclude = function( facet, value ) {
- this.state = this.state.removeExcludeRefinement( facet, value );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.removeExclude = function(facet, value) {
+ this.state = this.state.removeExcludeRefinement(facet, value)
+ this._change()
+ return this
+}
/**
* Ensure that a tag is not filtering the results
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.removeTag = function( tag ) {
- this.state = this.state.removeTagRefinement( tag );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.removeTag = function(tag) {
+ this.state = this.state.removeTagRefinement(tag)
+ this._change()
+ return this
+}
/**
* Toggle refinement state of an exclude
@@ -200,11 +200,11 @@ AlgoliaSearchHelper.prototype.removeTag = function( tag ) {
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.toggleExclude = function( facet, value ) {
- this.state = this.state.toggleExcludeFacetRefinement( facet, value );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.toggleExclude = function(facet, value) {
+ this.state = this.state.toggleExcludeFacetRefinement(facet, value)
+ this._change()
+ return this
+}
/**
* Toggle refinement state of a facet
@@ -212,74 +212,71 @@ AlgoliaSearchHelper.prototype.toggleExclude = function( facet, value ) {
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.toggleRefine = function( facet, value ) {
- if( this.state.isConjunctiveFacet( facet ) ) {
- this.state = this.state.toggleFacetRefinement( facet, value );
- }
- else if( this.state.isDisjunctiveFacet( facet ) ) {
- this.state = this.state.toggleDisjunctiveFacetRefinement( facet, value );
+AlgoliaSearchHelper.prototype.toggleRefine = function(facet, value) {
+ if (this.state.isConjunctiveFacet(facet)) {
+ this.state = this.state.toggleFacetRefinement(facet, value)
+ } else if (this.state.isDisjunctiveFacet(facet)) {
+ this.state = this.state.toggleDisjunctiveFacetRefinement(facet, value)
+ } else {
+ console.log("warning: you're trying to refine the undeclared facet '" + facet +
+ "'; add it to the helper options 'facets' or 'disjunctiveFacets'")
+ return this
}
- else {
- /* eslint-disable */
- console.log( "warning : you're trying to refine the undeclared facet '" + facet +
- "'; add it to the helper options 'facets' or 'disjunctiveFacets'" );
- /* eslint-enable */
- return this;
- }
- this._change();
- return this;
-};
+
+ this._change()
+ return this
+}
/**
* Toggle tag refinement
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.toggleTag = function( tag ) {
- this.state = this.state.toggleTagRefinement( tag );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
+ this.state = this.state.toggleTagRefinement(tag)
+ this._change()
+ return this
+}
/**
* Go to next page
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
- return this.setCurrentPage( this.state.page + 1 );
-};
+ return this.setCurrentPage(this.state.page + 1)
+}
/**
* Go to previous page
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
- return this.setCurrentPage( this.state.page - 1 );
-};
+ return this.setCurrentPage(this.state.page - 1)
+}
/**
* Change the current page
* @param {integer} page The page number
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.setCurrentPage = function( page ) {
- if( page < 0 ) throw new Error( "Page requested below 0." );
+AlgoliaSearchHelper.prototype.setCurrentPage = function(page) {
+ if (page < 0) throw new Error('Page requested below 0.')
- this.state = this.state.setPage( page );
- this._change();
- return this;
-};
+ this.state = this.state.setPage(page)
+ this._change()
+ return this
+}
/**
* Configure the underlying index name
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.setIndex = function( name ) {
- this.index = name;
- this.setCurrentPage( 0 );
- return this;
-};
+AlgoliaSearchHelper.prototype.setIndex = function(name) {
+ this.index = name
+ this.setCurrentPage(0)
+ return this
+}
/**
* Update any single parameter of the state/configuration (based on SearchParameters).
@@ -287,26 +284,26 @@ AlgoliaSearchHelper.prototype.setIndex = function( name ) {
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.setQueryParameter = function( parameter, value ) {
- var newState = this.state.setQueryParameter( parameter, value );
+AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
+ var newState = this.state.setQueryParameter(parameter, value)
- if( this.state === newState ) return this;
+ if (this.state === newState) return this
- this.state = newState;
- this._change();
- return this;
-};
+ this.state = newState
+ this._change()
+ return this
+}
/**
- * Set the whole state ( warning : will erase previous state )
+ * Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
*/
-AlgoliaSearchHelper.prototype.setState = function( newState ) {
- this.state = new SearchParameters( newState );
- this._change();
- return this;
-};
+AlgoliaSearchHelper.prototype.setState = function(newState) {
+ this.state = new SearchParameters(newState)
+ this._change()
+ return this
+}
/**
* Override the current state without triggering a change event.
@@ -315,19 +312,19 @@ AlgoliaSearchHelper.prototype.setState = function( newState ) {
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
- * helper.on( "change", function( state ){
+ * helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
- * updateYourURL( state );
- * } );
- * window.onpopstate = function( event ){
+ * updateYourURL(state)
+ * } )
+ * window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
- * helper.overrideStateWithoutTriggeringChangeEvent( event.state ).search();
+ * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
*/
-AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function( newState ) {
- this.state = new SearchParameters( newState );
- return this;
-};
+AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
+ this.state = new SearchParameters(newState)
+ return this
+}
/**
* Check the refinement state of a given value for a facet
@@ -335,25 +332,26 @@ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = functi
* @param {string} value the associated value
* @return {boolean} true if refined
*/
-AlgoliaSearchHelper.prototype.isRefined = function( facet, value ) {
- if( this.state.isConjunctiveFacet( facet ) ) {
- return this.state.isFacetRefined( facet, value );
+AlgoliaSearchHelper.prototype.isRefined = function(facet, value) {
+ if (this.state.isConjunctiveFacet(facet)) {
+ return this.state.isFacetRefined(facet, value)
+ } else if (this.state.isDisjunctiveFacet(facet)) {
+ return this.state.isDisjunctiveFacetRefined(facet, value)
}
- else if( this.state.isDisjunctiveFacet( facet ) ) {
- return this.state.isDisjunctiveFacetRefined( facet, value );
- }
- return false;
-};
+
+ return false
+}
/**
* Check if the attribute has any numeric, disjunctive or conjunctive refinements
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
*/
-AlgoliaSearchHelper.prototype.hasRefinements = function( attribute ) {
- var attributeHasNumericRefinements = !isEmpty( this.state.getNumericRefinements( attribute ) );
- return attributeHasNumericRefinements || this.isRefined( attribute );
-};
+AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
+ var attributeHasNumericRefinements = !isEmpty(this.state.getNumericRefinements(attribute))
+
+ return attributeHasNumericRefinements || this.isRefined(attribute)
+}
/**
* Check the exclude state of a facet
@@ -361,9 +359,9 @@ AlgoliaSearchHelper.prototype.hasRefinements = function( attribute ) {
* @param {string} value the associated value
* @return {boolean} true if refined
*/
-AlgoliaSearchHelper.prototype.isExcluded = function( facet, value ) {
- return this.state.isExcludeRefined( facet, value );
-};
+AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) {
+ return this.state.isExcludeRefined(facet, value)
+}
/**
* Check the refinement state of the disjunctive facet
@@ -371,100 +369,103 @@ AlgoliaSearchHelper.prototype.isExcluded = function( facet, value ) {
* @param {string} value the associated value
* @return {boolean} true if refined
*/
-AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function( facet, value ) {
- return this.state.isDisjunctiveFacetRefined( facet, value );
-};
+AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) {
+ return this.state.isDisjunctiveFacetRefined(facet, value)
+}
/**
* Check if the string is a currently filtering tag
* @param {string} tag tag to check
* @return {boolean}
*/
-AlgoliaSearchHelper.prototype.isTagRefined = function( tag ) {
- return this.state.isTagRefined( tag );
-};
+AlgoliaSearchHelper.prototype.isTagRefined = function(tag) {
+ return this.state.isTagRefined(tag)
+}
/**
* Get the underlying configured index name
* @return {string}
*/
AlgoliaSearchHelper.prototype.getIndex = function() {
- return this.index;
-};
+ return this.index
+}
/**
* Get the currently selected page
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getCurrentPage = function() {
- return this.state.page;
-};
+ return this.state.page
+}
/**
* Get all the filtering tags
* @return {string[]}
*/
AlgoliaSearchHelper.prototype.getTags = function() {
- return this.state.tagRefinements;
-};
+ return this.state.tagRefinements
+}
/**
* Get a parameter of the search by its name
* @param {string} parameterName the parameter name
* @return {any} the parameter value
*/
-AlgoliaSearchHelper.prototype.getQueryParameter = function( parameterName ) {
- return this.state.getQueryParameter( parameterName );
-};
+AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) {
+ return this.state.getQueryParameter(parameterName)
+}
/**
* Get the list of refinements for a given attribute.
* @param {string} facetName attribute name used for facetting
* @return {Refinement[]} All Refinement are objects that contain a value, and a type. Numeric also contains an operator.
*/
-AlgoliaSearchHelper.prototype.getRefinements = function( facetName ) {
- var refinements = [];
-
- if( this.state.isConjunctiveFacet( facetName ) ) {
- var conjRefinements = this.state.getConjunctiveRefinements( facetName );
- forEach( conjRefinements, function( r ) {
- refinements.push( {
- value : r,
- type : "conjunctive"
- } );
- } );
- }
- else if( this.state.isDisjunctiveFacet( facetName ) ) {
- var disjRefinements = this.state.getDisjunctiveRefinements( facetName );
- forEach( disjRefinements, function( r ) {
- refinements.push( {
- value : r,
- type : "disjunctive"
- } );
- } );
+AlgoliaSearchHelper.prototype.getRefinements = function(facetName) {
+ var refinements = []
+
+ if (this.state.isConjunctiveFacet(facetName)) {
+ var conjRefinements = this.state.getConjunctiveRefinements(facetName)
+
+ forEach(conjRefinements, function(r) {
+ refinements.push({
+ value: r,
+ type: 'conjunctive'
+ })
+ })
+ } else if (this.state.isDisjunctiveFacet(facetName)) {
+ var disjRefinements = this.state.getDisjunctiveRefinements(facetName)
+
+ forEach(disjRefinements, function(r) {
+ refinements.push({
+ value: r,
+ type: 'disjunctive'
+ })
+ })
}
- var excludeRefinements = this.state.getExcludeRefinements( facetName );
- forEach( excludeRefinements, function( r ) {
- refinements.push( {
- value : r,
- type : "exclude"
- } );
- } );
+ var excludeRefinements = this.state.getExcludeRefinements(facetName)
- var numericRefinements = this.state.getNumericRefinements( facetName );
- forEach( numericRefinements, function( value, operator ) {
- refinements.push( {
- value : value,
- operator : operator,
- type : "numeric"
- } );
- } );
+ forEach(excludeRefinements, function(r) {
+ refinements.push({
+ value: r,
+ type: 'exclude'
+ })
+ })
- return refinements;
-};
+ var numericRefinements = this.state.getNumericRefinements(facetName)
-///////////// PRIVATE
+ forEach(numericRefinements, function(value, operator) {
+ refinements.push({
+ value: value,
+ operator: operator,
+ type: 'numeric'
+ })
+ })
+
+ return refinements
+}
+
+// /////////// PRIVATE
/**
* Perform the underlying queries
@@ -472,14 +473,14 @@ AlgoliaSearchHelper.prototype.getRefinements = function( facetName ) {
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._search = function() {
- var state = this.state;
+ var state = this.state
- this.client.search( this._getQueries(),
- bind( this._handleResponse,
- this,
- state,
- this._queryId++ ) );
-};
+ this.client.search(this._getQueries(),
+ bind(this._handleResponse,
+ this,
+ state,
+ this._queryId++))
+}
/**
* Get all the queries to send to the client, those queries can used directly
@@ -488,26 +489,26 @@ AlgoliaSearchHelper.prototype._search = function() {
* @return {object[]} The queries
*/
AlgoliaSearchHelper.prototype._getQueries = function getQueries() {
- var queries = [];
-
- //One query for the hits
- queries.push( {
- indexName : this.index,
- query : this.state.query,
- params : this._getHitsSearchParams()
- } );
-
- //One for each disjunctive facets
- forEach( this.state.getRefinedDisjunctiveFacets(), function( refinedFacet ) {
- queries.push( {
- indexName : this.index,
- query : this.state.query,
- params : this._getDisjunctiveFacetSearchParams( refinedFacet )
- } );
- }, this );
-
- return queries;
-};
+ var queries = []
+
+ // One query for the hits
+ queries.push({
+ indexName: this.index,
+ query: this.state.query,
+ params: this._getHitsSearchParams()
+ })
+
+ // One for each disjunctive facets
+ forEach(this.state.getRefinedDisjunctiveFacets(), function(refinedFacet) {
+ queries.push({
+ indexName: this.index,
+ query: this.state.query,
+ params: this._getDisjunctiveFacetSearchParams(refinedFacet)
+ })
+ }, this)
+
+ return queries
+}
/**
* Transform the response as sent by the server and transform it into a user
@@ -519,22 +520,23 @@ AlgoliaSearchHelper.prototype._getQueries = function getQueries() {
* @param {object} content content of the response
* @return {undefined}
*/
-AlgoliaSearchHelper.prototype._handleResponse = function( state, queryId, err, content ) {
- if( queryId < this._lastQueryIdReceived ) {
+AlgoliaSearchHelper.prototype._handleResponse = function(state, queryId, err, content) {
+ if (queryId < this._lastQueryIdReceived) {
// Outdated answer
- return;
+ return
}
- this._lastQueryIdReceived = queryId;
+ this._lastQueryIdReceived = queryId
- if ( err ) {
- this.emit( "error", err );
- return;
+ if (err) {
+ this.emit('error', err)
+ return
}
- var formattedResponse = this.lastResults = new SearchResults( state, content );
- this.emit( "result", formattedResponse, state );
-};
+ var formattedResponse = this.lastResults = new SearchResults(state, content)
+
+ this.emit('result', formattedResponse, state)
+}
/**
* Build search parameters used to fetch hits
@@ -542,33 +544,34 @@ AlgoliaSearchHelper.prototype._handleResponse = function( state, queryId, err, c
* @return {object.}
*/
AlgoliaSearchHelper.prototype._getHitsSearchParams = function() {
- var query = this.state.query;
- var facets = this.state.facets.concat( this.state.disjunctiveFacets );
- var facetFilters = this._getFacetFilters();
- var numericFilters = this._getNumericFilters();
- var tagFilters = this._getTagFilters();
+ var query = this.state.query
+ var facets = this.state.facets.concat(this.state.disjunctiveFacets)
+ var facetFilters = this._getFacetFilters()
+ var numericFilters = this._getNumericFilters()
+ var tagFilters = this._getTagFilters()
var additionalParams = {
- facets : facets,
- tagFilters : tagFilters
- };
+ facets: facets,
+ tagFilters: tagFilters
+ }
- if( this.state.distinct === true || this.state.distinct === false ) {
- additionalParams.distinct = this.state.distinct;
+ if (this.state.distinct === true || this.state.distinct === false) {
+ additionalParams.distinct = this.state.distinct
}
- if( !this.containsRefinement( query, facetFilters, numericFilters, tagFilters ) ) {
- additionalParams.distinct = false;
+
+ if (!this.containsRefinement(query, facetFilters, numericFilters, tagFilters)) {
+ additionalParams.distinct = false
}
- if( facetFilters.length > 0 ) {
- additionalParams.facetFilters = facetFilters;
+ if (facetFilters.length > 0) {
+ additionalParams.facetFilters = facetFilters
}
- if( numericFilters.length > 0 ) {
- additionalParams.numericFilters = numericFilters;
+ if (numericFilters.length > 0) {
+ additionalParams.numericFilters = numericFilters
}
- return extend( this.state.getQueryParams(), additionalParams );
-};
+ return extend(this.state.getQueryParams(), additionalParams)
+}
/**
* Build search parameters used to fetch a disjunctive facet
@@ -576,45 +579,46 @@ AlgoliaSearchHelper.prototype._getHitsSearchParams = function() {
* @param {string} facet the associated facet name
* @return {object}
*/
-AlgoliaSearchHelper.prototype._getDisjunctiveFacetSearchParams = function( facet ) {
- var query = this.state.query;
- var facetFilters = this._getFacetFilters( facet );
- var numericFilters = this._getNumericFilters( facet );
- var tagFilters = this._getTagFilters();
+AlgoliaSearchHelper.prototype._getDisjunctiveFacetSearchParams = function(facet) {
+ var query = this.state.query
+ var facetFilters = this._getFacetFilters(facet)
+ var numericFilters = this._getNumericFilters(facet)
+ var tagFilters = this._getTagFilters()
var additionalParams = {
- hitsPerPage : 1,
- page : 0,
- attributesToRetrieve : [],
- attributesToHighlight : [],
- attributesToSnippet : [],
- facets : facet,
- tagFilters : tagFilters
- };
-
- if( this.state.distinct === true || this.state.distinct === false ) {
- additionalParams.distinct = this.state.distinct;
+ hitsPerPage: 1,
+ page: 0,
+ attributesToRetrieve: [],
+ attributesToHighlight: [],
+ attributesToSnippet: [],
+ facets: facet,
+ tagFilters: tagFilters
}
- if( !this.containsRefinement( query, facetFilters, numericFilters, tagFilters ) ) {
- additionalParams.distinct = false;
+
+ if (this.state.distinct === true || this.state.distinct === false) {
+ additionalParams.distinct = this.state.distinct
}
- if( numericFilters.length > 0 ) {
- additionalParams.numericFilters = numericFilters;
+ if (!this.containsRefinement(query, facetFilters, numericFilters, tagFilters)) {
+ additionalParams.distinct = false
}
- if( facetFilters.length > 0 ) {
- additionalParams.facetFilters = facetFilters;
+ if (numericFilters.length > 0) {
+ additionalParams.numericFilters = numericFilters
}
- return extend( this.state.getQueryParams(), additionalParams );
-};
+ if (facetFilters.length > 0) {
+ additionalParams.facetFilters = facetFilters
+ }
+
+ return extend(this.state.getQueryParams(), additionalParams)
+}
-AlgoliaSearchHelper.prototype.containsRefinement = function( query, facetFilters, numericFilters, tagFilters ) {
+AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query ||
- facetFilters.length !== 0 ||
- numericFilters.length !== 0 ||
- tagFilters.length !== 0;
-};
+ facetFilters.length !== 0 ||
+ numericFilters.length !== 0 ||
+ tagFilters.length !== 0
+}
/**
* Return the numeric filters in an algolia request fashion
@@ -622,17 +626,19 @@ AlgoliaSearchHelper.prototype.containsRefinement = function( query, facetFilters
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
-AlgoliaSearchHelper.prototype._getNumericFilters = function( facetName ) {
- var numericFilters = [];
- forEach( this.state.numericRefinements, function( operators, attribute ) {
- forEach( operators, function( value, operator ) {
- if( facetName !== attribute ) {
- numericFilters.push( attribute + operator + value );
+AlgoliaSearchHelper.prototype._getNumericFilters = function(facetName) {
+ var numericFilters = []
+
+ forEach(this.state.numericRefinements, function(operators, attribute) {
+ forEach(operators, function(value, operator) {
+ if (facetName !== attribute) {
+ numericFilters.push(attribute + operator + value)
}
- } );
- } );
- return numericFilters;
-};
+ })
+ })
+
+ return numericFilters
+}
/**
* Return the tags filters depending
@@ -640,12 +646,12 @@ AlgoliaSearchHelper.prototype._getNumericFilters = function( facetName ) {
* @return {string}
*/
AlgoliaSearchHelper.prototype._getTagFilters = function() {
- if( this.state.tagFilters ) {
- return this.state.tagFilters;
+ if (this.state.tagFilters) {
+ return this.state.tagFilters
}
- return this.state.tagRefinements.join( "," );
-};
+ return this.state.tagRefinements.join(',')
+}
/**
* Test if there are some disjunctive refinements on the facet
@@ -653,10 +659,10 @@ AlgoliaSearchHelper.prototype._getTagFilters = function() {
* @param {string} facet the attribute to test
* @return {boolean}
*/
-AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function( facet ) {
- return this.state.disjunctiveRefinements[ facet ] &&
- this.state.disjunctiveRefinements[ facet ].length > 0;
-};
+AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) {
+ return this.state.disjunctiveRefinements[facet] &&
+ this.state.disjunctiveRefinements[facet].length > 0
+}
/**
* Build facetFilters parameter based on current refinements. The array returned
@@ -665,35 +671,37 @@ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function( facet ) {
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.}
*/
-AlgoliaSearchHelper.prototype._getFacetFilters = function( facet ) {
- var facetFilters = [];
-
- forEach( this.state.facetsRefinements, function( facetValues, facetName ) {
- forEach( facetValues, function( facetValue ) {
- facetFilters.push( facetName + ":" + facetValue );
- } );
- } );
-
- forEach( this.state.facetsExcludes, function( facetValues, facetName ) {
- forEach( facetValues, function( facetValue ) {
- facetFilters.push( facetName + ":-" + facetValue );
- } );
- } );
-
- forEach( this.state.disjunctiveFacetsRefinements, function( facetValues, facetName ) {
- if( facetName === facet || !facetValues || facetValues.length === 0 ) return;
- var orFilters = [];
- forEach( facetValues, function( facetValue ) {
- orFilters.push( facetName + ":" + facetValue );
- } );
- facetFilters.push( orFilters );
- } );
-
- return facetFilters;
-};
+AlgoliaSearchHelper.prototype._getFacetFilters = function(facet) {
+ var facetFilters = []
+
+ forEach(this.state.facetsRefinements, function(facetValues, facetName) {
+ forEach(facetValues, function(facetValue) {
+ facetFilters.push(facetName + ':' + facetValue)
+ })
+ })
+
+ forEach(this.state.facetsExcludes, function(facetValues, facetName) {
+ forEach(facetValues, function(facetValue) {
+ facetFilters.push(facetName + ':-' + facetValue)
+ })
+ })
+
+ forEach(this.state.disjunctiveFacetsRefinements, function(facetValues, facetName) {
+ if (facetName === facet || !facetValues || facetValues.length === 0) return
+ var orFilters = []
+
+ forEach(facetValues, function(facetValue) {
+ orFilters.push(facetName + ':' + facetValue)
+ })
+
+ facetFilters.push(orFilters)
+ })
+
+ return facetFilters
+}
AlgoliaSearchHelper.prototype._change = function() {
- this.emit( "change", this.state, this.lastResults );
-};
+ this.emit('change', this.state, this.lastResults)
+}
-module.exports = AlgoliaSearchHelper;
+module.exports = AlgoliaSearchHelper
diff --git a/src/functions/deepFreeze.js b/src/functions/deepFreeze.js
index 05263d8238..1f524a9ba6 100644
--- a/src/functions/deepFreeze.js
+++ b/src/functions/deepFreeze.js
@@ -1,6 +1,6 @@
-"use strict";
-var isObject = require( "lodash/lang/isObject" );
-var forEach = require( "lodash/collection/forEach" );
+'use strict'
+var isObject = require('lodash/lang/isObject')
+var forEach = require('lodash/collection/forEach')
/**
* Recursively freeze the parts of an object that are not frozen.
@@ -8,15 +8,15 @@ var forEach = require( "lodash/collection/forEach" );
* @param {object} obj object to freeze
* @return {object} the object frozen
*/
-var deepFreeze = function( obj ) {
- if( !isObject( obj ) ) return obj;
+var deepFreeze = function(obj) {
+ if (!isObject(obj)) return obj
- forEach( obj, deepFreeze );
- if( !Object.isFrozen( obj ) ) {
- Object.freeze( obj );
+ forEach(obj, deepFreeze)
+ if (!Object.isFrozen(obj)) {
+ Object.freeze(obj)
}
- return obj;
-};
+ return obj
+}
-module.exports = deepFreeze;
+module.exports = deepFreeze
diff --git a/src/functions/extend.js b/src/functions/extend.js
index 3cf7359a4f..34d5191ac4 100644
--- a/src/functions/extend.js
+++ b/src/functions/extend.js
@@ -1,15 +1,18 @@
-"use strict";
-module.exports = function extend( out ) {
- out = out || {};
- for ( var i = 1; i < arguments.length; i++ ) {
- if ( !arguments[i] ) {
- continue;
+'use strict'
+module.exports = function extend(out) {
+ out = out || {}
+
+ for (var i = 1; i < arguments.length; i++) {
+ if (!arguments[i]) {
+ continue
}
- for ( var key in arguments[i] ) {
- if ( arguments[i].hasOwnProperty( key ) ) {
- out[key] = arguments[i][key];
+
+ for (var key in arguments[i]) {
+ if (arguments[i].hasOwnProperty(key)) {
+ out[key] = arguments[i][key]
}
}
}
- return out;
-};
+
+ return out
+}
diff --git a/test/integration-spec/helper.filters.js b/test/integration-spec/helper.filters.js
index ba20398fb4..122f121fdc 100644
--- a/test/integration-spec/helper.filters.js
+++ b/test/integration-spec/helper.filters.js
@@ -1,77 +1,81 @@
-"use strict";
+'use strict'
-var random = require( "lodash/number/random" );
-var test = require( "tape" );
-var algoliasearchHelper = process.browser ? window.algoliasearchHelper : require( "../../" );
-var setup = require( "../integration-utils.js" ).setup;
+var random = require('lodash/number/random')
+var test = require('tape')
+var algoliasearchHelper = process.browser ? window.algoliasearchHelper : require('../../')
+var setup = require('../integration-utils.js').setup
-test( "[INT][FILTERS] Should retrieve different values for multi facetted records", function( t ) {
- var indexName = ( process.env.TRAVIS_BUILD_NUMBER ||
- "helper-integration-tests-" ) + "helper_refinements" + random( 0, 5000 );
+test('[INT][FILTERS] Should retrieve different values for multi facetted records', function(t) {
+ var indexName = (process.env.TRAVIS_BUILD_NUMBER ||
+ 'helper-integration-tests-') + 'helper_refinements' + random(0, 5000)
- setup( indexName, function( client, index ) {
- return index.addObjects( [
- { facet : [ "f1", "f2" ] },
- { facet : [ "f1", "f3" ] },
- { facet : [ "f2", "f3" ] }
- ] )
- .then( function() {
- return index.setSettings( {
- attributesToIndex : [ "facet" ],
- attributesForFaceting : [ "facet" ]
- } );
- } )
- .then( function( content ) {
- return index.waitTask( content.taskID );
- } ).then( function() {
- return client;
- } );
- } ).then( function( client ) {
- var helper = algoliasearchHelper( client, indexName, {
- facets : [ "facet" ]
- } );
+ setup(indexName, function(client, index) {
+ return index.addObjects([
+ {facet: ['f1', 'f2']},
+ {facet: ['f1', 'f3']},
+ {facet: ['f2', 'f3']}
+ ])
+ .then(function() {
+ return index.setSettings({
+ attributesToIndex: ['facet'],
+ attributesForFaceting: ['facet']
+ })
+ })
+ .then(function(content) {
+ return index.waitTask(content.taskID)
+ }).then(function() {
+ return client
+ })
+ }).then(function(client) {
+ var helper = algoliasearchHelper(client, indexName, {
+ facets: ['facet']
+ })
- var calls = 0;
- helper.on( "error", function( err ) {
- t.fail( err );
- t.end();
- } );
- helper.on( "result", function( content ) {
- calls++;
- if( calls === 1 ) {
- t.equal( content.hits.length, 2, "filter should result in two items" );
- t.deepEqual( content.facets[ 0 ].data, {
- f1 : 2,
- f2 : 1,
- f3 : 1
- } );
- helper.addRefine( "facet", "f2" ).search();
+ var calls = 0
+ helper.on('error', function(err) {
+ t.fail(err)
+ t.end()
+ })
+ helper.on('result', function(content) {
+ calls++
+
+ if (calls === 1) {
+ t.equal(content.hits.length, 2, 'filter should result in two items')
+ t.deepEqual(content.facets[ 0 ].data, {
+ f1: 2,
+ f2: 1,
+ f3: 1
+ })
+
+ helper.addRefine('facet', 'f2').search()
}
- if( calls === 2 ) {
- t.equal( content.hits.length, 1, "filter should result in one item" );
- t.deepEqual( content.facets[ 0 ].data, {
- f1 : 1,
- f2 : 1
- } );
- helper.toggleRefine( "facet", "f3" ).search();
+
+ if (calls === 2) {
+ t.equal(content.hits.length, 1, 'filter should result in one item')
+ t.deepEqual(content.facets[ 0 ].data, {
+ f1: 1,
+ f2: 1
+ })
+ helper.toggleRefine('facet', 'f3').search()
}
- if( calls === 3 ) {
- t.equal( content.hits.length, 0, "filter should result in 0 item" );
- t.equal( content.facets[ 0 ], undefined );
- helper.removeRefine( "facet", "f2" ).search();
+
+ if (calls === 3) {
+ t.equal(content.hits.length, 0, 'filter should result in 0 item')
+ t.equal(content.facets[ 0 ], undefined)
+ helper.removeRefine('facet', 'f2').search()
}
- if( calls === 4 ) {
- t.equal( content.hits.length, 1, "filter should result in one item again" );
- t.deepEqual( content.facets[ 0 ].data, {
- f1 : 1,
- f3 : 1
- } );
- client.deleteIndex( indexName );
- t.end();
+ if (calls === 4) {
+ t.equal(content.hits.length, 1, 'filter should result in one item again')
+ t.deepEqual(content.facets[0].data, {
+ f1: 1,
+ f3: 1
+ })
+ client.deleteIndex(indexName)
+ t.end()
}
- } );
+ })
- helper.addRefine( "facet", "f1" ).search();
- } );
-} );
+ helper.addRefine('facet', 'f1').search()
+ })
+})
diff --git a/test/integration-spec/helper.highlight.js b/test/integration-spec/helper.highlight.js
index 273a813fc5..5f2a0c023f 100644
--- a/test/integration-spec/helper.highlight.js
+++ b/test/integration-spec/helper.highlight.js
@@ -1,65 +1,63 @@
-"use strict";
+'use strict'
-var random = require( "lodash/number/random" );
-var test = require( "tape" );
-var algoliasearchHelper = process.browser ? window.algoliasearchHelper : require( "../../" );
-var setup = require( "../integration-utils.js" ).setup;
+var random = require('lodash/number/random')
+var test = require('tape')
+var algoliasearchHelper = process.browser ? window.algoliasearchHelper : require('../../')
+var setup = require('../integration-utils.js').setup
-test( "[INT][HIGHLIGHT] The highlight should be consistent with the parameters", function( t ) {
- var indexName = ( process.env.TRAVIS_BUILD_NUMBER ||
- "helper-integration-tests-" ) + "helper_highlight" + random( 0, 5000 );
+test('[INT][HIGHLIGHT] The highlight should be consistent with the parameters', function(t) {
+ var indexName = (process.env.TRAVIS_BUILD_NUMBER ||
+ 'helper-integration-tests-') + 'helper_highlight' + random(0, 5000)
- setup( indexName, function( client, index ) {
- return index.addObjects( [
- { facet : [ "f1", "f2" ] },
- { facet : [ "f1", "f3" ] },
- { facet : [ "f2", "f3" ] }
- ] )
- .then( function() {
- return index.setSettings( {
- attributesToIndex : [ "facet" ],
- attributesForFaceting : [ "facet" ]
- } );
- } )
- .then( function( content ) {
- return index.waitTask( content.taskID );
- } ).then( function() {
- return client;
- } );
- } ).then( function( client ) {
- var helper = algoliasearchHelper( client, indexName, {
- attributesToHighlight : ["facet"],
- facets : [ "facet" ]
- } );
+ setup(indexName, function(client, index) {
+ return index.addObjects([
+ {facet: ['f1', 'f2']},
+ {facet: ['f1', 'f3']},
+ {facet: ['f2', 'f3']}
+ ])
+ .then(function() {
+ return index.setSettings({
+ attributesToIndex: ['facet'],
+ attributesForFaceting: ['facet']
+ })
+ })
+ .then(function(content) {
+ return index.waitTask(content.taskID)
+ }).then(function() {
+ return client
+ })
+ }).then(function(client) {
+ var helper = algoliasearchHelper(client, indexName, {
+ attributesToHighlight: ['facet'],
+ facets: ['facet']
+ })
- var calls = 0;
- helper.on( "result", function( content ) {
- calls++;
- if( calls === 1 ) {
- t.equal( content.hits[0]._highlightResult.facet[0].value,
- "f1",
- "should be hightlighted with em (default)" );
- t.equal( content.hits[1]._highlightResult.facet[0].value,
- "f1",
- "should be hightlighted with em (default)" );
- helper.setQueryParameter( "highlightPostTag", "" )
- .setQueryParameter( "highlightPreTag", "" )
- .search();
+ var calls = 0
+ helper.on('result', function(content) {
+ calls++
+ if (calls === 1) {
+ t.equal(content.hits[0]._highlightResult.facet[0].value,
+ 'f1',
+ 'should be hightlighted with em (default)')
+ t.equal(content.hits[1]._highlightResult.facet[0].value,
+ 'f1',
+ 'should be hightlighted with em (default)')
+ helper.setQueryParameter('highlightPostTag', '')
+ .setQueryParameter('highlightPreTag', '')
+ .search()
+ } else if (calls === 2) {
+ t.equal(content.hits[0]._highlightResult.facet[0].value,
+ 'f1',
+ 'should be hightlighted with strong (setting)')
+ t.equal(content.hits[1]._highlightResult.facet[0].value,
+ 'f1',
+ 'should be hightlighted with strong (setting)')
+ client.deleteIndex(indexName)
+ t.end()
}
- else if( calls === 2 ) {
- t.equal( content.hits[0]._highlightResult.facet[0].value,
- "f1",
- "should be hightlighted with strong (setting)" );
- t.equal( content.hits[1]._highlightResult.facet[0].value,
- "f1",
- "should be hightlighted with strong (setting)" );
- client.deleteIndex( indexName );
- t.end();
- }
- } );
-
- helper.setQuery( "f1" )
- .search();
- } );
-} );
+ })
+ helper.setQuery('f1')
+ .search()
+ })
+})
diff --git a/test/integration-spec/helper.tags.js b/test/integration-spec/helper.tags.js
index 747c577cf8..d4b424ee3e 100644
--- a/test/integration-spec/helper.tags.js
+++ b/test/integration-spec/helper.tags.js
@@ -1,76 +1,82 @@
-"use strict";
+'use strict'
-var random = require( "lodash/number/random" );
-var test = require( "tape" );
-var map = require( "lodash/collection/map" );
+var random = require('lodash/number/random')
+var test = require('tape')
+var map = require('lodash/collection/map')
-var algoliasearchHelper = process.browser ? window.algoliasearchHelper : require( "../../" );
-var setup = require( "../integration-utils.js" ).setup;
+var algoliasearchHelper = process.browser ? window.algoliasearchHelper : require('../../')
+var setup = require('../integration-utils.js').setup
-test( "[INT][TAGS]Test tags operations on the helper and their results on the algolia API", function( t ) {
- var indexName = ( process.env.TRAVIS_BUILD_NUMBER ||
- "helper-integration-tests-" ) + "helper_refinements" + random( 0, 5000 );
+test('[INT][TAGS]Test tags operations on the helper and their results on the algolia API', function(t) {
+ var indexName = (process.env.TRAVIS_BUILD_NUMBER ||
+ 'helper-integration-tests-') + 'helper_refinements' + random(0, 5000)
- setup( indexName, function( client, index ) {
- return index.addObjects( [
- { objectID : "0", _tags : [ "t1", "t2" ] },
- { objectID : "1", _tags : [ "t1", "t3" ] },
- { objectID : "2", _tags : [ "t2", "t3" ] },
- { objectID : "3", _tags : [ "t3", "t4" ] }
- ] )
- .then( function( content ) {
- return index.waitTask( content.taskID );
- } ).then( function() {
- return client;
- } );
- } ).then( function( client ) {
- var helper = algoliasearchHelper( client, indexName, {} );
+ setup(indexName, function(client, index) {
+ return index.addObjects([
+ {objectID: '0', _tags: ['t1', 't2']},
+ {objectID: '1', _tags: ['t1', 't3']},
+ {objectID: '2', _tags: ['t2', 't3']},
+ {objectID: '3', _tags: ['t3', 't4']}
+ ])
+ .then(function(content) {
+ return index.waitTask(content.taskID)
+ }).then(function() {
+ return client
+ })
+ }).then(function(client) {
+ var helper = algoliasearchHelper(client, indexName, {})
- var calls = 0;
- helper.on( "error", function( err ) {
- t.fail( err );
- t.end();
- } );
- helper.on( "result", function( content ) {
- calls++;
- var hitsToParsedID = function( h ) { return parseInt( h.objectID ); };
- if( calls === 1 ) {
- t.equal( content.hits.length, 4, "No tags : 3 results" );
- t.deepEqual( map( content.hits, hitsToParsedID ).sort(),
- [0, 1, 2, 3],
- "No tags expected ids : 0, 1, 2, 3" );
- helper.addTag( "t1" ).search();
- }
- if( calls === 2 ) {
- t.equal( content.hits.length, 2, "One tag (t1) : 2 results" );
- t.deepEqual( map( content.hits, hitsToParsedID ).sort(),
- [0, 1],
- "One tag (t1) expected ids : 0, 1" );
- helper.addTag( "t2" ).search();
+ var calls = 0
+
+ helper.on('error', function(err) {
+ t.fail(err)
+ t.end()
+ })
+
+ helper.on('result', function(content) {
+ calls++
+ var hitsToParsedID = function(h) { return parseInt(h.objectID, 10) }
+
+ if (calls === 1) {
+ t.equal(content.hits.length, 4, 'No tags: 3 results')
+ t.deepEqual(map(content.hits, hitsToParsedID).sort(),
+ [0, 1, 2, 3],
+ 'No tags expected ids: 0, 1, 2, 3')
+ helper.addTag('t1').search()
}
- if( calls === 3 ) {
- t.equal( content.hits.length, 1, "Two tags (t1, t2) : 1 result" );
- t.deepEqual( map( content.hits, hitsToParsedID ).sort(),
- [0],
- "Two tags (t1, t2) expected ids : 0" );
- helper.removeTag( "t2" ).toggleTag( "t3" ).toggleTag( "t1" ).search();
+
+ if (calls === 2) {
+ t.equal(content.hits.length, 2, 'One tag (t1): 2 results')
+ t.deepEqual(map(content.hits, hitsToParsedID).sort(),
+ [0, 1],
+ 'One tag (t1) expected ids: 0, 1')
+ helper.addTag('t2').search()
}
- if( calls === 4 ) {
- t.equal( content.hits.length, 3, "One tag (t3) : 3 results" );
- t.deepEqual( map( content.hits, hitsToParsedID ).sort(),
- [1, 2, 3],
- "One tag (t3) expected ids : 1, 2, 3" );
- helper.clearTags().setQueryParameter( "tagFilters", "t3,(t1,t2)" ).search();
+
+ if (calls === 3) {
+ t.equal(content.hits.length, 1, 'Two tags (t1, t2): 1 result')
+ t.deepEqual(map(content.hits, hitsToParsedID).sort(),
+ [0],
+ 'Two tags (t1, t2) expected ids: 0')
+ helper.removeTag('t2').toggleTag('t3').toggleTag('t1').search()
}
- if( calls === 5 ) {
- t.equal( content.hits.length, 2, "filter should result in two item again" );
- t.deepEqual( map( content.hits, hitsToParsedID ).sort(), [ 1, 2 ] );
- client.deleteIndex( indexName );
- t.end();
+
+ if (calls === 4) {
+ t.equal(content.hits.length, 3, 'One tag (t3): 3 results')
+ t.deepEqual(map(content.hits, hitsToParsedID).sort(),
+ [1, 2, 3],
+ 'One tag (t3) expected ids: 1, 2, 3')
+ helper.clearTags().setQueryParameter('tagFilters', 't3,(t1,t2)').search()
}
- } );
- helper.search();
- } );
+ if (calls === 5) {
+ t.equal(content.hits.length, 2, 'filter should result in two item again')
+ t.deepEqual(map(content.hits, hitsToParsedID).sort(), [1, 2])
+ client.deleteIndex(indexName)
+ t.end()
+ }
+ })
-} );
+ helper.search()
+ })
+})
diff --git a/test/integration-utils.js b/test/integration-utils.js
index 7b1b8888ff..029ca0a1bb 100644
--- a/test/integration-utils.js
+++ b/test/integration-utils.js
@@ -1,21 +1,21 @@
-"use strict";
+'use strict'
-var algoliasearch = require( "algoliasearch" );
+var algoliasearch = require('algoliasearch')
-function setup( indexName, fn ) {
- /* eslint-disable */
- var appID = process.env.INTEGRATION_TEST_APPID;
- var key = process.env.INTEGRATION_TEST_API_KEY;
- /* eslint-enable */
+function setup(indexName, fn) {
+ var appID = process.env.INTEGRATION_TEST_APPID
+ var key = process.env.INTEGRATION_TEST_API_KEY
- var client = algoliasearch( appID, key, { protocol : "https:" } );
- return client.deleteIndex( indexName )
- .then( function( ) {
- var index = client.initIndex( indexName );
- return fn( client, index );
- } );
+ var client = algoliasearch(appID, key, {protocol: 'https:'})
+
+ return client.deleteIndex(indexName)
+ .then(function() {
+ var index = client.initIndex(indexName)
+
+ return fn(client, index)
+ })
}
module.exports = {
- setup : setup
-};
+ setup: setup
+}
diff --git a/test/run.js b/test/run.js
index 027db606ae..20ed1bd80e 100644
--- a/test/run.js
+++ b/test/run.js
@@ -1,9 +1,8 @@
-"use strict";
+'use strict'
-require( "bulk-require" )( __dirname, ["spec/**/*.js"] );
+require('bulk-require')(__dirname, ['spec/**/*.js'])
-if ( process.env.INTEGRATION_TEST_API_KEY && process.env.INTEGRATION_TEST_APPID ) {
+if (process.env.INTEGRATION_TEST_API_KEY && process.env.INTEGRATION_TEST_APPID) {
// usage: INTEGRATION_TEST_APPID=$APPID INTEGRATION_TEST_API_KEY=$APIKEY npm run dev
- require( "bulk-require" )( __dirname, ["integration-spec/**/*.js"] );
+ require('bulk-require')(__dirname, ['integration-spec/**/*.js'])
}
-
diff --git a/test/spec/SearchParameters.addFacetRefinement.js b/test/spec/SearchParameters.addFacetRefinement.js
index 1c7ed580f1..ad9588b563 100644
--- a/test/spec/SearchParameters.addFacetRefinement.js
+++ b/test/spec/SearchParameters.addFacetRefinement.js
@@ -1,40 +1,41 @@
-"use strict";
-var test = require( "tape" );
-var SearchParameters = require( "../../src/SearchParameters" );
+'use strict'
+var test = require('tape')
+var SearchParameters = require('../../src/SearchParameters')
-test( "addFacetRefinement : should add a new item", function( t ) {
- var initialState = SearchParameters.make();
+test('addFacetRefinement: should add a new item', function(t) {
+ var initialState = SearchParameters.make()
- t.deepEqual( initialState.facetsRefinements, {}, "facetsRefinements should be empty at first" );
- var state1 = initialState.addFacetRefinement( "facetName", "facetValue1" );
- t.deepEqual( state1.facetsRefinements, { facetName : [ "facetValue1" ] } );
+ t.deepEqual(initialState.facetsRefinements, {}, 'facetsRefinements should be empty at first')
+ var state1 = initialState.addFacetRefinement('facetName', 'facetValue1')
- t.end();
-} );
+ t.deepEqual(state1.facetsRefinements, {facetName: ['facetValue1']})
-test( "addFacetRefinement : should be able to add more than one item", function( t ) {
+ t.end()
+})
+
+test('addFacetRefinement: should be able to add more than one item', function(t) {
var state = SearchParameters.make()
- .addFacetRefinement( "facetName", "facetValue1" )
- .addFacetRefinement( "facetName", "facetValue2" )
- .addFacetRefinement( "facetName", "facetValue3" );
+ .addFacetRefinement('facetName', 'facetValue1')
+ .addFacetRefinement('facetName', 'facetValue2')
+ .addFacetRefinement('facetName', 'facetValue3')
- t.deepEqual( state.facetsRefinements, { facetName : [ "facetValue1", "facetValue2", "facetValue3" ] } );
+ t.deepEqual(state.facetsRefinements, {facetName: ['facetValue1', 'facetValue2', 'facetValue3']})
- t.end();
-} );
+ t.end()
+})
-test( "addFacetRefinement : should be able to add values for different facet", function( t ) {
+test('addFacetRefinement: should be able to add values for different facet', function(t) {
var state = SearchParameters.make()
- .addFacetRefinement( "facetName1", "facetValue1" )
- .addFacetRefinement( "facetName2", "facetValue2" )
- .addFacetRefinement( "facetName2", "facetValue4" )
- .addFacetRefinement( "facetName3", "facetValue3" );
-
- t.deepEqual( state.facetsRefinements, {
- facetName1 : [ "facetValue1" ],
- facetName2 : [ "facetValue2", "facetValue4" ],
- facetName3 : [ "facetValue3" ]
- } );
-
- t.end();
-} );
+ .addFacetRefinement('facetName1', 'facetValue1')
+ .addFacetRefinement('facetName2', 'facetValue2')
+ .addFacetRefinement('facetName2', 'facetValue4')
+ .addFacetRefinement('facetName3', 'facetValue3')
+
+ t.deepEqual(state.facetsRefinements, {
+ facetName1: ['facetValue1'],
+ facetName2: ['facetValue2', 'facetValue4'],
+ facetName3: ['facetValue3']
+ })
+
+ t.end()
+})
diff --git a/test/spec/SearchParameters.getRefinedDisjunctiveFacets.js b/test/spec/SearchParameters.getRefinedDisjunctiveFacets.js
index 547db19cc1..e264f6718b 100644
--- a/test/spec/SearchParameters.getRefinedDisjunctiveFacets.js
+++ b/test/spec/SearchParameters.getRefinedDisjunctiveFacets.js
@@ -1,39 +1,42 @@
-"use strict";
-var test = require( "tape" );
-var SearchParameters = require( "../../src/SearchParameters" );
+'use strict'
+var test = require('tape')
+var SearchParameters = require('../../src/SearchParameters')
-test( "getRefinedDisjunctiveFacets should return the refined facets declared as disjunctive", function( t ) {
- var sp = new SearchParameters( {
- disjunctiveFacets : [ "myNumericFacet" ]
- } );
+test('getRefinedDisjunctiveFacets should return the refined facets declared as disjunctive', function(t) {
+ var sp = new SearchParameters({
+ disjunctiveFacets: ['myNumericFacet']
+ })
- t.equal( sp.getRefinedDisjunctiveFacets().length, 0, "Should be empty at first" );
- var newState = sp.addNumericRefinement( "myNumericFacet", ">", 3 );
- t.equal( newState.getRefinedDisjunctiveFacets().indexOf( "myNumericFacet" ), 0, "Should contain myNumericFacet" );
+ t.equal(sp.getRefinedDisjunctiveFacets().length, 0, 'Should be empty at first')
+ var newState = sp.addNumericRefinement('myNumericFacet', '>', 3)
- t.end();
-} );
+ t.equal(newState.getRefinedDisjunctiveFacets().indexOf('myNumericFacet'), 0, 'Should contain myNumericFacet')
-test( "getRefinedDisjunctiveFacets should return the refined once even if there are multiple filters on the same facet", function( t ) {
- var sp = new SearchParameters( {
- disjunctiveFacets : [ "myNumericFacet" ]
- } );
+ t.end()
+})
- t.equal( sp.getRefinedDisjunctiveFacets().length, 0, "Should be empty at first" );
- var newState = sp.addNumericRefinement( "myNumericFacet", ">", 3 ).addNumericRefinement( "myNumericFacet", "=", 3 );
- t.equal( newState.getRefinedDisjunctiveFacets().indexOf( "myNumericFacet" ), 0, "Should contain myNumericFacet" );
+test('getRefinedDisjunctiveFacets should return the refined once even if there are multiple filters on the same facet', function(t) {
+ var sp = new SearchParameters({
+ disjunctiveFacets: ['myNumericFacet']
+ })
- t.end();
-} );
+ t.equal(sp.getRefinedDisjunctiveFacets().length, 0, 'Should be empty at first')
+ var newState = sp.addNumericRefinement('myNumericFacet', '>', 3).addNumericRefinement('myNumericFacet', '=', 3)
-test( "getRefinedDisjunctiveFactes should not return refined normal facets", function( t ) {
- var sp = new SearchParameters( {
- facets : [ "myNumericFacet" ]
- } );
+ t.equal(newState.getRefinedDisjunctiveFacets().indexOf('myNumericFacet'), 0, 'Should contain myNumericFacet')
- t.equal( sp.getRefinedDisjunctiveFacets().length, 0, "Should be empty at first" );
- var newState = sp.addNumericRefinement( "myNumericFacet", ">", 3 );
- t.equal( newState.getRefinedDisjunctiveFacets().length, 0, "Should still be empty" );
+ t.end()
+})
- t.end();
-} );
+test('getRefinedDisjunctiveFactes should not return refined normal facets', function(t) {
+ var sp = new SearchParameters({
+ facets: ['myNumericFacet']
+ })
+
+ t.equal(sp.getRefinedDisjunctiveFacets().length, 0, 'Should be empty at first')
+ var newState = sp.addNumericRefinement('myNumericFacet', '>', 3)
+
+ t.equal(newState.getRefinedDisjunctiveFacets().length, 0, 'Should still be empty')
+
+ t.end()
+})
diff --git a/test/spec/SearchParameters.getUnrefinedDisjunctiveFacets.js b/test/spec/SearchParameters.getUnrefinedDisjunctiveFacets.js
index a019bd6396..b733ac6923 100644
--- a/test/spec/SearchParameters.getUnrefinedDisjunctiveFacets.js
+++ b/test/spec/SearchParameters.getUnrefinedDisjunctiveFacets.js
@@ -1,17 +1,17 @@
-"use strict";
-var test = require( "tape" );
-var SearchParameters = require( "../../src/SearchParameters" );
+'use strict'
+var test = require('tape')
+var SearchParameters = require('../../src/SearchParameters')
-test( "getUnrefinedDisjunctiveFacets : should return all non refined disjunctive facet", function( t ) {
- var state0 = SearchParameters.make( {
- disjunctiveFacets : [ "facet1", "facet2", "facet3" ]
- } );
+test('getUnrefinedDisjunctiveFacets: should return all non refined disjunctive facet', function(t) {
+ var state0 = SearchParameters.make({
+ disjunctiveFacets: ['facet1', 'facet2', 'facet3']
+ })
- var state1 = state0.addDisjunctiveFacetRefinement( "facet1", "a" )
- .addDisjunctiveFacetRefinement( "facet3", "x" )
- .addDisjunctiveFacetRefinement( "facet1", "abc" );
+ var state1 = state0.addDisjunctiveFacetRefinement('facet1', 'a')
+ .addDisjunctiveFacetRefinement('facet3', 'x')
+ .addDisjunctiveFacetRefinement('facet1', 'abc')
- t.deepEqual( state1.getUnrefinedDisjunctiveFacets(), [ "facet2" ], "Should only return [ facet2 ]" );
+ t.deepEqual(state1.getUnrefinedDisjunctiveFacets(), ['facet2'], 'Should only return [ facet2 ]')
- t.end();
-} );
+ t.end()
+})
diff --git a/test/spec/SearchParameters.noChanges.js b/test/spec/SearchParameters.noChanges.js
index 98d607aacb..3cefc50bb0 100644
--- a/test/spec/SearchParameters.noChanges.js
+++ b/test/spec/SearchParameters.noChanges.js
@@ -1,132 +1,128 @@
-"use strict";
-var test = require( "tape" );
+'use strict'
+var test = require('tape')
-var SearchParameters = require( "../../src/SearchParameters" );
+var SearchParameters = require('../../src/SearchParameters')
-test( "[No changes] setHitsPerPage", function( t ) {
- var state = SearchParameters.make( {
- hitsPerPage : 2
- } );
+test('[No changes] setHitsPerPage', function(t) {
+ var state = SearchParameters.make({
+ hitsPerPage: 2
+ })
- t.equal( state.setHitsPerPage( 2 ), state, "setHitsPerPage should return the same instance" );
+ t.equal(state.setHitsPerPage(2), state, 'setHitsPerPage should return the same instance')
- t.end();
-} );
+ t.end()
+})
-test( "[No changes] setTypoTolerance", function( t ) {
- var state = SearchParameters.make( {
- typoTolerance : true
- } );
+test('[No changes] setTypoTolerance', function(t) {
+ var state = SearchParameters.make({
+ typoTolerance: true
+ })
- t.equal( state.setTypoTolerance( true ), state, "setTypoTolerance should return the same instance" );
+ t.equal(state.setTypoTolerance(true), state, 'setTypoTolerance should return the same instance')
- t.end();
-} );
+ t.end()
+})
-test( "[No changes] setPage", function( t ) {
- var state = SearchParameters.make( {
- page : 2
- } );
+test('[No changes] setPage', function(t) {
+ var state = SearchParameters.make({
+ page: 2
+ })
- t.equal( state.setPage( 2 ), state, "setPage should return the same instance" );
+ t.equal(state.setPage(2), state, 'setPage should return the same instance')
- t.end();
-} );
+ t.end()
+})
+test('[No changes] setQuery', function(t) {
+ var state = SearchParameters.make({
+ query: 'query'
+ })
-test( "[No changes] setQuery", function( t ) {
- var state = SearchParameters.make( {
- query : "query"
- } );
+ t.equal(state.setQuery('query'), state, 'setQuery should return the same instance')
- t.equal( state.setQuery( "query" ), state, "setQuery should return the same instance" );
+ t.end()
+})
- t.end();
-} );
+test('[No changes] addTagRefinement', function(t) {
+ var state = SearchParameters.make({}).addTagRefinement('tag')
+ t.equal(state.addTagRefinement('tag'), state, 'addTagRefinement should return the same instance')
-test( "[No changes] addTagRefinement", function( t ) {
- var state = SearchParameters.make( {} ).addTagRefinement( "tag" );
+ t.end()
+})
- t.equal( state.addTagRefinement( "tag" ), state, "addTagRefinement should return the same instance" );
+test('[No changes] clearTags', function(t) {
+ var state = SearchParameters.make({
+ query: 'query'
+ })
- t.end();
-} );
+ t.equal(state.clearTags(), state, 'clearTags should return the same instance')
-test( "[No changes] clearTags", function( t ) {
- var state = SearchParameters.make( {
- query : "query"
- } );
+ t.end()
+})
- t.equal( state.clearTags(), state, "clearTags should return the same instance" );
+test('[No changes] addDisjunctiveFacetRefinement', function(t) {
+ var state = SearchParameters.make({
+ disjunctiveFacets: ['facet']
+ }).addDisjunctiveFacetRefinement('facet', 'value')
- t.end();
-} );
+ t.equal(state.addDisjunctiveFacetRefinement('facet', 'value'), state, 'addDisjunctiveFacetRefinement should return the same instance')
+ t.end()
+})
-test( "[No changes] addDisjunctiveFacetRefinement", function( t ) {
- var state = SearchParameters.make( {
- disjunctiveFacets : ["facet"]
- } ).addDisjunctiveFacetRefinement( "facet", "value" );
+test('[No changes] removeDisjunctiveFacetRefinement', function(t) {
+ var state = SearchParameters.make({
+ disjunctiveFacets: ['facet']
+ })
- t.equal( state.addDisjunctiveFacetRefinement( "facet", "value" ), state, "addDisjunctiveFacetRefinement should return the same instance" );
+ t.equal(state.removeDisjunctiveFacetRefinement('facet', 'value'), state, 'removeDisjunctiveFacetRefinement should return the same instance')
- t.end();
-} );
+ t.end()
+})
-test( "[No changes] removeDisjunctiveFacetRefinement", function( t ) {
- var state = SearchParameters.make( {
- disjunctiveFacets : ["facet"]
- } );
+test('[No changes] addFacetRefinement', function(t) {
+ var state = SearchParameters.make({
+ facets: ['facet']
+ }).addFacetRefinement('facet', 'value')
- t.equal( state.removeDisjunctiveFacetRefinement( "facet", "value" ), state, "removeDisjunctiveFacetRefinement should return the same instance" );
+ t.equal(state.addFacetRefinement('facet', 'value'), state, 'addFacetRefinement should return the same instance')
- t.end();
-} );
+ t.end()
+})
+test('[No changes] removeDisjunctiveFacetRefinement', function(t) {
+ var state = SearchParameters.make({
+ facets: ['facet']
+ })
-test( "[No changes] addFacetRefinement", function( t ) {
- var state = SearchParameters.make( {
- facets : ["facet"]
- } ).addFacetRefinement( "facet", "value" );
+ t.equal(state.removeDisjunctiveFacetRefinement('facet', 'value'), state, 'removeDisjunctiveFacetRefinement should return the same instance')
- t.equal( state.addFacetRefinement( "facet", "value" ), state, "addFacetRefinement should return the same instance" );
+ t.end()
+})
- t.end();
-} );
+test('[No changes] addNumericRefinement', function(t) {
+ var state = SearchParameters.make({}).addNumericRefinement('attribute', '>', 0)
-test( "[No changes] removeDisjunctiveFacetRefinement", function( t ) {
- var state = SearchParameters.make( {
- facets : ["facet"]
- } );
+ t.equal(state.addNumericRefinement('attribute', '>', 0), state, 'addNumericRefinement should return the same instance')
- t.equal( state.removeDisjunctiveFacetRefinement( "facet", "value" ), state, "removeDisjunctiveFacetRefinement should return the same instance" );
+ t.end()
+})
- t.end();
-} );
+test('[No changes] removeNumericRefinement', function(t) {
+ var state = SearchParameters.make({})
-test( "[No changes] addNumericRefinement", function( t ) {
- var state = SearchParameters.make( {} ).addNumericRefinement( "attribute", ">", 0 );
+ t.equal(state.removeNumericRefinement('attribute', '>'), state, 'removeNumericRefinement should return the same instance')
- t.equal( state.addNumericRefinement( "attribute", ">", 0 ), state, "addNumericRefinement should return the same instance" );
+ t.end()
+})
- t.end();
-} );
+test('[No changes] setQueryParameter', function(t) {
+ var state = SearchParameters.make({
+ minWordSizefor1Typo: 50
+ })
-test( "[No changes] removeNumericRefinement", function( t ) {
- var state = SearchParameters.make( {} );
+ t.equal(state.setQueryParameter('minWordSizefor1Typo', 50), state, 'setQueryParameter should return the same instance')
- t.equal( state.removeNumericRefinement( "attribute", ">" ), state, "removeNumericRefinement should return the same instance" );
-
- t.end();
-} );
-
-test( "[No changes] setQueryParameter", function( t ) {
- var state = SearchParameters.make( {
- minWordSizefor1Typo : 50
- } );
-
- t.equal( state.setQueryParameter( "minWordSizefor1Typo", 50 ), state, "setQueryParameter should return the same instance" );
-
- t.end();
-} );
+ t.end()
+})
diff --git a/test/spec/SearchParameters.setQueryParameter.js b/test/spec/SearchParameters.setQueryParameter.js
index 8a0d376b67..b28738859e 100644
--- a/test/spec/SearchParameters.setQueryParameter.js
+++ b/test/spec/SearchParameters.setQueryParameter.js
@@ -1,56 +1,56 @@
-"use strict";
-var test = require( "tape" );
-var SearchParameters = require( "../../src/SearchParameters" );
+'use strict'
+var test = require('tape')
+var SearchParameters = require('../../src/SearchParameters')
-test( "setqueryparameter should update existing parameter", function( t ) {
- var sp = new SearchParameters( {
- facets : ["facet"]
- } );
+test('setqueryparameter should update existing parameter', function(t) {
+ var sp = new SearchParameters({
+ facets: ['facet']
+ })
- var newValue = [];
- var newsp = sp.setQueryParameter( "facets", newValue );
+ var newValue = []
+ var newsp = sp.setQueryParameter('facets', newValue)
- t.equal( newsp.facets, newValue, "update of an existing parameter" );
+ t.equal(newsp.facets, newValue, 'update of an existing parameter')
- t.end();
-} );
+ t.end()
+})
-test( "setqueryparameter should add non-existing parameter", function( t ) {
- var sp = new SearchParameters( {
- facets : ["facet"]
- } );
+test('setqueryparameter should add non-existing parameter', function(t) {
+ var sp = new SearchParameters({
+ facets: ['facet']
+ })
- var newValue = [ "attributesToHighlight" ];
- var newsp = sp.setQueryParameter( "attributesToHighlight", newValue );
+ var newValue = ['attributesToHighlight']
+ var newsp = sp.setQueryParameter('attributesToHighlight', newValue)
- t.equal( newsp.attributesToHighlight, newValue, "add new parameter" );
+ t.equal(newsp.attributesToHighlight, newValue, 'add new parameter')
- t.end();
-} );
+ t.end()
+})
-test( "setQueryParameter should not create a new instance if the update is non effective", function( t ) {
- var sp = new SearchParameters( {
- facets : ["facet"],
- maxValuesPerFacet : 10
- } );
+test('setQueryParameter should not create a new instance if the update is non effective', function(t) {
+ var sp = new SearchParameters({
+ facets: ['facet'],
+ maxValuesPerFacet: 10
+ })
- var newValue = 10;
- var newsp = sp.setQueryParameter( "maxValuesPerFacet", newValue );
+ var newValue = 10
+ var newsp = sp.setQueryParameter('maxValuesPerFacet', newValue)
- t.equal( newsp, sp, "No change should result in the same instance" );
+ t.equal(newsp, sp, 'No change should result in the same instance')
- t.end();
-} );
+ t.end()
+})
-test( "setQueryParameter should throw an error when trying to add an unknown parameter", function( t ) {
- var partial = require( "lodash/function/partial" );
+test('setQueryParameter should throw an error when trying to add an unknown parameter', function(t) {
+ var partial = require('lodash/function/partial')
- var sp = new SearchParameters( {
- facets : ["facet"]
- } );
+ var sp = new SearchParameters({
+ facets: ['facet']
+ })
- t.throws( partial( sp.setQueryParameter, "unknown", "" ),
- "Unknown parameter should throw an exception" );
+ t.throws(partial(sp.setQueryParameter, 'unknown', ''),
+ 'Unknown parameter should throw an exception')
- t.end();
-} );
+ t.end()
+})
diff --git a/test/spec/SearchParameters.setQueryParameters.js b/test/spec/SearchParameters.setQueryParameters.js
index d425927e36..6e10c048aa 100644
--- a/test/spec/SearchParameters.setQueryParameters.js
+++ b/test/spec/SearchParameters.setQueryParameters.js
@@ -1,45 +1,45 @@
-"use strict";
-var test = require( "tape" );
-var SearchParameters = require( "../../src/SearchParameters" );
+'use strict'
+var test = require('tape')
+var SearchParameters = require('../../src/SearchParameters')
-test( "setQueryParameters should be able to mix an actual state with a new set of parameters", function( t ) {
- var originalSP = new SearchParameters( {
- facets : [ "a", "b" ],
- ignorePlurals : false,
- attributesToHighlight : ""
- } );
+test('setQueryParameters should be able to mix an actual state with a new set of parameters', function(t) {
+ var originalSP = new SearchParameters({
+ facets: ['a', 'b'],
+ ignorePlurals: false,
+ attributesToHighlight: ''
+ })
var params = {
- facets : [ "a", "c" ],
- attributesToHighlight : [ "city", "country" ],
- replaceSynonymsInHighlight : true
- };
- var newSP = originalSP.setQueryParameters( params );
+ facets: ['a', 'c'],
+ attributesToHighlight: ['city', 'country'],
+ replaceSynonymsInHighlight: true
+ }
+ var newSP = originalSP.setQueryParameters(params)
- t.equal( newSP.facets, params.facets, "Facets should be updated (existing parameter)" );
- t.equal( newSP.attributesToHighlight, newSP.attributesToHighlight, "attributesToHighlight should be updated (existing parameter)" );
- t.equal( newSP.replaceSynonymsInHighlight, newSP.replaceSynonymsInHighlight, "replaceSynonymsInHighlight should be updated (new parameter)" );
- t.equal( newSP.ignorePlurals, originalSP.ignorePlurals, "ignorePlurals should be the same as the original" );
+ t.equal(newSP.facets, params.facets, 'Facets should be updated (existing parameter)')
+ t.equal(newSP.attributesToHighlight, newSP.attributesToHighlight, 'attributesToHighlight should be updated (existing parameter)')
+ t.equal(newSP.replaceSynonymsInHighlight, newSP.replaceSynonymsInHighlight, 'replaceSynonymsInHighlight should be updated (new parameter)')
+ t.equal(newSP.ignorePlurals, originalSP.ignorePlurals, 'ignorePlurals should be the same as the original')
- t.end();
-} );
+ t.end()
+})
-test( "setQueryParameters should not add unknown properties", function( t ) {
- var partial = require( "lodash/function/partial" );
+test('setQueryParameters should not add unknown properties', function(t) {
+ var partial = require('lodash/function/partial')
- var originalSP = new SearchParameters( {
- facets : [ "a", "b" ],
- ignorePlurals : false,
- attributesToHighlight : ""
- } );
+ var originalSP = new SearchParameters({
+ facets: ['a', 'b'],
+ ignorePlurals: false,
+ attributesToHighlight: ''
+ })
var params = {
- unknow1 : [ "a", "c" ],
- facet : [ "city", "country" ]
- };
+ unknow1: ['a', 'c'],
+ facet: ['city', 'country']
+ }
- t.throws( partial( originalSP.setQueryParameters, params ),
- "The new searchParameters should be strictly equal" );
+ t.throws(partial(originalSP.setQueryParameters, params),
+ 'The new searchParameters should be strictly equal')
- t.end();
-} );
+ t.end()
+})
diff --git a/test/spec/SearchResults.getFacet.js b/test/spec/SearchResults.getFacet.js
index d3940a96af..804c9e24c2 100644
--- a/test/spec/SearchResults.getFacet.js
+++ b/test/spec/SearchResults.getFacet.js
@@ -1,19 +1,20 @@
-"use strict";
-var test = require( "tape" );
-var SearchResults = require( "../../src/SearchResults" );
+'use strict'
+var test = require('tape')
+var SearchResults = require('../../src/SearchResults')
-test( "getFacetByName should return a given facet be it disjunctive or conjunctive", function( t ) {
- var data = require( "./search.testdata" );
+test('getFacetByName should return a given facet be it disjunctive or conjunctive', function(t) {
+ var data = require('./search.testdata')
- var result = new SearchResults( data.searchParams, data.response );
+ var result = new SearchResults(data.searchParams, data.response)
- var cityFacet = result.getFacetByName( "city" );
- t.equal( cityFacet.name, "city", "name" );
- t.deepEqual( cityFacet.data, {
- "New York" : 1,
- "Paris" : 3,
- "San Francisco" : 1
- }, "values" );
+ var cityFacet = result.getFacetByName('city')
- t.end();
-} );
+ t.equal(cityFacet.name, 'city', 'name')
+ t.deepEqual(cityFacet.data, {
+ 'New York': 1,
+ Paris: 3,
+ 'San Francisco': 1
+ }, 'values')
+
+ t.end()
+})
diff --git a/test/spec/helper.clears.js b/test/spec/helper.clears.js
index 2dde73ea52..984817ed15 100644
--- a/test/spec/helper.clears.js
+++ b/test/spec/helper.clears.js
@@ -1,164 +1,163 @@
-"use strict";
-var test = require( "tape" ),
- algoliasearchHelper = require( "../../index" ),
- forEach = require( "lodash/collection/forEach" ),
- keys = require( "lodash/object/keys" ),
- isEmpty = require( "lodash/lang/isEmpty" ),
- isUndefined = require( "lodash/lang/isUndefined" );
+'use strict'
+var test = require('tape')
+var algoliasearchHelper = require('../../index')
+var forEach = require('lodash/collection/forEach')
+var keys = require('lodash/object/keys')
+var isEmpty = require('lodash/lang/isEmpty')
+var isUndefined = require('lodash/lang/isUndefined')
var fixture = function fixture() {
- var helper = algoliasearchHelper( undefined, "Index", {
- facets : ["facet1", "facet2", "both_facet"],
- disjunctiveFacets : ["disjunctiveFacet1", "disjunctiveFacet2", "both_facet"]
- } );
+ var helper = algoliasearchHelper(undefined, 'Index', {
+ facets: ['facet1', 'facet2', 'both_facet'],
+ disjunctiveFacets: ['disjunctiveFacet1', 'disjunctiveFacet2', 'both_facet']
+ })
- return helper.toggleRefine( "facet1", "0" )
- .toggleRefine( "facet2", "0" )
- .toggleRefine( "disjunctiveFacet1", "0" )
- .toggleRefine( "disjunctiveFacet2", "0" )
- .toggleExclude( "excluded1", "0" )
- .toggleExclude( "excluded2", "0" )
- .addNumericRefinement( "numeric1", ">=", "0" )
- .addNumericRefinement( "numeric1", "<", "10" )
- .addNumericRefinement( "numeric2", ">=", 0 )
- .addNumericRefinement( "numeric2", "<", 10 );
-};
+ return helper.toggleRefine('facet1', '0')
+ .toggleRefine('facet2', '0')
+ .toggleRefine('disjunctiveFacet1', '0')
+ .toggleRefine('disjunctiveFacet2', '0')
+ .toggleExclude('excluded1', '0')
+ .toggleExclude('excluded2', '0')
+ .addNumericRefinement('numeric1', '>=', '0')
+ .addNumericRefinement('numeric1', '<', '10')
+ .addNumericRefinement('numeric2', '>=', 0)
+ .addNumericRefinement('numeric2', '<', 10)
+}
-test( "Check that the state objects match how we test them", function( t ) {
- var helper = fixture();
+test('Check that the state objects match how we test them', function(t) {
+ var helper = fixture()
- t.deepEqual( helper.state.facetsRefinements, { "facet1" : [ "0" ], "facet2" : [ "0" ] } );
- t.deepEqual( helper.state.disjunctiveFacetsRefinements, { "disjunctiveFacet1" : [ "0" ], "disjunctiveFacet2" : [ "0" ] } );
- t.deepEqual( helper.state.facetsExcludes, { "excluded1" : [ "0" ], "excluded2" : [ "0" ] } );
- t.deepEqual( helper.state.numericRefinements, { "numeric1" : { ">=" : "0", "<" : "10" }, "numeric2" : { ">=" : 0, "<" : 10 } } );
+ t.deepEqual(helper.state.facetsRefinements, {facet1: ['0'], facet2: ['0']})
+ t.deepEqual(helper.state.disjunctiveFacetsRefinements, {disjunctiveFacet1: ['0'], disjunctiveFacet2: ['0']})
+ t.deepEqual(helper.state.facetsExcludes, {excluded1: ['0'], excluded2: ['0']})
+ t.deepEqual(helper.state.numericRefinements, {numeric1: {'>=': '0', '<': '10'}, numeric2: {'>=': 0, '<': 10}})
- t.end();
-} );
+ t.end()
+})
-test( "Clear with a name should work on every type and not remove others than targetted name", function( t ) {
- var helper = fixture();
+test('Clear with a name should work on every type and not remove others than targetted name', function(t) {
+ var helper = fixture()
- helper.clearRefinements( "facet1" );
- t.deepEqual( helper.state.facetsRefinements, { "facet2" : [ "0" ] } );
+ helper.clearRefinements('facet1')
+ t.deepEqual(helper.state.facetsRefinements, {facet2: ['0']})
- helper.clearRefinements( "disjunctiveFacet1" );
- t.deepEqual( helper.state.disjunctiveFacetsRefinements, { "disjunctiveFacet2" : [ "0" ] } );
+ helper.clearRefinements('disjunctiveFacet1')
+ t.deepEqual(helper.state.disjunctiveFacetsRefinements, {disjunctiveFacet2: ['0']})
- helper.clearRefinements( "excluded1" );
- t.deepEqual( helper.state.facetsExcludes, { "excluded2" : [ "0" ] } );
+ helper.clearRefinements('excluded1')
+ t.deepEqual(helper.state.facetsExcludes, {excluded2: ['0']})
- helper.clearRefinements( "numeric1" );
- t.deepEqual( helper.state.numericRefinements, { "numeric2" : { ">=" : 0, "<" : 10 } } );
+ helper.clearRefinements('numeric1')
+ t.deepEqual(helper.state.numericRefinements, {numeric2: {'>=': 0, '<': 10}})
- t.end();
-} );
+ t.end()
+})
+test('Clearing the same field from multiple elements should remove it everywhere', function(t) {
+ var helper = fixture()
-test( "Clearing the same field from multiple elements should remove it everywhere", function( t ) {
- var helper = fixture();
+ helper.addNumericRefinement('facet1', '>=', '10').toggleExclude('facet1', 'value')
- helper.addNumericRefinement( "facet1", ">=", "10" ).toggleExclude( "facet1", "value" );
+ t.deepEqual(helper.state.facetsRefinements.facet1, ['0'])
+ t.deepEqual(helper.state.numericRefinements.facet1, {'>=': '10'})
+ t.deepEqual(helper.state.facetsExcludes.facet1, ['value'])
- t.deepEqual( helper.state.facetsRefinements.facet1, [ "0" ] );
- t.deepEqual( helper.state.numericRefinements.facet1, { ">=" : "10" } );
- t.deepEqual( helper.state.facetsExcludes.facet1, [ "value" ] );
+ helper.clearRefinements('facet1')
+ t.assert(isUndefined(helper.state.facetsRefinements.facet1))
+ t.assert(isUndefined(helper.state.numericRefinements.facet1))
+ t.assert(isUndefined(helper.state.facetsExcludes.facet1))
- helper.clearRefinements( "facet1" );
- t.assert( isUndefined( helper.state.facetsRefinements.facet1 ) );
- t.assert( isUndefined( helper.state.numericRefinements.facet1 ) );
- t.assert( isUndefined( helper.state.facetsExcludes.facet1 ) );
+ t.end()
+})
- t.end();
-} );
+test('Clear with a function: neutral predicate', function(t) {
+ var helper = fixture()
+ var state0 = helper.state
-test( "Clear with a function : neutral predicate", function( t ) {
- var helper = fixture();
- var state0 = helper.state;
+ helper.clearRefinements(function() {
+ return false
+ })
- helper.clearRefinements( function() {
- return false;
- } );
+ t.deepEqual(helper.state.numericRefinements, state0.numericRefinements, 'Neutral op: numeric ref should be equal')
+ t.deepEqual(helper.state.facetsRefinements, state0.facetsRefinements, 'Neutral op: conj ref should be equal')
+ t.deepEqual(helper.state.facetsExcludes, state0.facetsExcludes, 'Neutral op: exclude ref should be equal')
+ t.deepEqual(helper.state.disjunctiveFacetsRefinements, state0.disjunctiveFacetsRefinements, 'Neutral op: disj ref should be equal')
- t.deepEqual( helper.state.numericRefinements, state0.numericRefinements, "Neutral op : numeric ref should be equal" );
- t.deepEqual( helper.state.facetsRefinements, state0.facetsRefinements, "Neutral op : conj ref should be equal" );
- t.deepEqual( helper.state.facetsExcludes, state0.facetsExcludes, "Neutral op : exclude ref should be equal" );
- t.deepEqual( helper.state.disjunctiveFacetsRefinements, state0.disjunctiveFacetsRefinements, "Neutral op : disj ref should be equal" );
+ t.end()
+})
- t.end();
-} );
+test('Clear with a function: remove all predicate', function(t) {
+ var helper = fixture()
-test( "Clear with a function : remove all predicate", function( t ) {
- var helper = fixture();
+ helper.clearRefinements(function() {
+ return true
+ })
- helper.clearRefinements( function() {
- return true;
- } );
+ t.assert(isEmpty(helper.state.numericRefinements), 'remove all numericRefinements')
+ t.assert(isEmpty(helper.state.facetsRefinements), 'remove all facetsRefinements')
+ t.assert(isEmpty(helper.state.facetsExcludes), 'remove all facetsExcludes')
+ t.assert(isEmpty(helper.state.disjunctiveFacetsRefinements), 'remove all disjunctiveFacetsRefinements')
- t.assert( isEmpty( helper.state.numericRefinements ), "remove all numericRefinements" );
- t.assert( isEmpty( helper.state.facetsRefinements ), "remove all facetsRefinements" );
- t.assert( isEmpty( helper.state.facetsExcludes ), "remove all facetsExcludes" );
- t.assert( isEmpty( helper.state.disjunctiveFacetsRefinements ), "remove all disjunctiveFacetsRefinements" );
+ t.end()
+})
- t.end();
-} );
-
-test( "Clear with a function : filtering", function( t ) {
- var helper = fixture();
+test('Clear with a function: filtering', function(t) {
+ var helper = fixture()
var checkType = {
- numeric : false,
- disjunctiveFacet : false,
- conjunctiveFacet : false,
- exclude : false
- };
-
- helper.clearRefinements( function( value, key, type ) {
- checkType[ type ] = true;
-
- return key.indexOf( "1" ) !== -1;
- } );
-
- t.equal( keys( checkType ).length, 4, "There should be only 4 refinements" );
- forEach( checkType, function( typeTest, type ) { t.ok( typeTest, "clear should go through : " + type ); } );
-
- t.deepEqual( helper.state.facetsRefinements, { "facet2" : [ "0" ] } );
- t.deepEqual( helper.state.disjunctiveFacetsRefinements, { "disjunctiveFacet2" : [ "0" ] } );
- t.deepEqual( helper.state.facetsExcludes, { "excluded2" : [ "0" ] } );
- t.deepEqual( helper.state.numericRefinements, { "numeric2" : { ">=" : 0, "<" : 10 } } );
-
- t.end();
-} );
-
-test( "Clearing twice the same attribute should be not problem", function( t ) {
- var helper = fixture();
-
- t.deepEqual( helper.state.facetsRefinements.facet1, [ "0" ] );
- helper.clearRefinements( "facet1" );
- t.assert( isUndefined( helper.state.facetsRefinements.facet1 ) );
- t.doesNotThrow( function() {
- helper.clearRefinements( "facet1" );
- } );
-
- t.deepEqual( helper.state.disjunctiveFacetsRefinements.disjunctiveFacet1, [ "0" ] );
- helper.clearRefinements( "disjunctiveFacet1" );
- t.assert( isUndefined( helper.state.disjunctiveFacetsRefinements.disjunctiveFacet1 ) );
- t.doesNotThrow( function() {
- helper.clearRefinements( "disjunctiveFacet1" );
- } );
-
- t.deepEqual( helper.state.facetsExcludes.excluded1, [ "0" ] );
- helper.clearRefinements( "excluded1" );
- t.assert( isUndefined( helper.state.facetsExcludes.excluded1 ) );
- t.doesNotThrow( function() {
- helper.clearRefinements( "excluded1" );
- } );
-
- t.deepEqual( helper.state.numericRefinements.numeric1, { ">=" : "0", "<" : "10" } );
- helper.clearRefinements( "numeric1" );
- t.assert( isUndefined( helper.state.numericRefinements.numeric1 ) );
- t.doesNotThrow( function() {
- helper.clearRefinements( "numeric1" );
- } );
-
- t.end();
-} );
+ numeric: false,
+ disjunctiveFacet: false,
+ conjunctiveFacet: false,
+ exclude: false
+ }
+
+ helper.clearRefinements(function(value, key, type) {
+ checkType[type] = true
+
+ return key.indexOf('1') !== -1
+ })
+
+ t.equal(keys(checkType).length, 4, 'There should be only 4 refinements')
+ forEach(checkType, function(typeTest, type) { t.ok(typeTest, 'clear should go through: ' + type) })
+
+ t.deepEqual(helper.state.facetsRefinements, {facet2: ['0']})
+ t.deepEqual(helper.state.disjunctiveFacetsRefinements, {disjunctiveFacet2: ['0']})
+ t.deepEqual(helper.state.facetsExcludes, {excluded2: ['0']})
+ t.deepEqual(helper.state.numericRefinements, {numeric2: {'>=': 0, '<': 10}})
+
+ t.end()
+})
+
+test('Clearing twice the same attribute should be not problem', function(t) {
+ var helper = fixture()
+
+ t.deepEqual(helper.state.facetsRefinements.facet1, ['0'])
+ helper.clearRefinements('facet1')
+ t.assert(isUndefined(helper.state.facetsRefinements.facet1))
+ t.doesNotThrow(function() {
+ helper.clearRefinements('facet1')
+ })
+
+ t.deepEqual(helper.state.disjunctiveFacetsRefinements.disjunctiveFacet1, ['0'])
+ helper.clearRefinements('disjunctiveFacet1')
+ t.assert(isUndefined(helper.state.disjunctiveFacetsRefinements.disjunctiveFacet1))
+ t.doesNotThrow(function() {
+ helper.clearRefinements('disjunctiveFacet1')
+ })
+
+ t.deepEqual(helper.state.facetsExcludes.excluded1, ['0'])
+ helper.clearRefinements('excluded1')
+ t.assert(isUndefined(helper.state.facetsExcludes.excluded1))
+ t.doesNotThrow(function() {
+ helper.clearRefinements('excluded1')
+ })
+
+ t.deepEqual(helper.state.numericRefinements.numeric1, {'>=': '0', '<': '10'})
+ helper.clearRefinements('numeric1')
+ t.assert(isUndefined(helper.state.numericRefinements.numeric1))
+ t.doesNotThrow(function() {
+ helper.clearRefinements('numeric1')
+ })
+
+ t.end()
+})
diff --git a/test/spec/helper.distinct.js b/test/spec/helper.distinct.js
index 0a51481bb9..7dd796caa8 100644
--- a/test/spec/helper.distinct.js
+++ b/test/spec/helper.distinct.js
@@ -1,140 +1,146 @@
-"use strict";
-var test = require( "tape" );
-var forEach = require( "lodash/collection/forEach" );
-
-var algoliasearchHelper = require( "../../index.js" );
-
-test( "Distinct not set", function( t ) {
- var helper = algoliasearchHelper( null, null, {} );
- var state0 = helper.state;
-
- var disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, false, "[disjunctive] distinct should be false" );
-
- var facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, false, "[hits] distinct should be false" );
-
- helper.setState( state0 );
- helper.setQuery( "not empty" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, undefined, "[disjunctive][query not empty] distinct should be undefined" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, undefined, "[hits][query not empty] distinct should be undefined" );
- forEach( helper._getQueries(), function( q ) {
- t.notOk( q.hasOwnProperty( "distinct" ), "[hits][query not empty] no distinct should be in the queries by default" );
- } );
-
- helper.setState( state0 );
- helper.addDisjunctiveRefine( "facet", "value" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, undefined, "[disjunctive][disjunctive refinement] distinct should be undefined" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, undefined, "[hits][disjunctive refinement] distinct should be undefined" );
- forEach( helper._getQueries(), function( q ) {
- t.notOk( q.hasOwnProperty( "distinct" ), "[hits][disjunctive refinement] no distinct should be in the queries by default" );
- } );
-
- helper.setState( state0 );
- helper.addRefine( "facet", "value" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, undefined, "[disjunctive][conjunctive refinement] distinct should be undefined" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, undefined, "[hits][conjunctive refinement] distinct should be undefined" );
- forEach( helper._getQueries(), function( q ) {
- t.notOk( q.hasOwnProperty( "distinct" ), "[disjunctive][conjunctive refinement] no distinct should be in the queries by default" );
- } );
-
- helper.setState( state0 );
- helper.addNumericRefinement( "attribute", ">", "0" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, undefined, "[disjunctive][numeric refinement] distinct should be undefined" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, undefined, "[hits][numeric refinement] distinct should be undefined" );
- forEach( helper._getQueries(), function( q ) {
- t.notOk( q.hasOwnProperty( "distinct" ), "no distinct should be in the queries by default" );
- } );
-
- t.end();
-} );
-
-test( "Distinct set to true", function( t ) {
- var helper = algoliasearchHelper( null, null, {} ).setQueryParameter( "distinct", true );
- var state0 = helper.state;
-
- var disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, false, "[disjunctive] distinct should be false" );
-
- var facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, false, "[hits] distinct should be false" );
-
- helper.setState( state0 );
- helper.setQuery( "not empty" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, true, "[disjunctive][query not empty] distinct should be true" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, true, "[hits][query not empty] distinct should be true" );
-
- helper.setState( state0 );
- helper.addDisjunctiveRefine( "facet", "value" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, true, "[disjunctive][disjunctive refinement] distinct should be true" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, true, "[hits][disjunctive refinement] distinct should be true" );
-
- helper.setState( state0 );
- helper.addRefine( "facet", "value" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, true, "[disjunctive][conjunctive refinement] distinct should be true" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, true, "[hits][conjunctive refinement] distinct should be true" );
-
- helper.setState( state0 );
- helper.addNumericRefinement( "attribute", ">", "0" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, true, "[disjunctive][numeric refinement] distinct should be true" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, true, "[hits][numeric refinement] distinct should be true" );
-
- t.end();
-} );
-
-test( "Distinct to false", function( t ) {
- var helper = algoliasearchHelper( null, null, {} ).setQueryParameter( "distinct", false );
- var state0 = helper.state;
-
- var disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, false, "[disjunctive] distinct should be false" );
-
- var facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, false, "[hits] distinct should be false" );
-
- helper.setState( state0 );
- helper.setQuery( "not empty" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, false, "[disjunctive][query not empty] distinct should be false" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, false, "[hits][query not empty] distinct should be false" );
-
- helper.setState( state0 );
- helper.addDisjunctiveRefine( "facet", "value" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, false, "[disjunctive][disjunctive refinement] distinct should be false" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, false, "[hits][disjunctive refinement] distinct should be false" );
-
- helper.setState( state0 );
- helper.addRefine( "facet", "value" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, false, "[disjunctive][conjunctive refinement] distinct should be false" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, false, "[hits][conjunctive refinement] distinct should be false" );
-
- helper.setState( state0 );
- helper.addNumericRefinement( "attribute", ">", "0" );
- disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams();
- t.equal( disjunctiveFacetSearchParam.distinct, false, "[disjunctive][numeric refinement] distinct should be false" );
- facetSearchParam = helper._getHitsSearchParams();
- t.equal( facetSearchParam.distinct, false, "[hits][numeric refinement] distinct should be false" );
-
- t.end();
-} );
+'use strict'
+var test = require('tape')
+var forEach = require('lodash/collection/forEach')
+
+var algoliasearchHelper = require('../../index.js')
+
+test('Distinct not set', function(t) {
+ var helper = algoliasearchHelper(null, null, {})
+ var state0 = helper.state
+
+ var disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+
+ t.equal(disjunctiveFacetSearchParam.distinct, false, '[disjunctive] distinct should be false')
+
+ var facetSearchParam = helper._getHitsSearchParams()
+
+ t.equal(facetSearchParam.distinct, false, '[hits] distinct should be false')
+
+ helper.setState(state0)
+ helper.setQuery('not empty')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, undefined, '[disjunctive][query not empty] distinct should be undefined')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, undefined, '[hits][query not empty] distinct should be undefined')
+ forEach(helper._getQueries(), function(q) {
+ t.notOk(q.hasOwnProperty('distinct'), '[hits][query not empty] no distinct should be in the queries by default')
+ })
+
+ helper.setState(state0)
+ helper.addDisjunctiveRefine('facet', 'value')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, undefined, '[disjunctive][disjunctive refinement] distinct should be undefined')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, undefined, '[hits][disjunctive refinement] distinct should be undefined')
+ forEach(helper._getQueries(), function(q) {
+ t.notOk(q.hasOwnProperty('distinct'), '[hits][disjunctive refinement] no distinct should be in the queries by default')
+ })
+
+ helper.setState(state0)
+ helper.addRefine('facet', 'value')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, undefined, '[disjunctive][conjunctive refinement] distinct should be undefined')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, undefined, '[hits][conjunctive refinement] distinct should be undefined')
+ forEach(helper._getQueries(), function(q) {
+ t.notOk(q.hasOwnProperty('distinct'), '[disjunctive][conjunctive refinement] no distinct should be in the queries by default')
+ })
+
+ helper.setState(state0)
+ helper.addNumericRefinement('attribute', '>', '0')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, undefined, '[disjunctive][numeric refinement] distinct should be undefined')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, undefined, '[hits][numeric refinement] distinct should be undefined')
+ forEach(helper._getQueries(), function(q) {
+ t.notOk(q.hasOwnProperty('distinct'), 'no distinct should be in the queries by default')
+ })
+
+ t.end()
+})
+
+test('Distinct set to true', function(t) {
+ var helper = algoliasearchHelper(null, null, {}).setQueryParameter('distinct', true)
+ var state0 = helper.state
+
+ var disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+
+ t.equal(disjunctiveFacetSearchParam.distinct, false, '[disjunctive] distinct should be false')
+
+ var facetSearchParam = helper._getHitsSearchParams()
+
+ t.equal(facetSearchParam.distinct, false, '[hits] distinct should be false')
+
+ helper.setState(state0)
+ helper.setQuery('not empty')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, true, '[disjunctive][query not empty] distinct should be true')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, true, '[hits][query not empty] distinct should be true')
+
+ helper.setState(state0)
+ helper.addDisjunctiveRefine('facet', 'value')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, true, '[disjunctive][disjunctive refinement] distinct should be true')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, true, '[hits][disjunctive refinement] distinct should be true')
+
+ helper.setState(state0)
+ helper.addRefine('facet', 'value')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, true, '[disjunctive][conjunctive refinement] distinct should be true')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, true, '[hits][conjunctive refinement] distinct should be true')
+
+ helper.setState(state0)
+ helper.addNumericRefinement('attribute', '>', '0')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, true, '[disjunctive][numeric refinement] distinct should be true')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, true, '[hits][numeric refinement] distinct should be true')
+
+ t.end()
+})
+
+test('Distinct to false', function(t) {
+ var helper = algoliasearchHelper(null, null, {}).setQueryParameter('distinct', false)
+ var state0 = helper.state
+
+ var disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+
+ t.equal(disjunctiveFacetSearchParam.distinct, false, '[disjunctive] distinct should be false')
+
+ var facetSearchParam = helper._getHitsSearchParams()
+
+ t.equal(facetSearchParam.distinct, false, '[hits] distinct should be false')
+
+ helper.setState(state0)
+ helper.setQuery('not empty')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, false, '[disjunctive][query not empty] distinct should be false')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, false, '[hits][query not empty] distinct should be false')
+
+ helper.setState(state0)
+ helper.addDisjunctiveRefine('facet', 'value')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, false, '[disjunctive][disjunctive refinement] distinct should be false')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, false, '[hits][disjunctive refinement] distinct should be false')
+
+ helper.setState(state0)
+ helper.addRefine('facet', 'value')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, false, '[disjunctive][conjunctive refinement] distinct should be false')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, false, '[hits][conjunctive refinement] distinct should be false')
+
+ helper.setState(state0)
+ helper.addNumericRefinement('attribute', '>', '0')
+ disjunctiveFacetSearchParam = helper._getDisjunctiveFacetSearchParams()
+ t.equal(disjunctiveFacetSearchParam.distinct, false, '[disjunctive][numeric refinement] distinct should be false')
+ facetSearchParam = helper._getHitsSearchParams()
+ t.equal(facetSearchParam.distinct, false, '[hits][numeric refinement] distinct should be false')
+
+ t.end()
+})
diff --git a/test/spec/helper.events.js b/test/spec/helper.events.js
index 36ff026205..6c0d44d1e8 100644
--- a/test/spec/helper.events.js
+++ b/test/spec/helper.events.js
@@ -1,56 +1,58 @@
-"use strict";
-
-var test = require( "tape" );
-var sinon = require( "sinon" );
-var algoliaSearchHelper = require( "../../index" );
-
-test( "Change events should be emitted as soon as the state change, but search should be triggered (refactored)", function( t ) {
- var helper = algoliaSearchHelper( undefined, "Index", {
- disjunctiveFacets : ["city"],
- facets : ["tower"]
- } );
-
- var count = 0;
- helper.on( "change", function() {
- count++;
- } );
- var stubbedSearch = sinon.stub( helper, "_search" );
-
- helper.setQuery( "" );
- t.equal( count, 1, "search" );
- t.equal( stubbedSearch.callCount, 0, "search" );
-
- helper.clearRefinements();
- t.equal( count, 2, "clearRefinements" );
- t.equal( stubbedSearch.callCount, 0, "clearRefinements" );
-
- helper.addDisjunctiveRefine( "city", "Paris" );
- t.equal( count, 3, "addDisjunctiveRefine" );
- t.equal( stubbedSearch.callCount, 0, "addDisjunctiveRefine" );
-
- helper.removeDisjunctiveRefine( "city", "Paris" );
- t.equal( count, 4, "removeDisjunctiveRefine" );
- t.equal( stubbedSearch.callCount, 0, "removeDisjunctiveRefine" );
-
- helper.addExclude( "tower", "Empire State Building" );
- t.equal( count, 5, "addExclude" );
- t.equal( stubbedSearch.callCount, 0, "addExclude" );
-
- helper.removeExclude( "tower", "Empire State Building" );
- t.equal( count, 6, "removeExclude" );
- t.equal( stubbedSearch.callCount, 0, "removeExclude" );
-
- helper.addRefine( "tower", "Empire State Building" );
- t.equal( count, 7, "addRefine" );
- t.equal( stubbedSearch.callCount, 0, "addRefine" );
-
- helper.removeRefine( "tower", "Empire State Building" );
- t.equal( count, 8, "removeRefine" );
- t.equal( stubbedSearch.callCount, 0, "removeRefine" );
-
- helper.search();
- t.equal( count, 8, "final search doesn't call the change" );
- t.equal( stubbedSearch.callCount, 1, "final search triggers the search" );
-
- t.end();
-} );
+'use strict'
+
+var test = require('tape')
+var sinon = require('sinon')
+var algoliaSearchHelper = require('../../index')
+
+test('Change events should be emitted as soon as the state change, but search should be triggered (refactored)', function(t) {
+ var helper = algoliaSearchHelper(undefined, 'Index', {
+ disjunctiveFacets: ['city'],
+ facets: ['tower']
+ })
+
+ var count = 0
+
+ helper.on('change', function() {
+ count++
+ })
+
+ var stubbedSearch = sinon.stub(helper, '_search')
+
+ helper.setQuery('')
+ t.equal(count, 1, 'search')
+ t.equal(stubbedSearch.callCount, 0, 'search')
+
+ helper.clearRefinements()
+ t.equal(count, 2, 'clearRefinements')
+ t.equal(stubbedSearch.callCount, 0, 'clearRefinements')
+
+ helper.addDisjunctiveRefine('city', 'Paris')
+ t.equal(count, 3, 'addDisjunctiveRefine')
+ t.equal(stubbedSearch.callCount, 0, 'addDisjunctiveRefine')
+
+ helper.removeDisjunctiveRefine('city', 'Paris')
+ t.equal(count, 4, 'removeDisjunctiveRefine')
+ t.equal(stubbedSearch.callCount, 0, 'removeDisjunctiveRefine')
+
+ helper.addExclude('tower', 'Empire State Building')
+ t.equal(count, 5, 'addExclude')
+ t.equal(stubbedSearch.callCount, 0, 'addExclude')
+
+ helper.removeExclude('tower', 'Empire State Building')
+ t.equal(count, 6, 'removeExclude')
+ t.equal(stubbedSearch.callCount, 0, 'removeExclude')
+
+ helper.addRefine('tower', 'Empire State Building')
+ t.equal(count, 7, 'addRefine')
+ t.equal(stubbedSearch.callCount, 0, 'addRefine')
+
+ helper.removeRefine('tower', 'Empire State Building')
+ t.equal(count, 8, 'removeRefine')
+ t.equal(stubbedSearch.callCount, 0, 'removeRefine')
+
+ helper.search()
+ t.equal(count, 8, "final search doesn't call the change")
+ t.equal(stubbedSearch.callCount, 1, 'final search triggers the search')
+
+ t.end()
+})
diff --git a/test/spec/helper.excludes.js b/test/spec/helper.excludes.js
index 7ded31718a..41535b1f9f 100644
--- a/test/spec/helper.excludes.js
+++ b/test/spec/helper.excludes.js
@@ -1,54 +1,59 @@
-"use strict";
+'use strict'
-var test = require( "tape" );
-var algoliasearchHelper = require( "../../index" );
+var test = require('tape')
+var algoliasearchHelper = require('../../index')
-test( "addExclude should add an exclusion", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
- helper._search = function() {};
- var facetName = "facet";
- var facetValueToExclude = "brand";
+test('addExclude should add an exclusion', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
- t.notOk( helper.state.facetsExcludes[ facetName ], "initialy empty" );
- helper.addExclude( facetName, facetValueToExclude );
- t.ok( helper.state.facetsExcludes[ facetName ], "not empty" );
- t.ok( helper.state.facetsExcludes[ facetName ][ 0 ] === facetValueToExclude, "with the correct value" );
+ helper._search = function() {}
- t.end();
-} );
+ var facetName = 'facet'
+ var facetValueToExclude = 'brand'
-test( "removeExclude should remove an exclusion", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
- helper._search = function() {};
- var facetName = "facet";
- var facetValueToExclude = "brand";
+ t.notOk(helper.state.facetsExcludes[facetName], 'initialy empty')
+ helper.addExclude(facetName, facetValueToExclude)
+ t.ok(helper.state.facetsExcludes[facetName], 'not empty')
+ t.ok(helper.state.facetsExcludes[facetName][0] === facetValueToExclude, 'with the correct value')
- helper.addExclude( facetName, facetValueToExclude );
- t.ok( helper.state.facetsExcludes[ facetName ].length === 1, "not empty at first" );
- helper.removeExclude( facetName, facetValueToExclude );
- t.ok( !helper.state.facetsExcludes[ facetName ], "then empty" );
+ t.end()
+})
+
+test('removeExclude should remove an exclusion', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+
+ helper._search = function() {}
+
+ var facetName = 'facet'
+ var facetValueToExclude = 'brand'
+
+ helper.addExclude(facetName, facetValueToExclude)
+ t.ok(helper.state.facetsExcludes[facetName].length === 1, 'not empty at first')
+ helper.removeExclude(facetName, facetValueToExclude)
+ t.ok(!helper.state.facetsExcludes[facetName], 'then empty')
try {
- helper.removeExclude( facetName, facetValueToExclude );
- }
- catch ( e ) {
- t.fail( "Removing unset exclusions should be ok..." );
+ helper.removeExclude(facetName, facetValueToExclude)
+ } catch (e) {
+ t.fail('Removing unset exclusions should be ok...')
}
- t.end();
-} );
+ t.end()
+})
+
+test('isExcluded should report exclusion correctly', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+
+ helper._search = function() {}
-test( "isExcluded should report exclusion correctly", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
- helper._search = function() {};
- var facetName = "facet";
- var facetValueToExclude = "brand";
+ var facetName = 'facet'
+ var facetValueToExclude = 'brand'
- t.notOk( helper.isExcluded( facetName, facetValueToExclude ), "value not exclude at first" );
- helper.addExclude( facetName, facetValueToExclude );
- t.ok( helper.isExcluded( facetName, facetValueToExclude ), "value is excluded" );
- helper.removeExclude( facetName, facetValueToExclude );
- t.notOk( helper.isExcluded( facetName, facetValueToExclude ), "value is not excluded anymore" );
+ t.notOk(helper.isExcluded(facetName, facetValueToExclude), 'value not exclude at first')
+ helper.addExclude(facetName, facetValueToExclude)
+ t.ok(helper.isExcluded(facetName, facetValueToExclude), 'value is excluded')
+ helper.removeExclude(facetName, facetValueToExclude)
+ t.notOk(helper.isExcluded(facetName, facetValueToExclude), 'value is not excluded anymore')
- t.end();
-} );
+ t.end()
+})
diff --git a/test/spec/helper.facetFilters.js b/test/spec/helper.facetFilters.js
index edaa3e1fed..e68fb7b6a5 100644
--- a/test/spec/helper.facetFilters.js
+++ b/test/spec/helper.facetFilters.js
@@ -1,37 +1,37 @@
-//Make sure we do facet filters correctly before sending them to algolia
+// Make sure we do facet filters correctly before sending them to algolia
-"use strict";
+'use strict'
-var test = require( "tape" );
-var algoliasearchHelper = require( "../../index" );
+var test = require('tape')
+var algoliasearchHelper = require('../../index')
-test( "The filters should contain the different filters for a single conjunctive facet with multiple refinements",
- function( t ) {
- var facetName = "myFacet";
- var helper = algoliasearchHelper( "", "", {
- facets : [ facetName ]
- } );
+test('The filters should contain the different filters for a single conjunctive facet with multiple refinements',
+ function(t) {
+ var facetName = 'myFacet'
+ var helper = algoliasearchHelper('', '', {
+ facets: [facetName]
+ })
- helper.addRefine( facetName, "value1" );
- t.deepEqual( helper._getFacetFilters(),
- [ facetName + ":value1" ],
- "One value : one filter" );
- helper.addRefine( facetName, "value2" );
- t.deepEqual( helper._getFacetFilters(),
- [ facetName + ":value1", facetName + ":value2" ],
- "Two values : two filters" );
- helper.toggleRefine( facetName, "value3" );
- t.deepEqual( helper._getFacetFilters(),
- [ facetName + ":value1", facetName + ":value2", facetName + ":value3" ],
- "Three values : three filters" );
- helper.removeRefine( facetName, "value3" );
- t.deepEqual( helper._getFacetFilters(),
- [ facetName + ":value1", facetName + ":value2" ],
- "Three values : three filters" );
- helper.addRefine( facetName, "value1" );
- t.deepEqual( helper._getFacetFilters(),
- [ facetName + ":value1", facetName + ":value2"],
- "Add multiple times the same parameter : only two parameters" );
+ helper.addRefine(facetName, 'value1')
+ t.deepEqual(helper._getFacetFilters(),
+ [facetName + ':value1'],
+ 'One value: one filter')
+ helper.addRefine(facetName, 'value2')
+ t.deepEqual(helper._getFacetFilters(),
+ [facetName + ':value1', facetName + ':value2'],
+ 'Two values: two filters')
+ helper.toggleRefine(facetName, 'value3')
+ t.deepEqual(helper._getFacetFilters(),
+ [facetName + ':value1', facetName + ':value2', facetName + ':value3'],
+ 'Three values: three filters')
+ helper.removeRefine(facetName, 'value3')
+ t.deepEqual(helper._getFacetFilters(),
+ [facetName + ':value1', facetName + ':value2'],
+ 'Three values: three filters')
+ helper.addRefine(facetName, 'value1')
+ t.deepEqual(helper._getFacetFilters(),
+ [facetName + ':value1', facetName + ':value2'],
+ 'Add multiple times the same parameter: only two parameters')
- t.end();
-} );
+ t.end()
+ })
diff --git a/test/spec/helper.getQueryParameter.js b/test/spec/helper.getQueryParameter.js
index f556aac358..437d6feb0c 100644
--- a/test/spec/helper.getQueryParameter.js
+++ b/test/spec/helper.getQueryParameter.js
@@ -1,21 +1,21 @@
-"use strict";
-var test = require( "tape" );
-var algoliaSearchHelper = require( "../../index.js" );
+'use strict'
+var test = require('tape')
+var algoliaSearchHelper = require('../../index.js')
-test( "getQueryParameter", function( t ) {
- var partial = require( "lodash/function/partial" );
+test('getQueryParameter', function(t) {
+ var partial = require('lodash/function/partial')
- var helper = algoliaSearchHelper( null, null, {
- facets : [ "facet1" ],
- minWordSizefor1Typo : 8,
- ignorePlurals : true
- } );
+ var helper = algoliaSearchHelper(null, null, {
+ facets: ['facet1'],
+ minWordSizefor1Typo: 8,
+ ignorePlurals: true
+ })
- t.deepEqual( helper.getQueryParameter( "facets" ), [ "facet1" ] );
- t.equal( helper.getQueryParameter( "minWordSizefor1Typo" ), 8 );
- t.equal( helper.getQueryParameter( "ignorePlurals" ), true );
+ t.deepEqual(helper.getQueryParameter('facets'), ['facet1'])
+ t.equal(helper.getQueryParameter('minWordSizefor1Typo'), 8)
+ t.equal(helper.getQueryParameter('ignorePlurals'), true)
- t.throws( partial( helper.getQueryParameter, "unknown" ) );
+ t.throws(partial(helper.getQueryParameter, 'unknown'))
- t.end();
-} );
+ t.end()
+})
diff --git a/test/spec/helper.numericFilters.js b/test/spec/helper.numericFilters.js
index b932316538..cfe7663c23 100644
--- a/test/spec/helper.numericFilters.js
+++ b/test/spec/helper.numericFilters.js
@@ -1,64 +1,70 @@
-"use strict";
-var test = require( "tape" );
-var algoliaSearch = require( "algoliasearch" );
-var algoliasearchHelper = require( "../../index" );
-
-test( "Numeric filters : numeric filters from constructor", function( t ) {
- var client = algoliaSearch( "dsf", "dsfdf" );
- client.search = function( queries ) {
- var ps = queries[0].params;
- t.equals( ps.numericFilters[ 0 ], "attribute1>3" );
- t.equals( ps.numericFilters[ 1 ], "attribute1<=100" );
- t.equals( ps.numericFilters[ 2 ], "attribute2=42" );
- t.end();
- };
-
- var helper = algoliasearchHelper( client, "index", {
- numericRefinements : {
- "attribute1" : {
- ">" : 3,
- "<=" : 100
+'use strict'
+var test = require('tape')
+var algoliaSearch = require('algoliasearch')
+var algoliasearchHelper = require('../../index')
+
+test('Numeric filters: numeric filters from constructor', function(t) {
+ var client = algoliaSearch('dsf', 'dsfdf')
+
+ client.search = function(queries) {
+ var ps = queries[0].params
+
+ t.equals(ps.numericFilters[0], 'attribute1>3')
+ t.equals(ps.numericFilters[1], 'attribute1<=100')
+ t.equals(ps.numericFilters[2], 'attribute2=42')
+ t.end()
+ }
+
+ var helper = algoliasearchHelper(client, 'index', {
+ numericRefinements: {
+ attribute1: {
+ '>': 3,
+ '<=': 100
},
- "attribute2" : {
- "=" : 42
+ attribute2: {
+ '=': 42
}
}
- } );
- helper.search();
-} );
-
-test( "Numeric filters : numeric filters from setters", function( t ) {
- var client = algoliaSearch( "dsf", "dsfdf" );
- client.search = function( queries ) {
- var ps = queries[0].params;
- t.equals( ps.numericFilters[ 0 ], "badassAttribute>9000" );
- t.equals( ps.numericFilters[ 1 ], "attribute2!=7" );
- t.end();
- };
-
- var helper = algoliasearchHelper( client, "index" );
- helper.addNumericRefinement( "badassAttribute", ">", 9000, true );
- helper.addNumericRefinement( "attribute2", "!=", "7", true );
-
- helper.search();
-} );
-
-test( "Should be able to remove a value if it equals 0", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
-
- helper.addNumericRefinement( "attribute", ">", 0 );
- t.equal( helper.state.numericRefinements.attribute[ ">" ], 0, "should be set to 0 initially" );
- helper.removeNumericRefinement( "attribute", ">", 0 );
- t.equal( helper.state.numericRefinements.attribute, undefined, "should set to undefined" );
- t.end();
-} );
-
-test( "Should be able to get if an attribute has numeric filter with hasRefinements", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
-
- t.notOk( helper.hasRefinements( "attribute" ), "not refined initially" );
- helper.addNumericRefinement( "attribute", "=", 42 );
- t.ok( helper.hasRefinements( "attribute" ), "should be refined" );
-
- t.end();
-} );
+ })
+
+ helper.search()
+})
+
+test('Numeric filters: numeric filters from setters', function(t) {
+ var client = algoliaSearch('dsf', 'dsfdf')
+
+ client.search = function(queries) {
+ var ps = queries[0].params
+
+ t.equals(ps.numericFilters[0], 'badassAttribute>9000')
+ t.equals(ps.numericFilters[1], 'attribute2!=7')
+ t.end()
+ }
+
+ var helper = algoliasearchHelper(client, 'index')
+
+ helper.addNumericRefinement('badassAttribute', '>', 9000, true)
+ helper.addNumericRefinement('attribute2', '!=', '7', true)
+
+ helper.search()
+})
+
+test('Should be able to remove a value if it equals 0', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+
+ helper.addNumericRefinement('attribute', '>', 0)
+ t.equal(helper.state.numericRefinements.attribute['>'], 0, 'should be set to 0 initially')
+ helper.removeNumericRefinement('attribute', '>', 0)
+ t.equal(helper.state.numericRefinements.attribute, undefined, 'should set to undefined')
+ t.end()
+})
+
+test('Should be able to get if an attribute has numeric filter with hasRefinements', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+
+ t.notOk(helper.hasRefinements('attribute'), 'not refined initially')
+ helper.addNumericRefinement('attribute', '=', 42)
+ t.ok(helper.hasRefinements('attribute'), 'should be refined')
+
+ t.end()
+})
diff --git a/test/spec/helper.pages.js b/test/spec/helper.pages.js
index a076c60d32..c51bd19f54 100644
--- a/test/spec/helper.pages.js
+++ b/test/spec/helper.pages.js
@@ -1,72 +1,72 @@
-"use strict";
-var test = require( "tape" );
-var algoliasearchHelper = require( "../../index" );
-
-test( "setChange should change the current page", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
-
- t.ok( helper.getCurrentPage() === 0, "First page should be 0" );
- helper.setCurrentPage( 3 );
- t.ok( helper.getCurrentPage() === 3, "If page was changed to 3, getCurrentPage should return 3" );
- t.end();
-} );
-
-test( "nextPage should increment the page by one", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
-
- t.ok( helper.getCurrentPage() === 0, "First page should be 0" );
- helper.nextPage();
- helper.nextPage();
- helper.nextPage();
- t.ok( helper.getCurrentPage() === 3, "If page was increment 3 times, getCurrentPage should return 3" );
- t.end();
-} );
-
-test( "previousPage should decrement the current page by one", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
-
- t.ok( helper.getCurrentPage() === 0, "First page should be 0" );
- helper.setCurrentPage( 3 );
- t.ok( helper.getCurrentPage() === 3, "If page was changed to 3, getCurrentPage should return 3" );
- helper.previousPage();
- t.ok( helper.getCurrentPage() === 2, "must be 2 now" );
- t.end();
-} );
-
-test( "pages should be reset if the mutation might change the number of pages", function( t ) {
- var bindAll = require( "lodash/function/bindAll" );
- var partial = require( "lodash/function/partial" );
-
- var helper = algoliasearchHelper( "", "", {
- facets : [ "facet1", "f2" ],
- disjunctiveFacets : [ "f1" ]
- } );
-
- bindAll(helper);
-
- var testMutation = function( tester, text, testFn ) {
- helper.setCurrentPage( 10 );
- t.equal( helper.getCurrentPage(), 10, "set the current page to 10" + text );
- testFn();
- t.equal( helper.getCurrentPage(), 0, "page resetted" + text );
- };
-
- testMutation( t, " clearRefinements", helper.clearRefinements );
- testMutation( t, " setQuery", partial( helper.setQuery, "query" ) );
- testMutation( t, " addNumericRefinement", partial( helper.addNumericRefinement, "facet", ">", "2" ) );
- testMutation( t, " removeNumericRefinement", partial( helper.removeNumericRefinement, "facet", ">" ) );
-
- testMutation( t, " addExclude", partial( helper.addExclude, "facet1", "val2" ) );
- testMutation( t, " removeExclude", partial( helper.removeExclude, "facet1", "val2" ) );
-
- testMutation( t, " addRefine", partial( helper.addRefine, "f1", "val" ) );
- testMutation( t, " removeRefine", partial( helper.removeRefine, "f1", "val" ) );
-
- testMutation( t, " addDisjunctiveRefine", partial( helper.addDisjunctiveRefine, "f2", "val" ) );
- testMutation( t, " removeDisjunctiveRefine", partial( helper.removeDisjunctiveRefine, "f2", "val" ) );
-
- testMutation( t, " toggleRefine", partial( helper.toggleRefine, "f1", "v1" ) );
- testMutation( t, " toggleExclude", partial( helper.toggleExclude, "facet1", "55" ) );
-
- t.end();
-} );
+'use strict'
+var test = require('tape')
+var algoliasearchHelper = require('../../index')
+
+test('setChange should change the current page', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+
+ t.ok(helper.getCurrentPage() === 0, 'First page should be 0')
+ helper.setCurrentPage(3)
+ t.ok(helper.getCurrentPage() === 3, 'If page was changed to 3, getCurrentPage should return 3')
+ t.end()
+})
+
+test('nextPage should increment the page by one', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+
+ t.ok(helper.getCurrentPage() === 0, 'First page should be 0')
+ helper.nextPage()
+ helper.nextPage()
+ helper.nextPage()
+ t.ok(helper.getCurrentPage() === 3, 'If page was increment 3 times, getCurrentPage should return 3')
+ t.end()
+})
+
+test('previousPage should decrement the current page by one', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+
+ t.ok(helper.getCurrentPage() === 0, 'First page should be 0')
+ helper.setCurrentPage(3)
+ t.ok(helper.getCurrentPage() === 3, 'If page was changed to 3, getCurrentPage should return 3')
+ helper.previousPage()
+ t.ok(helper.getCurrentPage() === 2, 'must be 2 now')
+ t.end()
+})
+
+test('pages should be reset if the mutation might change the number of pages', function(t) {
+ var bindAll = require('lodash/function/bindAll')
+ var partial = require('lodash/function/partial')
+
+ var helper = algoliasearchHelper('', '', {
+ facets: ['facet1', 'f2'],
+ disjunctiveFacets: ['f1']
+ })
+
+ bindAll(helper)
+
+ var testMutation = function(tester, text, testFn) {
+ helper.setCurrentPage(10)
+ t.equal(helper.getCurrentPage(), 10, 'set the current page to 10' + text)
+ testFn()
+ t.equal(helper.getCurrentPage(), 0, 'page resetted' + text)
+ }
+
+ testMutation(t, ' clearRefinements', helper.clearRefinements)
+ testMutation(t, ' setQuery', partial(helper.setQuery, 'query'))
+ testMutation(t, ' addNumericRefinement', partial(helper.addNumericRefinement, 'facet', '>', '2'))
+ testMutation(t, ' removeNumericRefinement', partial(helper.removeNumericRefinement, 'facet', '>'))
+
+ testMutation(t, ' addExclude', partial(helper.addExclude, 'facet1', 'val2'))
+ testMutation(t, ' removeExclude', partial(helper.removeExclude, 'facet1', 'val2'))
+
+ testMutation(t, ' addRefine', partial(helper.addRefine, 'f1', 'val'))
+ testMutation(t, ' removeRefine', partial(helper.removeRefine, 'f1', 'val'))
+
+ testMutation(t, ' addDisjunctiveRefine', partial(helper.addDisjunctiveRefine, 'f2', 'val'))
+ testMutation(t, ' removeDisjunctiveRefine', partial(helper.removeDisjunctiveRefine, 'f2', 'val'))
+
+ testMutation(t, ' toggleRefine', partial(helper.toggleRefine, 'f1', 'v1'))
+ testMutation(t, ' toggleExclude', partial(helper.toggleExclude, 'facet1', '55'))
+
+ t.end()
+})
diff --git a/test/spec/helper.queryID.js b/test/spec/helper.queryID.js
index bb5ab0d0dd..f813cca8b2 100644
--- a/test/spec/helper.queryID.js
+++ b/test/spec/helper.queryID.js
@@ -1,43 +1,46 @@
-"use strict";
-var test = require( "tape" );
-var algoliasearchHelper = require( "../../index" );
+'use strict'
+var test = require('tape')
+var algoliasearchHelper = require('../../index')
-test( "the queryid should keep increasing when new requests arrives", function( t ) {
- var initialQueryID;
+test('the queryid should keep increasing when new requests arrives', function(t) {
+ var initialQueryID
var client = {
- search : function() {
- initialQueryID++;
+ search: function() {
+ initialQueryID++
}
- };
- var helper = algoliasearchHelper( client, null, {} );
- initialQueryID = helper._queryId;
+ }
+ var helper = algoliasearchHelper(client, null, {})
- helper.search().search().search().search().search();
+ initialQueryID = helper._queryId
- t.equal( helper._queryId, initialQueryID, "the _queryID should have increased of the number of calls" );
+ helper.search().search().search().search().search()
- t.end();
-} );
+ t.equal(helper._queryId, initialQueryID, 'the _queryID should have increased of the number of calls')
-test( "the response handler should check that the query is not outdated", function( t ) {
- var testData = require( "./search.testdata" );
- var shouldTriggerResult = true;
- var callCount = 0;
+ t.end()
+})
- var helper = algoliasearchHelper( null, null, {} );
- helper.on( "result", function() {
- callCount++;
- if( !shouldTriggerResult ) {
- t.fail( "The id was outdated" );
+test('the response handler should check that the query is not outdated', function(t) {
+ var testData = require('./search.testdata')
+ var shouldTriggerResult = true
+ var callCount = 0
+
+ var helper = algoliasearchHelper(null, null, {})
+
+ helper.on('result', function() {
+ callCount++
+
+ if (!shouldTriggerResult) {
+ t.fail('The id was outdated')
}
- } );
+ })
- helper._handleResponse( helper.state, helper._lastQueryIdReceived + 1, null, testData.response );
- helper._handleResponse( helper.state, helper._lastQueryIdReceived + 10, null, testData.response );
- t.equal( callCount, 2, "the callback should have been called twice" );
- shouldTriggerResult = false;
- helper._handleResponse( helper.state, helper._lastQueryIdReceived - 1, null, testData.response );
- t.equal( callCount, 2, "and shouldn't have been called if outdated" );
+ helper._handleResponse(helper.state, helper._lastQueryIdReceived + 1, null, testData.response)
+ helper._handleResponse(helper.state, helper._lastQueryIdReceived + 10, null, testData.response)
+ t.equal(callCount, 2, 'the callback should have been called twice')
+ shouldTriggerResult = false
+ helper._handleResponse(helper.state, helper._lastQueryIdReceived - 1, null, testData.response)
+ t.equal(callCount, 2, "and shouldn't have been called if outdated")
- t.end();
-} );
+ t.end()
+})
diff --git a/test/spec/helper.setQueryParameter.js b/test/spec/helper.setQueryParameter.js
index d8937d3c65..42fdb4a07b 100644
--- a/test/spec/helper.setQueryParameter.js
+++ b/test/spec/helper.setQueryParameter.js
@@ -1,39 +1,39 @@
-"use strict";
-var test = require( "tape" );
-var algoliasearchHelper = require( "../../index" );
-
-test( "setChange should change the current state", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
- var changed = false;
-
- helper.on( "change", function() {
- changed = true;
- } );
-
- t.equal( helper.getCurrentPage(), 0, "Initially page is 0" );
- t.notOk( changed, "No changes called yet" );
- helper.setQueryParameter( "page", 22 );
- t.equal( helper.getCurrentPage(), 22, "After setting the page is 22" );
- t.ok( changed, "Change event should have been triggered" );
-
- t.end();
-} );
-
-test( "setChange should not change the current state : no real modification", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
- var changed = false;
- var initialState = helper.state;
-
- helper.on( "change", function() {
- changed = true;
- } );
-
- t.equal( helper.getCurrentPage(), 0, "Initially page is 0" );
- t.notOk( changed, "No changes called yet" );
- helper.setQueryParameter( "page", 0 );
- t.equal( helper.getCurrentPage(), 0, "After setting the page is 0" );
- t.notOk( changed, "Change event should not have been triggered" );
- t.equal( helper.state, initialState, "The state instance should remain the same" );
-
- t.end();
-} );
+'use strict'
+var test = require('tape')
+var algoliasearchHelper = require('../../index')
+
+test('setChange should change the current state', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+ var changed = false
+
+ helper.on('change', function() {
+ changed = true
+ })
+
+ t.equal(helper.getCurrentPage(), 0, 'Initially page is 0')
+ t.notOk(changed, 'No changes called yet')
+ helper.setQueryParameter('page', 22)
+ t.equal(helper.getCurrentPage(), 22, 'After setting the page is 22')
+ t.ok(changed, 'Change event should have been triggered')
+
+ t.end()
+})
+
+test('setChange should not change the current state: no real modification', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+ var changed = false
+ var initialState = helper.state
+
+ helper.on('change', function() {
+ changed = true
+ })
+
+ t.equal(helper.getCurrentPage(), 0, 'Initially page is 0')
+ t.notOk(changed, 'No changes called yet')
+ helper.setQueryParameter('page', 0)
+ t.equal(helper.getCurrentPage(), 0, 'After setting the page is 0')
+ t.notOk(changed, 'Change event should not have been triggered')
+ t.equal(helper.state, initialState, 'The state instance should remain the same')
+
+ t.end()
+})
diff --git a/test/spec/helper.tags.js b/test/spec/helper.tags.js
index 6954e91a9a..7455eefa45 100644
--- a/test/spec/helper.tags.js
+++ b/test/spec/helper.tags.js
@@ -1,53 +1,54 @@
-"use strict";
-var test = require( "tape" );
-var algoliasearchHelper = require( "../../index" );
+'use strict'
+var test = require('tape')
+var algoliasearchHelper = require('../../index')
-test( "Tag filters : operations on tags list", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
- helper.addTag( "tag" ).addTag( "tag2" );
- t.deepEqual( helper.getTags(), [ "tag", "tag2" ], "should be [ tag, tag2 ]" );
- helper.removeTag( "tag" );
- t.deepEqual( helper.getTags(), [ "tag2" ], "should be [ tag2 ]" );
- helper.toggleTag( "tag3" ).toggleTag( "tag2" ).toggleTag( "tag4" );
- t.deepEqual( helper.getTags(), [ "tag3", "tag4" ], "should be [ tag3, tag4 ]" );
- t.end();
-} );
+test('Tag filters: operations on tags list', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
-test( "Tags filters : advanced query", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
+ helper.addTag('tag').addTag('tag2')
+ t.deepEqual(helper.getTags(), ['tag', 'tag2'], 'should be [ tag, tag2 ]')
+ helper.removeTag('tag')
+ t.deepEqual(helper.getTags(), ['tag2'], 'should be [ tag2 ]')
+ helper.toggleTag('tag3').toggleTag('tag2').toggleTag('tag4')
+ t.deepEqual(helper.getTags(), ['tag3', 'tag4'], 'should be [ tag3, tag4 ]')
+ t.end()
+})
- var complexQuery = "( sea, city ), romantic, -mountain";
- helper.setQueryParameter( "tagFilters", complexQuery );
+test('Tags filters: advanced query', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
- t.deepEqual( helper._getTagFilters(), complexQuery, "The complex query should be equal to the user input" );
+ var complexQuery = '(sea, city), romantic, -mountain'
- t.end();
-} );
+ helper.setQueryParameter('tagFilters', complexQuery)
-test( "Tags filters : switching between advanced and simple API should be forbidden without clearing the refinements first", function( t ) {
- var helper = algoliasearchHelper( null, null, null );
+ t.deepEqual(helper._getTagFilters(), complexQuery, 'The complex query should be equal to the user input')
- helper.addTag( "tag" ).addTag( "tag2" );
- t.deepEqual( helper._getTagFilters(), "tag,tag2", "should be [ tag, tag2 ]" );
+ t.end()
+})
+
+test('Tags filters: switching between advanced and simple API should be forbidden without clearing the refinements first', function(t) {
+ var helper = algoliasearchHelper(null, null, null)
+
+ helper.addTag('tag').addTag('tag2')
+ t.deepEqual(helper._getTagFilters(), 'tag,tag2', 'should be [ tag, tag2 ]')
+
+ var complexQuery = '(sea, city), romantic, -mountain'
- var complexQuery = "( sea, city ), romantic, -mountain";
try {
- helper.setQueryParameter( "tagFilters", complexQuery );
- t.fail( "Can't switch directly from the advanced API to the managed API" );
- }
- catch( e0 ) {
- helper.clearTags().setQueryParameter( "tagFilters", complexQuery );
- t.deepEqual( helper._getTagFilters(), complexQuery, "The complex should override the simple mode if cleared before" );
+ helper.setQueryParameter('tagFilters', complexQuery)
+ t.fail("Can't switch directly from the advanced API to the managed API")
+ } catch (e0) {
+ helper.clearTags().setQueryParameter('tagFilters', complexQuery)
+ t.deepEqual(helper._getTagFilters(), complexQuery, 'The complex should override the simple mode if cleared before')
try {
- helper.addTag( "tag" ).addTag( "tag2" );
- t.fail( "Can't switch directly from the managed API to the advanced API" );
- }
- catch( e1 ) {
- helper.setQueryParameter( "tagFilters", undefined ).addTag( "tag" ).addTag( "tag2" );
- t.deepEqual( helper._getTagFilters(), "tag,tag2", "should be [ tag, tag2 ]" );
+ helper.addTag('tag').addTag('tag2')
+ t.fail("Can't switch directly from the managed API to the advanced API")
+ } catch (e1) {
+ helper.setQueryParameter('tagFilters', undefined).addTag('tag').addTag('tag2')
+ t.deepEqual(helper._getTagFilters(), 'tag,tag2', 'should be [ tag, tag2 ]')
- t.end();
+ t.end()
}
}
-} );
+})
diff --git a/test/spec/refinements.js b/test/spec/refinements.js
index fc80949ca0..798b1c5cee 100644
--- a/test/spec/refinements.js
+++ b/test/spec/refinements.js
@@ -1,252 +1,254 @@
-"use strict";
-var test = require( "tape" );
-var _ = require( "lodash" );
-var algoliasearchHelper = require( "../../index" );
-
-
-test( "Adding refinments should add an entry to the refinments attribute", function( t ) {
- var helper = algoliasearchHelper( {}, "index", {} );
-
- var facetName = "facet1";
- var facetValue = "42";
-
- t.ok( _.isEmpty( helper.state.facetsRefinements ), "should be empty at first" );
- helper.addRefine( facetName, facetValue );
- t.ok( _.size( helper.state.facetsRefinements ) === 1, "when adding a refinment, should have one" );
- t.deepEqual( helper.state.facetsRefinements.facet1, [ facetValue ] );
- helper.addRefine( facetName, facetValue );
- t.ok( _.size( helper.state.facetsRefinements ) === 1, "when adding the same, should still be one" );
- helper.removeRefine( facetName, facetValue );
- t.ok( _.size( helper.state.facetsRefinements ) === 0, "Then empty " );
- t.end();
-} );
-
-test( "Adding several refinements for a single attribute should be handled", function( t ) {
- var facetName = "facet";
-
- var helper = algoliasearchHelper( null, null, {
- facets : [ facetName ]
- } );
-
- t.ok( _.isEmpty( helper.state.facetsRefinements ), "empty" );
- helper.addRefine( facetName, "value1" );
- t.ok( _.size( helper.state.facetsRefinements[ facetName ] ) === 1, "Adding one refinement, should have one" );
- helper.addRefine( facetName, "value2" );
- t.ok( _.size( helper.state.facetsRefinements[ facetName ] ) === 2, "Adding another refinement, should have two" );
- helper.addRefine( facetName, "value1" );
- t.ok( _.size( helper.state.facetsRefinements[ facetName ] ) === 2, "Adding same refinement as the first, should have two" );
-
- t.end();
-} );
-
-test( "Toggling several refinements for a single attribute should be handled", function( t ) {
- var facetName = "facet";
-
- var helper = algoliasearchHelper( null, null, {
- facets : [ facetName ]
- } );
-
- t.ok( _.isEmpty( helper.state.facetsRefinements ), "empty" );
- helper.toggleRefine( facetName, "value1" );
- t.ok( _.size( helper.state.facetsRefinements[ facetName ] ) === 1, "Adding one refinement, should have one" );
- helper.toggleRefine( facetName, "value2" );
- t.ok( _.size( helper.state.facetsRefinements[ facetName ] ) === 2, "Adding another refinement, should have two" );
- helper.toggleRefine( facetName, "value1" );
- t.ok( _.size( helper.state.facetsRefinements[ facetName ] ) === 1, "Adding same refinement as the first, should have two" );
- t.deepEqual( helper.state.facetsRefinements[ facetName ], [ "value2" ], "should contain value2" );
-
- t.end();
-} );
-
-test( "Removing several refinements for a single attribute should be handled", function( t ) {
- var facetName = "facet";
-
- var helper = algoliasearchHelper( null, null, {
- facets : [ facetName ]
- } );
-
- t.ok( _.isEmpty( helper.state.facetsRefinements ), "empty" );
- helper.addRefine( facetName, "value1" );
- helper.addRefine( facetName, "value2" );
- helper.addRefine( facetName, "value3" );
- t.ok( _.size( helper.state.facetsRefinements[ facetName ] ) === 3, "Adding another refinement, should have two" );
- helper.removeRefine( facetName, "value2" );
- t.ok( _.size( helper.state.facetsRefinements[ facetName ] ) === 2, "Adding same refinement as the first, should have two" );
- t.deepEqual( helper.state.facetsRefinements[ facetName ], [ "value1", "value3" ], "should contain value1 and value3" );
-
- t.end();
-} );
-
-test( "isDisjunctiveRefined", function( t ) {
- var helper = algoliasearchHelper( null, null, {} );
-
- var facet = "MyFacet";
- var value = "MyValue";
-
- t.notOk( helper.isDisjunctiveRefined( facet, value ),
- "isDisjunctiveRefined should not return true for undefined refinement" );
- helper.addDisjunctiveRefine( facet, value );
- t.ok( helper.isDisjunctiveRefined( facet, value ),
- "isDisjunctiveRefined should not return false for defined refinement" );
- helper.removeDisjunctiveRefine( facet, value );
- t.notOk( helper.isDisjunctiveRefined( facet, value ),
- "isDisjunctiveRefined should not return true for removed refinement" );
- t.end();
-} );
-
-test( "IsRefined should return true if the ( facet, value ) is refined.", function( t ) {
- var helper = algoliasearchHelper( null, null, {
- facets : [ "facet1" ]
- } );
-
- helper.addRefine( "facet1", "boom" );
-
- t.ok( helper.isRefined( "facet1", "boom" ), "the facet + value is refined >> true" );
-
- t.notOk( helper.isRefined( "facet1", "booohh" ), "value not refined but is a facet" );
- t.notOk( helper.isRefined( "notAFacet", "maoooh" ), "not refined because it's not a facet" );
- t.notOk( helper.isRefined( null, null ), "not even valid values" );
-
- t.end();
-} );
-
-test( "isRefined(facet)/hasRefinements should return true if the facet is refined.", function( t ) {
- var helper = algoliasearchHelper( null, null, {
- facets : [ "facet1" ]
- } );
-
- t.notOk( helper.isRefined( "facet1" ), "the facet is not refined yet >> false" );
- t.notOk( helper.hasRefinements( "facet1" ), "the facet is not refined yet >> false" );
-
- helper.addRefine( "facet1", "boom" );
-
- t.ok( helper.isRefined( "facet1" ), "the facet is refined >> true" );
- t.ok( helper.hasRefinements( "facet1" ), "the facet is refined >> true" );
-
- t.notOk( helper.isRefined( "notAFacet" ), "not a facet" );
- t.notOk( helper.hasRefinements( "notAFacet" ), "not a facet" );
- t.notOk( helper.isRefined( null ), "not even valid values" );
- t.notOk( helper.hasRefinements( null ), "not even valid values" );
-
- t.end();
-} );
-
-test( "getRefinements should return all the refinements for a given facet", function( t ) {
- var helper = algoliasearchHelper( null, null, {
- facets : [ "facet1" ],
- disjunctiveFacets : [ "facet2", "sales" ]
- } );
-
- helper.addRefine( "facet1", "val1" )
- .addRefine( "facet1", "val2" )
- .addExclude( "facet1", "val-1" )
- .toggleRefine( "facet1", "val3" );
-
- helper.addDisjunctiveRefine( "facet2", "val4" )
- .addDisjunctiveRefine( "facet2", "val5" )
- .toggleRefine( "facet2", "val6" );
-
- helper.addNumericRefinement( "sales", ">", "3" )
- .addNumericRefinement( "sales", "<", "9" );
-
- t.deepEqual( helper.getRefinements( "facet1" ),
- [
- { value : "val1", type : "conjunctive" },
- { value : "val2", type : "conjunctive" },
- { value : "val3", type : "conjunctive" },
- { value : "val-1", type : "exclude" }
- ],
- "" );
-
- t.deepEqual( helper.getRefinements( "facet2" ),
- [
- { value : "val4", type : "disjunctive" },
- { value : "val5", type : "disjunctive" },
- { value : "val6", type : "disjunctive" }
- ],
- "" );
-
- t.deepEqual( helper.getRefinements( "sales" ),
- [
- { value : "3", operator : ">", type : "numeric" },
- { value : "9", operator : "<", type : "numeric" }
- ],
- "" );
-
- t.end();
-} );
-
-test( "getRefinements should return an empty array if the facet has no refinement", function( t ) {
- var helper = algoliasearchHelper( null, null, {
- facets : [ "facet1" ],
- disjunctiveFacets : [ "facet2" ]
- } );
-
- t.deepEqual( helper.getRefinements( "facet1" ), [], "" );
- t.deepEqual( helper.getRefinements( "facet2" ), [], "" );
-
- t.end();
-} );
-
-test( "[Conjunctive] Facets should be resilient to user attempt to use numbers", function( t ) {
- var helper = algoliasearchHelper( null, null, {
- facets : [ "facet1" ],
- disjunctiveFacets : [ "facet2" ]
- } );
-
- helper.addRefine( "facet1", 42 );
- t.ok( helper.isRefined( "facet1", 42 ), "[facet][number] should be refined" );
- t.ok( helper.isRefined( "facet1", "42" ), "[facet][string] should be refined" );
-
- var stateWithFacet1and42 = helper.state;
- helper.removeRefine( "facet1", "42" );
- t.notOk( helper.isRefined( "facet1", "42" ), "[facet][string] should not be refined" );
-
- helper.setState( stateWithFacet1and42 );
- helper.removeRefine( "facet1", 42 );
- t.notOk( helper.isRefined( "facet1", 42 ), "[facet][number] should not be refined" );
-
- t.end();
-} );
-
-test( "[Disjunctive] Facets should be resilient to user attempt to use numbers", function( t ) {
- var helper = algoliasearchHelper( null, null, {
- facets : [ "facet1" ],
- disjunctiveFacets : [ "facet2" ]
- } );
-
- helper.addExclude( "facet1", 42 );
- t.ok( helper.isExcluded( "facet1", 42 ), "[facet][number] should be refined" );
- t.ok( helper.isExcluded( "facet1", "42" ), "[facet][string] should be refined" );
-
- var stateWithFacet1Without42 = helper.state;
- helper.removeExclude( "facet1", "42" );
- t.notOk( helper.isExcluded( "facet1", "42" ), "[facet][string] should not be refined" );
-
- helper.setState( stateWithFacet1Without42 );
- helper.removeExclude( "facet1", 42 );
- t.notOk( helper.isExcluded( "facet1", 42 ), "[facet][number] should not be refined" );
-
- t.end();
-} );
-
-test( "[Disjunctive] Facets should be resilient to user attempt to use numbers", function( t ) {
- var helper = algoliasearchHelper( null, null, {
- facets : [ "facet1" ],
- disjunctiveFacets : [ "facet2" ]
- } );
-
- helper.addDisjunctiveRefine( "facet2", 42 );
- t.ok( helper.isDisjunctiveRefined( "facet2", 42 ), "[facet][number] should be refined" );
- t.ok( helper.isDisjunctiveRefined( "facet2", "42" ), "[facet][string] should be refined" );
-
- var stateWithFacet2and42 = helper.state;
- helper.removeDisjunctiveRefine( "facet2", "42" );
- t.notOk( helper.isDisjunctiveRefined( "facet2", "42" ), "[facet][string] should not be refined" );
- helper.setState( stateWithFacet2and42 );
-
- helper.removeDisjunctiveRefine( "facet2", 42 );
- t.notOk( helper.isDisjunctiveRefined( "facet2", 42 ), "[facet][number] should not be refined" );
-
- t.end();
-} );
+'use strict'
+var test = require('tape')
+var _ = require('lodash')
+var algoliasearchHelper = require('../../index')
+
+test('Adding refinments should add an entry to the refinments attribute', function(t) {
+ var helper = algoliasearchHelper({}, 'index', {})
+
+ var facetName = 'facet1'
+ var facetValue = '42'
+
+ t.ok(_.isEmpty(helper.state.facetsRefinements), 'should be empty at first')
+ helper.addRefine(facetName, facetValue)
+ t.ok(_.size(helper.state.facetsRefinements) === 1, 'when adding a refinment, should have one')
+ t.deepEqual(helper.state.facetsRefinements.facet1, [facetValue])
+ helper.addRefine(facetName, facetValue)
+ t.ok(_.size(helper.state.facetsRefinements) === 1, 'when adding the same, should still be one')
+ helper.removeRefine(facetName, facetValue)
+ t.ok(_.size(helper.state.facetsRefinements) === 0, 'Then empty ')
+ t.end()
+})
+
+test('Adding several refinements for a single attribute should be handled', function(t) {
+ var facetName = 'facet'
+
+ var helper = algoliasearchHelper(null, null, {
+ facets: [facetName]
+ })
+
+ t.ok(_.isEmpty(helper.state.facetsRefinements), 'empty')
+ helper.addRefine(facetName, 'value1')
+ t.ok(_.size(helper.state.facetsRefinements[facetName]) === 1, 'Adding one refinement, should have one')
+ helper.addRefine(facetName, 'value2')
+ t.ok(_.size(helper.state.facetsRefinements[facetName]) === 2, 'Adding another refinement, should have two')
+ helper.addRefine(facetName, 'value1')
+ t.ok(_.size(helper.state.facetsRefinements[facetName]) === 2, 'Adding same refinement as the first, should have two')
+
+ t.end()
+})
+
+test('Toggling several refinements for a single attribute should be handled', function(t) {
+ var facetName = 'facet'
+
+ var helper = algoliasearchHelper(null, null, {
+ facets: [facetName]
+ })
+
+ t.ok(_.isEmpty(helper.state.facetsRefinements), 'empty')
+ helper.toggleRefine(facetName, 'value1')
+ t.ok(_.size(helper.state.facetsRefinements[facetName]) === 1, 'Adding one refinement, should have one')
+ helper.toggleRefine(facetName, 'value2')
+ t.ok(_.size(helper.state.facetsRefinements[facetName]) === 2, 'Adding another refinement, should have two')
+ helper.toggleRefine(facetName, 'value1')
+ t.ok(_.size(helper.state.facetsRefinements[facetName]) === 1, 'Adding same refinement as the first, should have two')
+ t.deepEqual(helper.state.facetsRefinements[facetName], ['value2'], 'should contain value2')
+
+ t.end()
+})
+
+test('Removing several refinements for a single attribute should be handled', function(t) {
+ var facetName = 'facet'
+
+ var helper = algoliasearchHelper(null, null, {
+ facets: [facetName]
+ })
+
+ t.ok(_.isEmpty(helper.state.facetsRefinements), 'empty')
+ helper.addRefine(facetName, 'value1')
+ helper.addRefine(facetName, 'value2')
+ helper.addRefine(facetName, 'value3')
+ t.ok(_.size(helper.state.facetsRefinements[facetName]) === 3, 'Adding another refinement, should have two')
+ helper.removeRefine(facetName, 'value2')
+ t.ok(_.size(helper.state.facetsRefinements[facetName]) === 2, 'Adding same refinement as the first, should have two')
+ t.deepEqual(helper.state.facetsRefinements[facetName], ['value1', 'value3'], 'should contain value1 and value3')
+
+ t.end()
+})
+
+test('isDisjunctiveRefined', function(t) {
+ var helper = algoliasearchHelper(null, null, {})
+
+ var facet = 'MyFacet'
+ var value = 'MyValue'
+
+ t.notOk(helper.isDisjunctiveRefined(facet, value),
+ 'isDisjunctiveRefined should not return true for undefined refinement')
+ helper.addDisjunctiveRefine(facet, value)
+ t.ok(helper.isDisjunctiveRefined(facet, value),
+ 'isDisjunctiveRefined should not return false for defined refinement')
+ helper.removeDisjunctiveRefine(facet, value)
+ t.notOk(helper.isDisjunctiveRefined(facet, value),
+ 'isDisjunctiveRefined should not return true for removed refinement')
+ t.end()
+})
+
+test('IsRefined should return true if the (facet, value ) is refined.', function(t) {
+ var helper = algoliasearchHelper(null, null, {
+ facets: ['facet1']
+ })
+
+ helper.addRefine('facet1', 'boom')
+
+ t.ok(helper.isRefined('facet1', 'boom'), 'the facet + value is refined >> true')
+
+ t.notOk(helper.isRefined('facet1', 'booohh'), 'value not refined but is a facet')
+ t.notOk(helper.isRefined('notAFacet', 'maoooh'), "not refined because it's not a facet")
+ t.notOk(helper.isRefined(null, null), 'not even valid values')
+
+ t.end()
+})
+
+test('isRefined(facet)/hasRefinements should return true if the facet is refined.', function(t) {
+ var helper = algoliasearchHelper(null, null, {
+ facets: ['facet1']
+ })
+
+ t.notOk(helper.isRefined('facet1'), 'the facet is not refined yet >> false')
+ t.notOk(helper.hasRefinements('facet1'), 'the facet is not refined yet >> false')
+
+ helper.addRefine('facet1', 'boom')
+
+ t.ok(helper.isRefined('facet1'), 'the facet is refined >> true')
+ t.ok(helper.hasRefinements('facet1'), 'the facet is refined >> true')
+
+ t.notOk(helper.isRefined('notAFacet'), 'not a facet')
+ t.notOk(helper.hasRefinements('notAFacet'), 'not a facet')
+ t.notOk(helper.isRefined(null), 'not even valid values')
+ t.notOk(helper.hasRefinements(null), 'not even valid values')
+
+ t.end()
+})
+
+test('getRefinements should return all the refinements for a given facet', function(t) {
+ var helper = algoliasearchHelper(null, null, {
+ facets: ['facet1'],
+ disjunctiveFacets: ['facet2', 'sales']
+ })
+
+ helper.addRefine('facet1', 'val1')
+ .addRefine('facet1', 'val2')
+ .addExclude('facet1', 'val-1')
+ .toggleRefine('facet1', 'val3')
+
+ helper.addDisjunctiveRefine('facet2', 'val4')
+ .addDisjunctiveRefine('facet2', 'val5')
+ .toggleRefine('facet2', 'val6')
+
+ helper.addNumericRefinement('sales', '>', '3')
+ .addNumericRefinement('sales', '<', '9')
+
+ t.deepEqual(helper.getRefinements('facet1'),
+ [
+ {value: 'val1', type: 'conjunctive'},
+ {value: 'val2', type: 'conjunctive'},
+ {value: 'val3', type: 'conjunctive'},
+ {value: 'val-1', type: 'exclude'}
+ ],
+ '')
+
+ t.deepEqual(helper.getRefinements('facet2'),
+ [
+ {value: 'val4', type: 'disjunctive'},
+ {value: 'val5', type: 'disjunctive'},
+ {value: 'val6', type: 'disjunctive'}
+ ],
+ '')
+
+ t.deepEqual(helper.getRefinements('sales'),
+ [
+ {value: '3', operator: '>', type: 'numeric'},
+ {value: '9', operator: '<', type: 'numeric'}
+ ],
+ '')
+
+ t.end()
+})
+
+test('getRefinements should return an empty array if the facet has no refinement', function(t) {
+ var helper = algoliasearchHelper(null, null, {
+ facets: ['facet1'],
+ disjunctiveFacets: ['facet2']
+ })
+
+ t.deepEqual(helper.getRefinements('facet1'), [], '')
+ t.deepEqual(helper.getRefinements('facet2'), [], '')
+
+ t.end()
+})
+
+test('[Conjunctive] Facets should be resilient to user attempt to use numbers', function(t) {
+ var helper = algoliasearchHelper(null, null, {
+ facets: ['facet1'],
+ disjunctiveFacets: ['facet2']
+ })
+
+ helper.addRefine('facet1', 42)
+ t.ok(helper.isRefined('facet1', 42), '[facet][number] should be refined')
+ t.ok(helper.isRefined('facet1', '42'), '[facet][string] should be refined')
+
+ var stateWithFacet1and42 = helper.state
+
+ helper.removeRefine('facet1', '42')
+ t.notOk(helper.isRefined('facet1', '42'), '[facet][string] should not be refined')
+
+ helper.setState(stateWithFacet1and42)
+ helper.removeRefine('facet1', 42)
+ t.notOk(helper.isRefined('facet1', 42), '[facet][number] should not be refined')
+
+ t.end()
+})
+
+test('[Disjunctive] Facets should be resilient to user attempt to use numbers', function(t) {
+ var helper = algoliasearchHelper(null, null, {
+ facets: ['facet1'],
+ disjunctiveFacets: ['facet2']
+ })
+
+ helper.addExclude('facet1', 42)
+ t.ok(helper.isExcluded('facet1', 42), '[facet][number] should be refined')
+ t.ok(helper.isExcluded('facet1', '42'), '[facet][string] should be refined')
+
+ var stateWithFacet1Without42 = helper.state
+
+ helper.removeExclude('facet1', '42')
+ t.notOk(helper.isExcluded('facet1', '42'), '[facet][string] should not be refined')
+
+ helper.setState(stateWithFacet1Without42)
+ helper.removeExclude('facet1', 42)
+ t.notOk(helper.isExcluded('facet1', 42), '[facet][number] should not be refined')
+
+ t.end()
+})
+
+test('[Disjunctive] Facets should be resilient to user attempt to use numbers', function(t) {
+ var helper = algoliasearchHelper(null, null, {
+ facets: ['facet1'],
+ disjunctiveFacets: ['facet2']
+ })
+
+ helper.addDisjunctiveRefine('facet2', 42)
+ t.ok(helper.isDisjunctiveRefined('facet2', 42), '[facet][number] should be refined')
+ t.ok(helper.isDisjunctiveRefined('facet2', '42'), '[facet][string] should be refined')
+
+ var stateWithFacet2and42 = helper.state
+
+ helper.removeDisjunctiveRefine('facet2', '42')
+ t.notOk(helper.isDisjunctiveRefined('facet2', '42'), '[facet][string] should not be refined')
+ helper.setState(stateWithFacet2and42)
+
+ helper.removeDisjunctiveRefine('facet2', 42)
+ t.notOk(helper.isDisjunctiveRefined('facet2', 42), '[facet][number] should not be refined')
+
+ t.end()
+})
diff --git a/test/spec/search.js b/test/spec/search.js
index deafbaa2a2..4c66904a7c 100644
--- a/test/spec/search.js
+++ b/test/spec/search.js
@@ -1,56 +1,56 @@
-"use strict";
-var test = require( "tape" );
-var sinon = require( "sinon" );
-var algoliaSearch = require( "algoliasearch" );
+'use strict'
+var test = require('tape')
+var sinon = require('sinon')
+var algoliaSearch = require('algoliasearch')
-var algoliasearchHelper = require( "../../index" );
+var algoliasearchHelper = require('../../index')
-test( "Search should call the algolia client according to the number of refinements", function( t ) {
- var testData = require( "./search.testdata" );
+test('Search should call the algolia client according to the number of refinements', function(t) {
+ var testData = require('./search.testdata')
- var client = algoliaSearch( "dsf", "dsfdf" );
+ var client = algoliaSearch('dsf', 'dsfdf')
+ var mock = sinon.mock(client)
- var mock = sinon.mock( client );
- mock.expects( "search" ).once().yields( null, testData.response );
+ mock.expects('search').once().yields(null, testData.response)
- var helper = algoliasearchHelper( client, "test_hotels-node", {
- disjunctiveFacets : ["city"]
- } );
+ var helper = algoliasearchHelper(client, 'test_hotels-node', {
+ disjunctiveFacets: ['city']
+ })
- helper.addDisjunctiveRefine( "city", "Paris", true );
- helper.addDisjunctiveRefine( "city", "New York", true );
+ helper.addDisjunctiveRefine('city', 'Paris', true)
+ helper.addDisjunctiveRefine('city', 'New York', true)
- helper.on( "result", function( data ) {
- t.deepEqual( data, testData.responseHelper, "should be equal" );
- t.ok( mock.verify(), "Mock constraints should be verified!" );
- t.end();
- } );
+ helper.on('result', function(data) {
+ t.deepEqual(data, testData.responseHelper, 'should be equal')
+ t.ok(mock.verify(), 'Mock constraints should be verified!')
+ t.end()
+ })
- helper.search( "" );
-} );
+ helper.search('')
+})
-test( "no mutating methods should trigger a search", function( t ) {
- var helper = algoliasearchHelper( undefined, "Index", {
- disjunctiveFacets : ["city"],
- facets : ["tower"]
- } );
+test('no mutating methods should trigger a search', function(t) {
+ var helper = algoliasearchHelper(undefined, 'Index', {
+ disjunctiveFacets: ['city'],
+ facets: ['tower']
+ })
- var stubbedSearch = sinon.stub( helper, "_search" );
+ var stubbedSearch = sinon.stub(helper, '_search')
- helper.setQuery( "" );
- helper.clearRefinements();
- helper.addDisjunctiveRefine( "city", "Paris" );
- helper.removeDisjunctiveRefine( "city", "Paris" );
- helper.addExclude( "tower", "Empire State Building" );
- helper.removeExclude( "tower", "Empire State Building" );
- helper.addRefine( "tower", "Empire State Building" );
- helper.removeRefine( "tower", "Empire State Building" );
+ helper.setQuery('')
+ helper.clearRefinements()
+ helper.addDisjunctiveRefine('city', 'Paris')
+ helper.removeDisjunctiveRefine('city', 'Paris')
+ helper.addExclude('tower', 'Empire State Building')
+ helper.removeExclude('tower', 'Empire State Building')
+ helper.addRefine('tower', 'Empire State Building')
+ helper.removeRefine('tower', 'Empire State Building')
- t.equal( stubbedSearch.callCount, 0, "should not have triggered calls" );
+ t.equal(stubbedSearch.callCount, 0, 'should not have triggered calls')
- helper.search();
+ helper.search()
- t.equal( stubbedSearch.callCount, 1, "should have triggered a single search" );
+ t.equal(stubbedSearch.callCount, 1, 'should have triggered a single search')
- t.end();
-} );
+ t.end()
+})
diff --git a/test/spec/search.testdata.js b/test/spec/search.testdata.js
index 4b1b4b8ab1..6e5138ca5b 100644
--- a/test/spec/search.testdata.js
+++ b/test/spec/search.testdata.js
@@ -1,369 +1,369 @@
-"use strict";
-var SearchParameters = require( "../../src/SearchParameters" );
+'use strict'
+var SearchParameters = require('../../src/SearchParameters')
var response = {
- "results" : [
- {
- "page" : 0,
- "index" : "test_hotels-node",
- "hits" : [
- {
- "stars" : "****",
- "facilities" : [
- "spa"
- ],
- "city" : "New York",
- "objectID" : "366084010",
- "name" : "Hotel E",
- "_highlightResult" : {
- "name" : {
- "matchedWords" : [],
- "value" : "Hotel E",
- "matchLevel" : "none"
- },
- "stars" : {
- "matchLevel" : "none",
- "matchedWords" : [],
- "value" : "****"
- },
- "facilities" : [
- {
- "matchLevel" : "none",
- "value" : "spa",
- "matchedWords" : []
- }
- ],
- "city" : {
- "matchLevel" : "none",
- "value" : "New York",
- "matchedWords" : []
- }
+ 'results': [
+ {
+ 'page': 0,
+ 'index': 'test_hotels-node',
+ 'hits': [
+ {
+ 'stars': '****',
+ 'facilities': [
+ 'spa'
+ ],
+ 'city': 'New York',
+ 'objectID': '366084010',
+ 'name': 'Hotel E',
+ '_highlightResult': {
+ 'name': {
+ 'matchedWords': [],
+ 'value': 'Hotel E',
+ 'matchLevel': 'none'
+ },
+ 'stars': {
+ 'matchLevel': 'none',
+ 'matchedWords': [],
+ 'value': '****'
+ },
+ 'facilities': [
+ {
+ 'matchLevel': 'none',
+ 'value': 'spa',
+ 'matchedWords': []
}
+ ],
+ 'city': {
+ 'matchLevel': 'none',
+ 'value': 'New York',
+ 'matchedWords': []
+ }
+ }
+ },
+ {
+ '_highlightResult': {
+ 'stars': {
+ 'matchedWords': [],
+ 'value': '****',
+ 'matchLevel': 'none'
},
- {
- "_highlightResult" : {
- "stars" : {
- "matchedWords" : [],
- "value" : "****",
- "matchLevel" : "none"
- },
- "facilities" : [
- {
- "value" : "spa",
- "matchedWords" : [],
- "matchLevel" : "none"
- }
- ],
- "city" : {
- "matchedWords" : [],
- "value" : "Paris",
- "matchLevel" : "none"
- },
- "name" : {
- "value" : "Hotel D",
- "matchedWords" : [],
- "matchLevel" : "none"
- }
- },
- "name" : "Hotel D",
- "objectID" : "366084000",
- "facilities" : [
- "spa"
- ],
- "city" : "Paris",
- "stars" : "****"
+ 'facilities': [
+ {
+ 'value': 'spa',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
+ }
+ ],
+ 'city': {
+ 'matchedWords': [],
+ 'value': 'Paris',
+ 'matchLevel': 'none'
},
- {
- "_highlightResult" : {
- "stars" : {
- "matchLevel" : "none",
- "value" : "*",
- "matchedWords" : []
- },
- "city" : {
- "matchLevel" : "none",
- "value" : "Paris",
- "matchedWords" : []
- },
- "facilities" : [
- {
- "value" : "wifi",
- "matchedWords" : [],
- "matchLevel" : "none"
- }
- ],
- "name" : {
- "matchedWords" : [],
- "value" : "Hotel B",
- "matchLevel" : "none"
- }
- },
- "name" : "Hotel B",
- "objectID" : "366083980",
- "city" : "Paris",
- "facilities" : [
- "wifi"
- ],
- "stars" : "*"
+ 'name': {
+ 'value': 'Hotel D',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
+ }
+ },
+ 'name': 'Hotel D',
+ 'objectID': '366084000',
+ 'facilities': [
+ 'spa'
+ ],
+ 'city': 'Paris',
+ 'stars': '****'
+ },
+ {
+ '_highlightResult': {
+ 'stars': {
+ 'matchLevel': 'none',
+ 'value': '*',
+ 'matchedWords': []
},
- {
- "stars" : "*",
- "city" : "Paris",
- "facilities" : [
- "wifi",
- "bath",
- "spa"
- ],
- "objectID" : "366083970",
- "name" : "Hotel A",
- "_highlightResult" : {
- "name" : {
- "value" : "Hotel A",
- "matchedWords" : [],
- "matchLevel" : "none"
- },
- "stars" : {
- "matchLevel" : "none",
- "value" : "*",
- "matchedWords" : []
- },
- "facilities" : [
- {
- "matchLevel" : "none",
- "value" : "wifi",
- "matchedWords" : []
- },
- {
- "value" : "bath",
- "matchedWords" : [],
- "matchLevel" : "none"
- },
- {
- "matchLevel" : "none",
- "matchedWords" : [],
- "value" : "spa"
- }
- ],
- "city" : {
- "matchLevel" : "none",
- "matchedWords" : [],
- "value" : "Paris"
- }
+ 'city': {
+ 'matchLevel': 'none',
+ 'value': 'Paris',
+ 'matchedWords': []
+ },
+ 'facilities': [
+ {
+ 'value': 'wifi',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
}
+ ],
+ 'name': {
+ 'matchedWords': [],
+ 'value': 'Hotel B',
+ 'matchLevel': 'none'
}
- ],
- "params" : "query=&hitsPerPage=20&page=0&facets=%5B%5D&facetFilters=%5B%5B%22city%3AParis%22%2C%22city%3ANew%20York%22%5D%5D",
- "exhaustiveFacetsCount" : true,
- "nbHits" : 4,
- "query" : "",
- "processingTimeMS" : 2,
- "nbPages" : 1,
- "hitsPerPage" : 20
- },
- {
- "query" : "",
- "nbPages" : 5,
- "hitsPerPage" : 1,
- "processingTimeMS" : 3,
- "page" : 0,
- "index" : "test_hotels-node",
- "facets" : {
- "city" : {
- "New York" : 1,
- "Paris" : 3,
- "San Francisco" : 1
- }
+ },
+ 'name': 'Hotel B',
+ 'objectID': '366083980',
+ 'city': 'Paris',
+ 'facilities': [
+ 'wifi'
+ ],
+ 'stars': '*'
},
- "exhaustiveFacetsCount" : false,
- "nbHits" : 5,
- "hits" : [
- {
- "objectID" : "366084010"
+ {
+ 'stars': '*',
+ 'city': 'Paris',
+ 'facilities': [
+ 'wifi',
+ 'bath',
+ 'spa'
+ ],
+ 'objectID': '366083970',
+ 'name': 'Hotel A',
+ '_highlightResult': {
+ 'name': {
+ 'value': 'Hotel A',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
+ },
+ 'stars': {
+ 'matchLevel': 'none',
+ 'value': '*',
+ 'matchedWords': []
+ },
+ 'facilities': [
+ {
+ 'matchLevel': 'none',
+ 'value': 'wifi',
+ 'matchedWords': []
+ },
+ {
+ 'value': 'bath',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
+ },
+ {
+ 'matchLevel': 'none',
+ 'matchedWords': [],
+ 'value': 'spa'
+ }
+ ],
+ 'city': {
+ 'matchLevel': 'none',
+ 'matchedWords': [],
+ 'value': 'Paris'
}
- ],
- "params" : "query=&hitsPerPage=1&page=0&attributesToRetrieve=%5B%5D&attributesToHighlight=%5B%5D&attributesToSnippet=%5B%5D&facets=city&facetFilters=%5B%5D"
- }
- ]
-};
+ }
+ }
+ ],
+ 'params': 'query=&hitsPerPage=20&page=0&facets=%5B%5D&facetFilters=%5B%5B%22city%3AParis%22%2C%22city%3ANew%20York%22%5D%5D',
+ 'exhaustiveFacetsCount': true,
+ 'nbHits': 4,
+ 'query': '',
+ 'processingTimeMS': 2,
+ 'nbPages': 1,
+ 'hitsPerPage': 20
+ },
+ {
+ 'query': '',
+ 'nbPages': 5,
+ 'hitsPerPage': 1,
+ 'processingTimeMS': 3,
+ 'page': 0,
+ 'index': 'test_hotels-node',
+ 'facets': {
+ 'city': {
+ 'New York': 1,
+ 'Paris': 3,
+ 'San Francisco': 1
+ }
+ },
+ 'exhaustiveFacetsCount': false,
+ 'nbHits': 5,
+ 'hits': [
+ {
+ 'objectID': '366084010'
+ }
+ ],
+ 'params': 'query=&hitsPerPage=1&page=0&attributesToRetrieve=%5B%5D&attributesToHighlight=%5B%5D&attributesToSnippet=%5B%5D&facets=city&facetFilters=%5B%5D'
+ }
+ ]
+}
-var searchParams = new SearchParameters( {
- disjunctiveFacets : [ "city" ],
- disjunctiveFacetsRefinements : {
- city : [ "Paris", "New York" ]
+var searchParams = new SearchParameters({
+ disjunctiveFacets: ['city'],
+ disjunctiveFacetsRefinements: {
+ city: ['Paris', 'New York']
}
-} );
+})
var responseHelper = {
- "_state" : searchParams,
- "query" : "",
- "hits" : [
+ '_state': searchParams,
+ 'query': '',
+ 'hits': [
{
- "stars" : "****",
- "facilities" : [
- "spa"
+ 'stars': '****',
+ 'facilities': [
+ 'spa'
],
- "city" : "New York",
- "objectID" : "366084010",
- "name" : "Hotel E",
- "_highlightResult" : {
- "name" : {
- "matchedWords" : [],
- "value" : "Hotel E",
- "matchLevel" : "none"
+ 'city': 'New York',
+ 'objectID': '366084010',
+ 'name': 'Hotel E',
+ '_highlightResult': {
+ 'name': {
+ 'matchedWords': [],
+ 'value': 'Hotel E',
+ 'matchLevel': 'none'
},
- "stars" : {
- "matchLevel" : "none",
- "matchedWords" : [],
- "value" : "****"
+ 'stars': {
+ 'matchLevel': 'none',
+ 'matchedWords': [],
+ 'value': '****'
},
- "facilities" : [
+ 'facilities': [
{
- "matchLevel" : "none",
- "value" : "spa",
- "matchedWords" : []
+ 'matchLevel': 'none',
+ 'value': 'spa',
+ 'matchedWords': []
}
],
- "city" : {
- "matchLevel" : "none",
- "value" : "New York",
- "matchedWords" : []
+ 'city': {
+ 'matchLevel': 'none',
+ 'value': 'New York',
+ 'matchedWords': []
}
}
},
{
- "_highlightResult" : {
- "stars" : {
- "matchedWords" : [],
- "value" : "****",
- "matchLevel" : "none"
+ '_highlightResult': {
+ 'stars': {
+ 'matchedWords': [],
+ 'value': '****',
+ 'matchLevel': 'none'
},
- "facilities" : [
+ 'facilities': [
{
- "value" : "spa",
- "matchedWords" : [],
- "matchLevel" : "none"
+ 'value': 'spa',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
}
],
- "city" : {
- "matchedWords" : [],
- "value" : "Paris",
- "matchLevel" : "none"
+ 'city': {
+ 'matchedWords': [],
+ 'value': 'Paris',
+ 'matchLevel': 'none'
},
- "name" : {
- "value" : "Hotel D",
- "matchedWords" : [],
- "matchLevel" : "none"
+ 'name': {
+ 'value': 'Hotel D',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
}
},
- "name" : "Hotel D",
- "objectID" : "366084000",
- "facilities" : [
- "spa"
+ 'name': 'Hotel D',
+ 'objectID': '366084000',
+ 'facilities': [
+ 'spa'
],
- "city" : "Paris",
- "stars" : "****"
+ 'city': 'Paris',
+ 'stars': '****'
},
{
- "_highlightResult" : {
- "stars" : {
- "matchLevel" : "none",
- "value" : "*",
- "matchedWords" : []
+ '_highlightResult': {
+ 'stars': {
+ 'matchLevel': 'none',
+ 'value': '*',
+ 'matchedWords': []
},
- "city" : {
- "matchLevel" : "none",
- "value" : "Paris",
- "matchedWords" : []
+ 'city': {
+ 'matchLevel': 'none',
+ 'value': 'Paris',
+ 'matchedWords': []
},
- "facilities" : [
+ 'facilities': [
{
- "value" : "wifi",
- "matchedWords" : [],
- "matchLevel" : "none"
+ 'value': 'wifi',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
}
],
- "name" : {
- "matchedWords" : [],
- "value" : "Hotel B",
- "matchLevel" : "none"
+ 'name': {
+ 'matchedWords': [],
+ 'value': 'Hotel B',
+ 'matchLevel': 'none'
}
},
- "name" : "Hotel B",
- "objectID" : "366083980",
- "city" : "Paris",
- "facilities" : [
- "wifi"
+ 'name': 'Hotel B',
+ 'objectID': '366083980',
+ 'city': 'Paris',
+ 'facilities': [
+ 'wifi'
],
- "stars" : "*"
+ 'stars': '*'
},
{
- "stars" : "*",
- "city" : "Paris",
- "facilities" : [
- "wifi",
- "bath",
- "spa"
+ 'stars': '*',
+ 'city': 'Paris',
+ 'facilities': [
+ 'wifi',
+ 'bath',
+ 'spa'
],
- "objectID" : "366083970",
- "name" : "Hotel A",
- "_highlightResult" : {
- "name" : {
- "value" : "Hotel A",
- "matchedWords" : [],
- "matchLevel" : "none"
+ 'objectID': '366083970',
+ 'name': 'Hotel A',
+ '_highlightResult': {
+ 'name': {
+ 'value': 'Hotel A',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
},
- "stars" : {
- "matchLevel" : "none",
- "value" : "*",
- "matchedWords" : []
+ 'stars': {
+ 'matchLevel': 'none',
+ 'value': '*',
+ 'matchedWords': []
},
- "facilities" : [
+ 'facilities': [
{
- "matchLevel" : "none",
- "value" : "wifi",
- "matchedWords" : []
+ 'matchLevel': 'none',
+ 'value': 'wifi',
+ 'matchedWords': []
},
{
- "value" : "bath",
- "matchedWords" : [],
- "matchLevel" : "none"
+ 'value': 'bath',
+ 'matchedWords': [],
+ 'matchLevel': 'none'
},
{
- "matchLevel" : "none",
- "matchedWords" : [],
- "value" : "spa"
+ 'matchLevel': 'none',
+ 'matchedWords': [],
+ 'value': 'spa'
}
],
- "city" : {
- "matchLevel" : "none",
- "matchedWords" : [],
- "value" : "Paris"
+ 'city': {
+ 'matchLevel': 'none',
+ 'matchedWords': [],
+ 'value': 'Paris'
}
}
}
],
- "index" : "test_hotels-node",
- "hitsPerPage" : 20,
- "nbHits" : 4,
- "nbPages" : 1,
- "page" : 0,
- "processingTimeMS" : 5,
- "disjunctiveFacets" : [
+ 'index': 'test_hotels-node',
+ 'hitsPerPage': 20,
+ 'nbHits': 4,
+ 'nbPages': 1,
+ 'page': 0,
+ 'processingTimeMS': 5,
+ 'disjunctiveFacets': [
{
- "name" : "city",
- "data" : {
- "New York" : 1,
- "Paris" : 3,
- "San Francisco" : 1
+ 'name': 'city',
+ 'data': {
+ 'New York': 1,
+ 'Paris': 3,
+ 'San Francisco': 1
},
- "exhaustive" : false
+ 'exhaustive': false
}
],
- "facets" : []
-};
+ 'facets': []
+}
module.exports = {
- response : response,
- searchParams : searchParams,
- responseHelper : responseHelper
-};
+ response: response,
+ searchParams: searchParams,
+ responseHelper: responseHelper
+}
diff --git a/tutorials/00-cheatsheet.md b/tutorials/00-cheatsheet.md
index b261733a93..b6644847aa 100644
--- a/tutorials/00-cheatsheet.md
+++ b/tutorials/00-cheatsheet.md
@@ -1,7 +1,7 @@
# JS Helper Cheat Sheet
-
+
- [Init the helper](#init-the-helper)
@@ -21,37 +21,35 @@
## Init the helper
```
-var helper = algoliasearchHelper( client, indexName, parameters );
+var helper = algoliasearchHelper(client, indexName, parameters);
```
## Helper lifecycle
1. modify the parameters of the search (usually through user interactions)
```js
-helper.setQuery("iphone").addRefine( “category”, “phone” )
+helper.setQuery("iphone").addRefine("category", "phone");
```
2. trigger the search (after all the modification have been applied)
```js
-helper.search()
+helper.search();
```
3. read the results (with the event "result" handler) and update the UI with the results
```js
-helper.on( “result”, function( results) {
- updateUI( results );
-} );
+helper.on("result", updateUI);
```
4. go back to 1
## Objects
-**AlgoliasearchHelper** : the helper. Keeps the state of the search, makes the queries and calls the handlers when an event happen
+**AlgoliasearchHelper**: the helper. Keeps the state of the search, makes the queries and calls the handlers when an event happen
-**SearchParameters** : the object representing the state of the search.
+**SearchParameters**: the object representing the state of the search.
-**SearchResults** : the object in which the Algolia answers are transformed into. This object is passed to the result event handler.
+**SearchResults**: the object in which the Algolia answers are transformed into. This object is passed to the result event handler.
## Search
@@ -59,50 +57,48 @@ The search is triggered by the search() method.
It takes all the previous modifications to the search and use them to create the queries to Algolia. The search parameters are stateful.
-Example :
+Example:
```
-var helper = algoliasearchHelper( client, "index", {} );
+var helper = algoliasearchHelper(client, "index", {});
// Let’s monitor the results with the console
-helper.on( "result", function( content ) { console.log( content ) } );
+helper.on("result", function(content) {
+ console.log(content);
+});
// Let’s make an empty search
// The results are all taken sorted using the dashboard configuration
helper.search();
// Let’s search for "landscape"
-helper.setQuery( "landscape" ).search();
+helper.setQuery("landscape").search();
// Let’s add a category "photo"
-// Will make a search with "photo" tag and “landscape” as the query
-helper.addTag( "photo" ).search();
+// Will make a search with "photo" tag and "landscape" as the query
+helper.addTag("photo").search();
```
## Events
-result : get the new results when available. The handler function will receive two objects the search results (SearchResults) and the
+result: get the new results when available. The handler function will receive two objects the search results (SearchResults) and the
-error : get the errors from the API
+error: get the errors from the API
-change : get notified when a property has changed in the helper
+change: get notified when a property has changed in the helper
### Listen to the "result" event
```
-helper.on( "result", function( results ){
- updateTheResults( results );
-} )
+helper.on("result", updateTheResults);
```
-### Listen to an "result" event once
+### Listen to a "result" event once
```
-helper.once( "result", function( results ){
- updateTheResults( results );
-} )
+helper.once("result", updateTheResults);
```
### Remove all "result" listeners
```
-helper.removeListener( "result" )
+helper.removeListener("result");
```
## Query
@@ -110,33 +106,33 @@ helper.removeListener( "result" )
### Do a search with the query "fruit"
```
-helper.setQuery( "fruit" ).search();
+helper.setQuery("fruit").search();
```
## Filtering results
-Facets are categories created upon attributes. First you need to define which attribute will be used as facet in the dashboard : [https://www.algolia.com/explorer#?tab=display](https://www.algolia.com/explorer#?tab=display)
+Facets are categories created upon attributes. First you need to define which attribute will be used as facet in the dashboard: [https://www.algolia.com/explorer#?tab=display](https://www.algolia.com/explorer#?tab=display)
### "And" facets
#### Facet definition
```
-var helper = algoliasearchHelper( client, indexName, {
- facets : [ "andFacet" ]
-} );
+var helper = algoliasearchHelper(client, indexName, {
+ facets: ["andFacet"]
+});
```
#### Add a facet filter
```
-helper.addRefine( "andFacet", “valueOfAndFacet” ).search();
+helper.addRefine("andFacet", "valueOfAndFacet").search();
```
#### Remove a facet filter
```
-helper.removeRefine( "andFacet", “valueOfAndFacet” ).search();
+helper.removeRefine("andFacet", "valueOfAndFacet").search();
```
### "Or" facets
@@ -144,21 +140,21 @@ helper.removeRefine( "andFacet", “valueOfAndFacet” ).search();
#### Facet definition
```
-var helper = algoliasearchHelper( client, indexName, {
- disjunctiveFacets : [ "orFacet" ]
-} );
+var helper = algoliasearchHelper(client, indexName, {
+ disjunctiveFacets: ["orFacet"]
+});
```
#### Add a facet filter
```
-helper.addDisjunctiveRefine( "orFacet", “valueOfOrFacet” ).search();
+helper.addDisjunctiveRefine("orFacet", "valueOfOrFacet").search();
```
#### Remove a facet filter
```
-helper.removeDisjunctiveRefine( "orFacet", “valueOfFacet” ).search();
+helper.removeDisjunctiveRefine("orFacet", "valueOfFacet").search();
```
### Negative facets
@@ -168,21 +164,21 @@ filter so that we do NOT get a given category
#### Facet definition (same as "and" facet)
```
-var helper = algoliasearchHelper( client, indexName, {
- facets: [ "andFacet" ]
-} ).search();
+var helper = algoliasearchHelper(client, indexName, {
+ facets: ["andFacet"]
+}).search();
```
#### Exclude a value for a facet
```
-helper.addExclude( "andFacet", “valueOfAndFacetToExclude” );
+helper.addExclude("andFacet", "valueOfAndFacetToExclude");
```
#### Remove an exclude from the list of excluded values
```
-helper.removeExclude( "andFacet", “valueOfAndFacetToExclude” );
+helper.removeExclude("andFacet", "valueOfAndFacetToExclude");
```
### Numeric facets
@@ -192,21 +188,21 @@ Filter over numeric attributes with math operations like =, >, <, >=, <=. Can be
#### Facet definition
```
-var helper = algoliasearchHelper( client, indexName, {
- disjunctiveFacets : [ "numericFacet" ]
-} );
+var helper = algoliasearchHelper(client, indexName, {
+ disjunctiveFacets: ["numericFacet"]
+});
```
#### Add a numeric refinement
```
-helper.addNumericRefinement( "numericFacet", “=”, “3” ).search();
+helper.addNumericRefinement("numericFacet", "=", "3").search();
```
#### Remove a numeric refinement
```
-helper.removeNumericRefinemetn( "numericFacet", “=”, “3” ).search();
+helper.removeNumericRefinemetn("numericFacet", "=", "3").search();
```
### Clearing filters
@@ -220,15 +216,15 @@ helper.clearRefinements().search();
#### Clear all the refinements for a specific attribute
```
-helper.clearRefinements( "andFacet" ).search();
+helper.clearRefinements("andFacet").search();
```
#### [ADVANCED] Clear only the exclusions on the "andFacet" attribute
```
-helper.clearRefinements( function( value, attribute, type ) {
- return type==="exclude” && attribute===”andFacet”;
-} ).search();
+helper.clearRefinements(function(value, attribute, type) {
+ return type === "exclude" && attribute === "andFacet";
+}).search();
```
## Tags
@@ -238,13 +234,13 @@ Tags are an easy way to do filtering. They are based on a special attribute in t
### Add a tag filter for the value "landscape"
```
-helper.addTag( "landscape" ).search();
+helper.addTag("landscape").search();
```
### Remove a tag filter for the value "landscape"
```
-helper.removeTag( "landscape" ).search();
+helper.removeTag("landscape").search();
```
### Clear all the tags filters
@@ -262,7 +258,7 @@ helper.getCurrentPage();
### Change page
```
-helper.setCurrentPage( 3 ).search();
+helper.setCurrentPage(3).search();
```
## Index
@@ -271,7 +267,7 @@ Index can be changed. The common use case is when you have several slaves with d
### Change the current index
```
-helper.setIndex( "index_orderByPrice" ).search();
+helper.setIndex("index_orderByPrice").search();
```
### Get the current index
@@ -286,15 +282,15 @@ There are lots of other parameters you can set.
### Set a parameter at the initialization of the helper
```
-var helper = algoliasearchHelper( client, indexName, {
- hitsPerPage : 50
-} );
+var helper = algoliasearchHelper(client, indexName, {
+ hitsPerPage: 50
+});
```
### Set a parameter later
```
-helper.setQueryParameter( "hitsPerPage", 20 ).search();
+helper.setQueryParameter("hitsPerPage", 20).search();
```
### List of parameters that can be set
@@ -605,7 +601,7 @@ helper.setQueryParameter( "hitsPerPage", 20 ).search();
string
- How the query should be treated by the search engine. Possible values : prefixAll, prefixLast, prefixNone
+ How the query should be treated by the search engine. Possible values: prefixAll, prefixLast, prefixNone
queryType on Algolia.com
|
@@ -677,7 +673,7 @@ helper.setQueryParameter( "hitsPerPage", 20 ).search();
string
- How the typo tolerance behave in the search engine. Possible values : true, false, min, strict
+ How the typo tolerance behave in the search engine. Possible values: true, false, min, strict
typoTolerance on Algolia.com
|
diff --git a/zuul.config.js b/zuul.config.js
index 9c459b6fab..08949120a1 100644
--- a/zuul.config.js
+++ b/zuul.config.js
@@ -1,4 +1,4 @@
-"use strict";
+'use strict'
var zuulConfig = module.exports = {
ui: 'tape',
@@ -8,72 +8,76 @@ var zuulConfig = module.exports = {
transform: 'envify'
}],
scripts: [
+
// browser integration tests will use the dist file, so that we test the
// build process also
'/dist/algoliasearch.helper.min.js'
],
+
// only used when run with saucelabs
// not activated when dev or phantom
concurrency: 5,
+
// if browser does not sends output in 30s since last output:
// stop testing, something is wrong
- browser_output_timeout: 50*1000,
+ browser_output_timeout: 50 * 1000,
+
// we want to be notified something is wrong asap, so no retry
browser_retries: 0
-};
+}
if (process.env.TRAVIS_BUILD_NUMBER !== undefined) {
- zuulConfig.tunnel = 'ngrok';
+ zuulConfig.tunnel = 'ngrok'
}
var browsers = {
all: [{
- name: 'chrome',
- version: '42..beta',
- platform: 'Windows 2012 R2' // Force Win 8.1, more stable than linux etc
- }, {
- name: 'firefox',
- version: '37..beta',
- platform: 'Windows 2012 R2'
- }, {
- name: 'ie',
- version: '9..latest'
- }, {
- name: 'safari',
- version: '6..latest'
- }, {
- name: 'iphone',
- version: '7.0..latest'
- }, {
- name: 'android',
- version: '4.1..latest'
- }, {
- name: 'ipad',
- version: '7.0..latest'
- }
+ name: 'chrome',
+ version: '42..beta',
+ platform: 'Windows 2012 R2' // Force Win 8.1, more stable than linux etc
+ }, {
+ name: 'firefox',
+ version: '37..beta',
+ platform: 'Windows 2012 R2'
+ }, {
+ name: 'ie',
+ version: '9..latest'
+ }, {
+ name: 'safari',
+ version: '6..latest'
+ }, {
+ name: 'iphone',
+ version: '7.0..latest'
+ }, {
+ name: 'android',
+ version: '4.1..latest'
+ }, {
+ name: 'ipad',
+ version: '7.0..latest'
+ }
],
pullRequest: [{
- name: 'chrome',
- version: 'latest', // `latest` === stable
- platform: 'Windows 2012 R2'
- }, {
- name: 'firefox',
- version: 'latest',
- platform: 'Windows 2012 R2'
- }, {
- name: 'ie',
- version: 'latest'
- }, {
- name: 'iphone',
- version: 'latest'
- }, {
- name: 'android',
- version: 'latest'
- }
+ name: 'chrome',
+ version: 'latest', // `latest` === stable
+ platform: 'Windows 2012 R2'
+ }, {
+ name: 'firefox',
+ version: 'latest',
+ platform: 'Windows 2012 R2'
+ }, {
+ name: 'ie',
+ version: 'latest'
+ }, {
+ name: 'iphone',
+ version: 'latest'
+ }, {
+ name: 'android',
+ version: 'latest'
+ }
]
-};
+}
zuulConfig.browsers =
process.env.TRAVIS_PULL_REQUEST && process.env.TRAVIS_PULL_REQUEST !== 'false' ?
browsers.pullRequest :
- browsers.all;
+ browsers.all