Skip to content

Instantly share code, notes, and snippets.

@cameri
Created August 1, 2017 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameri/44febe7ae97683c96caf4d8f4e634bad to your computer and use it in GitHub Desktop.
Save cameri/44febe7ae97683c96caf4d8f4e634bad to your computer and use it in GitHub Desktop.
define([
'angular',
'common/common-module',
], function(angular, module) {
function Service($q, Restangular) {
var States = {
Idle: 'Idle',
Busy: 'Busy',
Done: 'Done'
};
return function(modelName, options) {
var instance = this;
if (typeof modelName === 'string') {
modelName = [ modelName ];
}
instance.model = null;
do {
var args = modelName.shift();
var func = null;
if (!instance.model) {
if (typeof args === 'string') {
func = Restangular.all;
} else {
func = Restangular.one;
}
} else {
if (typeof args === 'string') {
func = instance.model.all;
} else {
func = instance.model.one;
}
}
if (typeof args === 'string') {
args = [ args ];
}
instance.model = func.apply(undefined, args);
} while (modelName.length > 0);
instance.debug = options.debug;
instance.page = 1;
instance.limit = options.limit || 10;
instance.queryParams = options.queryParams || {};
instance.results = [];
instance.presentState = States.Idle;
function setState(nextState) {
instance.presentState = nextState;
}
function getState() {
return instance.presentState;
}
function isDone() {
return instance.presentState == States.Done;
}
instance.isDone = isDone;
function isBusy() {
return instance.presentState == States.Busy;
}
instance.isBusy = isBusy;
function setLimit(limit) {
instance.limit = limit;
}
instance.setLimit = setLimit;
function clear() {
instance.results = [];
instance.presentState = States.Idle;
instance.page = 1;
}
instance.clear = clear;
function doSearch(context, reset) {
function success(results) {
if (results.length < instance.limit) {
if (instance.debug) {
instance.page = 0;
} else {
setState(States.Done);
}
} else {
setState(States.Idle);
}
instance.page += 1;
instance.results = instance.results.concat(results);
return instance.results;
}
function failure(error) {
setState(States.Done);
throw error;
}
if (reset) {
clear();
}
if (getState() !== States.Idle) {
return $q.reject('NotIdle');
}
setState(States.Busy);
var _context = angular.copy(context);
_context.page = instance.page;
_context.per_page = instance.limit;
_context = angular.extend(_context, options.queryParams);
return instance.model.getList(_context).then(success, failure);
}
function search(context) {
return doSearch(context, true);
}
instance.search = search;
function more(context) {
return doSearch(context, false);
}
instance.more = more;
};
}
module
.service('PaginatedSearchService', [
'$q',
'Restangular',
Service
]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment