Vicente García
Vicente García

Reputation: 51

Select distinct via not sql with feathersjs rethinkdb adapter

I have an Angular 4 application developed with some Feathersjs services with rethinkdb database adapter.

I'm a newbie in not SQL persistence. In Sql I would use select distinct... from ... to get the "distinct" car makers from a car fleet to allow the user to filter this list or group by.

How can I get this in Feathers?

Upvotes: 2

Views: 524

Answers (1)

Vicente García
Vicente García

Reputation: 51

I solved my problem with a custom hook for rethinkdb database adapter in feathersjs :

module.exports = function (options = {}) { 
  return function distinct(hook) {
    let query = hook.params.query;

    // Must be a before hook
    if (hook.type !== 'before') {
      throw new Error('El hook \'distinct\' sólo puede usarse como hook \'before\' (hooks.distinct).');
    }

    // Throw error when no field is provided - eg. just users?$distinct
    if (query.$distinct === '') {
      throw new Error('$distinct no encontrado: ¿Qué campo debería ser distinto? (hooks.distinct)');
    }

    let distinctValue = query.$distinct || null;
    console.log('distinctValue', distinctValue);
    if (distinctValue == null) return hook;

    // Remove $distinct param from query (preventing errors)
    delete query.$distinct;

    // Add only the field we are searching for
    query = Object.assign({ $select: distinctValue },query)

    const rethinkdbQuery = this.createQuery(query);
    const r = this.options.r;

    // In our case, disable pagination
    hook.params.paginate = false;

    // Update the query with an additional `distinct` condition
    hook.params.rethinkdb = rethinkdbQuery.distinct();

    return hook;
  }
};

Upvotes: 3

Related Questions