graphiti-api / spraypaint.js

Graphiti Client / Javascript ORM / JSONAPI
MIT License
108 stars 69 forks source link

Export Request model as part of main package #80

Closed e-pavlica closed 4 years ago

e-pavlica commented 4 years ago

In my current project we have a couple of "custom" endpoints in addition to the usual JSON:API routes. This PR exposes the Request object so that it can be used to create additional methods on a Spraypaint model.

Example:

import {
  Attr,
  Model,
  Request,
} from 'spraypaint';

import { ApplicationRecord } from './ApplicationRecord';

@Model()
export class Candy extends ApplicationRecord {
  static jsonapiType = 'candies';

  @Attr() flavor: string;
  @Attr() color: string;
  @Attr() type: string;

  async eat (): Promise<Candy> {
    const request = new Request(this.klass.middlewareStack, this.klass.logger);
    const url = `${this.klass.url(this.id)}/eat`;
    const response = await request.post(url, {data: null}, this.klass.fetchOptions());

    return this.fromJsonapi(
      response.jsonPayload.data,
      response.jsonPayload,
    );
  }
}