From 9a2f61bc6f6634a4be517ddedfa70a18d80bd6ad Mon Sep 17 00:00:00 2001 From: Stefan Peters Date: Fri, 13 Nov 2020 12:13:13 +0100 Subject: [PATCH] Use new creator middleware in scheme service (#122) --- routes/schemes.js | 2 ++ services/schemes.js | 34 ++++++++++------------------------ 2 files changed, 12 insertions(+), 24 deletions(-) diff --git a/routes/schemes.js b/routes/schemes.js index 6d23ded..1f80d6a 100644 --- a/routes/schemes.js +++ b/routes/schemes.js @@ -43,6 +43,7 @@ if (config.schemes.update) { utils.wrappers.async(async (req) => { return await schemeService.putScheme({ body: req.body, + existing: req.existing, }) }), utils.adjust, @@ -58,6 +59,7 @@ if (config.schemes.delete) { utils.wrappers.async(async (req) => { return await schemeService.deleteScheme({ uri: req.query.uri, + existing: req.existing, }) }), (req, res) => res.sendStatus(204), diff --git a/services/schemes.js b/services/schemes.js index 2a4c829..e9c878e 100644 --- a/services/schemes.js +++ b/services/schemes.js @@ -161,18 +161,14 @@ module.exports = class SchemeService { return isMultiple ? response : response[0] } - async putScheme({ body }) { + async putScheme({ body, existing }) { let scheme = body // Prepare scheme = await this.prepareAndCheckSchemeForAction(scheme, "update") - const existingScheme = await Scheme.findById(scheme.uri).lean() - if (!existingScheme) { - throw new EntityNotFoundError() - } - if (existingScheme.created) { - scheme.created = existingScheme.created + if (existing.created) { + scheme.created = existing.created } // Write scheme to database @@ -189,12 +185,16 @@ module.exports = class SchemeService { return scheme } - async deleteScheme({ uri }) { + async deleteScheme({ uri, existing }) { if (!uri) { throw new MalformedRequestError() } - const scheme = await this.prepareAndCheckSchemeForAction({ uri }, "delete") - const result = await Scheme.deleteOne({ _id: scheme._id }) + if (existing.concepts.length) { + // Disallow deletion + // ? Which error type? + throw new MalformedRequestError(`Concept scheme ${uri} still has concepts in the database and therefore can't be deleted.`) + } + const result = await Scheme.deleteOne({ _id: existing._id }) if (!result.ok) { throw new DatabaseAccessError() } @@ -232,20 +232,6 @@ module.exports = class SchemeService { delete scheme.created } } - if (action == "delete") { - // Replace scheme with scheme from databas - const uri = scheme.uri - scheme = await Scheme.findById(uri).lean() - if (!scheme) { - throw new EntityNotFoundError(null, uri) - } - // Check if concepts exists - if (scheme.concepts.length) { - // Disallow deletion - // ? Which error type? - throw new MalformedRequestError(`Concept scheme ${uri} still has concepts in the database and therefore can't be deleted.`) - } - } return scheme }