devour-js/devour-client

Missing Relationship Function: DELETE

thedanmwangi opened this issue · 2 comments

Hello, great work on this package!

However, I have encountered an error when deleting a relationship using the code:
jsonApi.one('author', 1).relationships('articles').delete([{ id: 1 }])

The error I am getting is:
Uncaught TypeError: schema_schema__WEBPACK_IMPORTED_MODULE_12. jsonApi.one(...).relationships(...).delete is not a function_

Could this be an internal issue with the package?

I am on the latest version of Devour-Client.

tijn commented

You're right. In our own apps we're using a patch for this that probably should become part of the official devour-client, but only after improving.

Our code looks like this:

import { get, last, map } from "lodash"

export function destroyRelationships(relationshipName, ids, params = {}) {
  const lastRequest = last(this.builderStack)
  const modelName = get(lastRequest, "model")
  if (!modelName) {
    throw new Error("destroyRelationships must be called with a preceding model.")
  }
  const relationship = this.relationshipFor(modelName, relationshipName)

  this.builderStack.push({ path: "relationships" })
  this.builderStack.push({ path: relationship.path, model: relationship.type })

  const data = map(ids, (id) => {
    return { type: relationship.type, id: id }
  })

  const req = {
    method: "DELETE",
    url: this.urlFor(),
    model: modelName,
    params: params,
    data: data,
  }

  if (this.resetBuilderOnCall) {
    this.resetBuilder()
  }

  return this.runMiddleware(req)
}

The thing with this code is that you cannot use it like you described (which would be totally logical to expect):

jsonApi.one('author', 1).relationships('articles').delete([{ id: 1 }])

You need to do something like this:

jsonApi.one('author', 1).destroyRelationships('articles', [1])

So, you see, it works but it should be brought in line with the rest of the methods (in my opinion).