text: import Field from '@apps/maha/models/field'
  import Record from '@apps/datasets/models/record'
  
  const getRecords = async(req, { dataset_id, depth, filter, sort, type_id, limit }) => {
  
    const fields = await Field.query(qb => {
      qb.where('parent_type', 'datasets_types')
      qb.where('parent_id', type_id)
    }).fetchAll({
      transacting: req.trx
    })
  
    const records = await Record.filterFetch({
      scope: qb => {
        qb.select('datasets_records.*','maha_version_versions.published_value as values')
        qb.joinRaw('inner join maha_version_versions on maha_version_versions.versionable_type=? and maha_version_versions.versionable_id=datasets_records.id','datasets_records')
        qb.where('type_id', type_id)
        qb.whereIn('maha_version_versions.status', ['published','changed'])
        qb.whereNull('deleted_at')
        if(limit) qb.limit(limit)
      },
      aliases: fields.reduce((aliases, field) => ({
        ...aliases,
        [field.get('name').token]: `maha_version_versions.published_value->>'${field.code}'`
      }), {}),
      filter: {
        params: filter
      },
      sort: {
        params: sort,
        defaults:  '-created_at'
      },
      transacting: req.trx
    })
  
    return records.map(record => ({
      id: 1,
      name: 'Aloja Airewele',
      email: 'aaa247@cornell.edu',
      phone: '(607) 272-2292 x156',
      photo: {
        id: 91,
        path: '/assets/91/img-20161125-wa0002.jpg',
        width: 200,
        height: 200
      },
      position: 'Energy Warriors Coordinator',
      ...fields.reduce((aliases, field) => ({
        ...aliases,
        [field.get('name').token]: record.get('values')[field.get('code')]
      }), {})
    }))
  
  }
  
  export default getRecords
  