Sha256: dad43784ea757f3ad9976c1f26d5dc6965c0881d9add94c3c1e349623e8772e8

Contents?: true

Size: 1.6 KB

Versions: 7

Compression:

Stored size: 1.6 KB

Contents

import pluralize from 'pluralize'
import _ from 'lodash'
import { useSelector } from 'react-redux'

export default function (schema) {
  function addRelations(s, objects, objectType, relations) {
    // first find out relation name
    if (_.isArray(relations)) {
      relations.forEach(relation => {
        objects = addRelations(s, objects, objectType, relation)
      })
    } else if (typeof(relations) === 'object') {
      const relation = Object.keys(relations)[0]
      const subRelations = relations[relation]

      objects = addRelations(s, objects, objectType, relation)
      objects[relation] = addRelations(s, objects[relation], pluralize(relation), subRelations)
      // #
    } else if (typeof(relations) === 'string') {
      const relation = relations
      if (_.isArray(objects)) {
        objects = objects.map(obj => addRelations(s, obj, objectType, relation))
      } else {
        const relatedObjects = _.values(s[pluralize(relation)].entities)

        if(pluralize.isSingular(relation)) {
          objects = { ...objects, [relation]: _.find(relatedObjects, { id: objects[relation + 'Id'] }) }
        } else {
          objects = { ...objects, [relation]: relatedObjects.filter(e => e[pluralize.singular(objectType) + 'Id'] === objects.id) }
        }
      }
    }

    return objects
  }

  function useEager(entity, id = null, relations = []) {
    if (id) {
      return useSelector(s => addRelations(s, { ...s[entity].entities[String(id)] }, entity, relations))
    } else {
      return useSelector(s => addRelations(s, _.values(s[entity].entities), entity, relations))
    }
  }

  return useEager
}

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
jason-rails-0.6.1 client/src/makeEager.ts
jason-rails-0.6.0 client/src/makeEager.ts
jason-rails-0.5.1 client/src/makeEager.ts
jason-rails-0.5.0 client/src/makeEager.ts
jason-rails-0.4.1 client/src/makeEager.ts
jason-rails-0.4.0 client/src/makeEager.ts
jason-rails-0.3.0 client/src/makeEager.ts