From ff1ff47045b4e13c1580f02cad07c6dc82510449 Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Wed, 6 Oct 2021 03:23:24 +0000 Subject: [PATCH] feat(#317): add createResource method --- .changeset/ten-students-study.md | 5 +++++ packages/druxt/src/client.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 .changeset/ten-students-study.md diff --git a/.changeset/ten-students-study.md b/.changeset/ten-students-study.md new file mode 100644 index 000000000..e468de798 --- /dev/null +++ b/.changeset/ten-students-study.md @@ -0,0 +1,5 @@ +--- +"druxt": minor +--- + +Added createResource method to DruxtClient diff --git a/packages/druxt/src/client.js b/packages/druxt/src/client.js index 7685f1cf1..952d6c5f0 100644 --- a/packages/druxt/src/client.js +++ b/packages/druxt/src/client.js @@ -136,6 +136,37 @@ class DruxtClient { } } + /** + * Create a JSON:API resource. + * + * @param {object} resource - The JSON:API resource object + * + * @returns {object} The response data + */ + async createResource(resource) { + const { href } = await this.getIndex(resource.type) + if (!href) { + return false + } + + let response + try { + response = await this.axios.post( + href, + { data: resource }, + { + headers: { + 'Content-Type': 'application/vnd.api+json' + } + } + ) + } catch (err) { + response = (err.response || {}).data || err.message + } + + return response + } + /** * Get a collection of resources from the JSON:API server. *