Skip to content
This repository has been archived by the owner on Nov 16, 2018. It is now read-only.

Abstract JSON API calls by modeling resources #60

Open
mortenson opened this issue Jul 5, 2017 · 1 comment
Open

Abstract JSON API calls by modeling resources #60

mortenson opened this issue Jul 5, 2017 · 1 comment

Comments

@mortenson
Copy link

mortenson commented Jul 5, 2017

I've recently started using ghidoz/angular2-jsonapi, which allows developers to model their JSON API resources and query for those models, instead of querying for a specific path (i.e. you ask for Article[], not /articles). Here's an example model for an article:

@JsonApiModelConfig({
  type: 'articles'
})
export class Article extends JsonApiModel {

  @Attribute()
  internalId: number;

  @Attribute()
  createdAt: Date;

  @Attribute()
  title: string;

  @HasMany()
  tags: Tag[];

  @BelongsTo()
  owner: User;

}

In addition to documenting your attributes, angular2-jsonapi will also convert certain data for you automatically - for example it will parse the "createdAt" property as a date string and make sure article.date is a valid Date object. You'll also notice that the modeling syntax supports JSON API relationships - so if you query for Articles and and include users, article.owner will represent a User object, which is also defined as a model. Here is the final query call for all articles and their owners, once everything is set up:

let query = this.datastore.query(Article, {
  include: 'owner'
});
query.subscribe(
  (articles: Article[]) => {
    // You can access article.owner directly now!
  }
);

Without getting more into the weeds of how angular2-jsonapi works, I think that generally the DX of modeling resources like this is super valuable, and makes the resulting query code very clean.

Right now Waterwheel abstracts query building, the http request, and auth from users, so I feel that this is a natural next-step to improving the DX of querying Drupal data.

@mortenson
Copy link
Author

To save a lot re-implementation for handling relationships and included resources, it might be worth looking into adding https://github.com/mysidewalk/jsonapi-parse as a step towards fully modeled resources. Sounds like an easy DX improvement.

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

No branches or pull requests

2 participants