acquia / waterwheel.js

A generic JavaScript helper library to query and manipulate Drupal 8 via core REST and JSON API
https://github.com/acquia/waterwheel.js
232 stars 26 forks source link

Abstract JSON API calls by modeling resources #60

Open mortenson opened 7 years ago

mortenson commented 7 years ago

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 commented 7 years ago

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.