Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
_find (params = {}) {
const paginate = typeof params.paginate !== 'undefined' ? params.paginate : this.paginate;
// Prepare the special query params.
const { filters } = filterQuery(params.query || {}, paginate);
let q = params.rethinkdb || this.createQuery(params.query);
let countQuery;
// For pagination, count has to run as a separate query, but without limit.
if (paginate.default) {
countQuery = q.count().run();
}
// Handle $skip AFTER the count query but BEFORE $limit.
if (filters.$skip) {
q = q.skip(filters.$skip);
}
// Handle $limit AFTER the count query and $skip.
if (typeof filters.$limit !== 'undefined') {
q = q.limit(filters.$limit);
return this._find(params).then(page => {
const items = page.data;
const { query } = filterQuery(params.query || {});
const q = this.db(params);
// build up the knex query out of the query params
this.knexify(q, query);
return q.del().then(() => {
if (id !== null) {
if (items.length === 1) {
return items[0];
} else {
throw new errors.NotFound(`No record found for id '${id}'`);
}
}
return items;
});
createQuery (params = {}) {
const { schema, table, id } = this;
const { filters, query } = filterQuery(params.query || {});
let q = this.db(params);
if (schema) { q = q.withSchema(schema).from(`${table} as ${table}`); }
q = (filters.$select)
// $select uses a specific find syntax, so it has to come first.
? q.select(...filters.$select.concat(`${table}.${id}`))
: q.select([`${table}.*`]);
// build up the knex query out of the query params
this.knexify(q, query);
// Handle $sort
if (filters.$sort) {
Object.keys(filters.$sort).forEach(key => {
q = q.orderBy(key, filters.$sort[key] === 1 ? 'asc' : 'desc');
patch (id, raw, params) {
const query = filterQuery(params.query || {}).query;
const data = Object.assign({}, raw);
const mapIds = page => page.data.map(current => current[this.id]);
// By default we will just query for the one id. For multi patch
// we create a list of the ids of all items that will be changed
// to re-query them after the update
const ids = id === null ? this._find(params)
.then(mapIds) : Promise.resolve([ id ]);
if (id !== null) {
query[this.id] = id;
}
const q = this.db(params);
this.knexify(q, query);
createQuery (originalQuery) {
const { filters, query } = filterQuery(originalQuery || {});
let r = this.options.r;
let rq = this.table.filter(this.createFilter(query));
// Handle $select
if (filters.$select) {
rq = rq.pluck(filters.$select);
}
// Handle $sort
if (filters.$sort) {
_.each(filters.$sort, (order, fieldName) => {
if (parseInt(order) === 1) {
rq = rq.orderBy(fieldName);
} else {
rq = rq.orderBy(r.desc(fieldName));
query => filterQuery(query, paginate)
);