From 22fbcc57c775c6a6031ee05ec96e431c0bf2efd2 Mon Sep 17 00:00:00 2001 From: Carl Bennett Date: Mon, 31 Aug 2015 10:22:18 +1200 Subject: [PATCH] Add beforeDelete transform The id list is deliberately not replaced with the value returned from the transform as the user should not be able to silently remove ids from the id list. Therefore, this 'transform' should be used purely as a way to throw errors when the requested deletion is not allowed. Closes #66 --- src/ResourceTypeRegistry.js | 2 +- src/controllers/API.js | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/ResourceTypeRegistry.js b/src/ResourceTypeRegistry.js index 43ea8d9b..70669608 100644 --- a/src/ResourceTypeRegistry.js +++ b/src/ResourceTypeRegistry.js @@ -5,7 +5,7 @@ * whose property is being retrieved/set, and the value to set it to, if any. */ const autoGetterSetterProps = ["dbAdapter", "beforeSave", "beforeRender", - "labelMappers", "defaultIncludes", "info", "parentType"]; + "beforeDelete", "labelMappers", "defaultIncludes", "info", "parentType"]; /** * To fulfill a JSON API request, you often need to know about all the resources diff --git a/src/controllers/API.js b/src/controllers/API.js index 6a7a94f9..3785a52b 100644 --- a/src/controllers/API.js +++ b/src/controllers/API.js @@ -2,6 +2,7 @@ import co from "co"; import Response from "../types/HTTP/Response"; import Document from "../types/Document"; +import Resource from "../types/Resource"; import Collection from "../types/Collection"; import APIError from "../types/APIError"; @@ -114,6 +115,28 @@ class APIController { } } + if (request.method === "delete") { + let toTransform; + + if (Array.isArray(request.idOrIds)) { + toTransform = new Collection( + request.idOrIds.map((id) => { + if (typeof id === "string") { + return new Resource(request.type, id); + } + }) + ); + } + + else if (typeof request.idOrIds === "string") { + toTransform = new Resource(request.type, request.idOrIds); + } + + yield applyTransform( + toTransform, "beforeDelete", registry, frameworkReq, frameworkRes + ); + } + // Actually fulfill the request! // If we've already populated the primary resources, which is possible // because the label may have mapped to no id(s), we don't need to query.