Skip to content

Instantly share code, notes, and snippets.

@danielthall
Created March 3, 2017 20:33
Show Gist options
  • Save danielthall/f1233e36274bc0807c76023b00b107a4 to your computer and use it in GitHub Desktop.
Save danielthall/f1233e36274bc0807c76023b00b107a4 to your computer and use it in GitHub Desktop.
A function to be used with Ember Mirage to handle requests with query params
export default function() {
this.get('foo', queryParamHandler('foo'));
}
const queryParamHandler = (model) => {
return function(db, req) {
const query = _.omit(req.queryParams, 'sortBy', 'sortDir', 'offset', 'limit');
const sortBy = req.queryParams.sortBy || 'id';
const sortDir = req.queryParams.sortBy || 'asc';
const offset = parseInt(req.queryParams.offset || 0);
const limit = parseInt(req.queryParams.limit || 20);
const filter = (item) => {
for (const k in query) {
const val = query[k];
if (!_.includes(k, 'filter')) {
if (_.isArray(val)) {
if (!_.contains(val, item[k])) {
return false;
}
} else if (val !== item[k]) {
return false;
}
}
}
return true;
};
const multiple = sortDir === 'asc' ? 1 : -1;
const sort = (a, b) => {
const aVal = a[sortBy];
const bVal = b[sortBy];
if (aVal === bVal) {
return 0;
}
if (aVal < bVal) {
return multiple * -1;
}
return multiple * 1;
};
const items = db[model].all().filter(filter).sort(sort);
const resp = this.serialize(items.slice(offset, offset + limit));
resp.meta = { pagination: { total: items.length, offset, limit } };
return resp;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment