Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Polymorphic relations and MultiMapper #83

Open
rhys-vdw opened this issue Jun 10, 2016 · 1 comment
Open

Polymorphic relations and MultiMapper #83

rhys-vdw opened this issue Jun 10, 2016 · 1 comment
Labels

Comments

@rhys-vdw
Copy link
Owner

rhys-vdw commented Jun 10, 2016

Should be fairly simple in the belongsTo end.

hasMany and belongsToMany are more complicated:

Images.relations({
  owners() return this.polymorphicBelongsToMany(posts, users, pages, comments, { typeAttribute: 'owner_type', idAttribute: 'owner_id' });
})

const images = [
  { id: 5, owner_type: 'posts', owner_id: 6, path: '...' },
  { id: 24, owner_type: 'posts', owner_id: 8, path: '...' },
  { id: 5, owner_type: 'users', owner_id: 24, path: '...' },
]

// `fetch` returns a `MultiMapper` that delegates to each of the required mappers.
Images.relation('owners').of(images).fetch().then(({ posts, users }) => {
  // whatever
});
class MultiMapper extends Chain {

  initialize() {
    this.setState({ mappers: {} })
  }

  mappers(...mappers) {
    const next = keyBy(flatten(mappers), m => m.getName())
  }

  delegateAsync(method, ...args) {
    const promises = mapValues(this.state.mappers, m => m[method](...args))
    return Promise.props(promises);
  }

  delegate(method, ...args) {
    const mappers = mapValues(this.state.mappers, m => m[method](...args))
    this.setState({ mappers })
  }

}

function delegateMethods(methodNames, delegationMethod) {
  return transform(methodNames, (results, name) => {
    result[name] = function(...args) {
      this[delegationMethod](name, args);
    }
  }, {});
}

const asyncMethods = ['fetch', 'update', 'insert', 'updateAll', 'destroyAll'];
const syncMethods = ['require', 'attributes'];

assign(
  MultMapper.prototype,
  delegateMethods(syncMethods, 'delegate'),
  delegateMethods(syncMethods, 'delegateAsync')
);

export default MultiMapper; 
@rhys-vdw rhys-vdw added the TODO label Jun 10, 2016
@rhys-vdw
Copy link
Owner Author

This can be supported more easily using a Proxy instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant