Skip to content
This repository has been archived by the owner on Oct 7, 2021. It is now read-only.

HalCollection #37

Open
davestewart opened this issue Dec 12, 2018 · 2 comments
Open

HalCollection #37

davestewart opened this issue Dec 12, 2018 · 2 comments

Comments

@davestewart
Copy link
Contributor

davestewart commented Dec 12, 2018

It seems that fetching collections of links could do with a bit of sugar.

Right now, to collect a list of resources from an array of links we need something along the lines of:

function fetch (res, name) {
  const target = res.prop(name)
  return Array.isArray(target)
    ? Promise.all(target.map(t => t.fetch()))
    : target.fetch()
}

If we had a HalCollection class, with perhaps an IFetchable interface, both HalResource and HalCollection could be fetch()ed:

const results = res.prop('site').fetch().then( /* Site or Array of Sites */ )

Of course the collection class would be iterable just like an Array as well.

What do you think?

@davestewart
Copy link
Contributor Author

A quick test and this seems to work:

class Collection extends Array {
  public fetch () {
    return Promise.all(this.map(res => res.fetch()))
  }
}

var collection = Collection.from(root.sites)
collection.fetch().then(console.log)
[HalResource]

Thoughts?

@davestewart
Copy link
Contributor Author

Hmm. So I got this working nicely, then discovered that Vue converts any classes extending Array to Arrays when it uses them. I'm sure IE will probably have issues as well.

So it seems to me that this might also be solved most easily with a fetchProp() method.

For now, I can add it to a model:

import { HalResource } from 'hal-rest-client'

export class BaseModel extends HalResource {

  public fetchProp (name: string, forceOrParams ?: boolean | object): Promise<HalResource | HalResource[]> {
    const prop = this.prop(name)
    return Array.isArray(prop)
      ? Promise.all(prop.map((res: HalResource) => res.fetch(forceOrParams)))
      : prop.fetch(forceOrParams)
  }

}

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

No branches or pull requests

1 participant