From 49e78d064d60a14826ef163be2899a10307a8798 Mon Sep 17 00:00:00 2001 From: rijkvanzanten Date: Tue, 30 Jun 2020 18:08:03 -0400 Subject: [PATCH] Add delete collection --- src/routes/collections.ts | 14 +++++++++++++- src/services/collections.ts | 19 ++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/routes/collections.ts b/src/routes/collections.ts index dabfe77961..41dabb66df 100644 --- a/src/routes/collections.ts +++ b/src/routes/collections.ts @@ -3,7 +3,7 @@ import asyncHandler from 'express-async-handler'; import sanitizeQuery from '../middleware/sanitize-query'; import validateQuery from '../middleware/validate-query'; import * as CollectionsService from '../services/collections'; -import { schemaInspector } from '../database'; +import database, { schemaInspector } from '../database'; import { InvalidPayloadException, CollectionNotFoundException } from '../exceptions'; import Joi from '@hapi/joi'; @@ -58,4 +58,16 @@ router.get( }) ); +router.delete( + '/:collection', + asyncHandler(async (req, res) => { + if ((await schemaInspector.hasTable(req.params.collection)) === false) { + throw new CollectionNotFoundException(req.params.collection); + } + + await CollectionsService.deleteCollection(req.params.collection); + res.end(); + }) +); + export default router; diff --git a/src/services/collections.ts b/src/services/collections.ts index 59b7a9129f..057162a796 100644 --- a/src/services/collections.ts +++ b/src/services/collections.ts @@ -32,7 +32,7 @@ export const create = async (payload: any) => { }); }); - return await ItemsService.createItem('directus_collections', { + const collection = await ItemsService.createItem('directus_collections', { collection: payload.collection, hidden: payload.hidden || false, single: payload.single || false, @@ -40,6 +40,10 @@ export const create = async (payload: any) => { note: payload.note || null, translation: payload.translation || null, }); + + /** @TODO insert all fields */ + + return collection; }; export const readAll = async (query?: Query) => { @@ -81,3 +85,16 @@ export const readOne = async (collection: string, query?: Query) => { translation: collectionInfo?.translation || null, }; }; + +export const deleteCollection = async (collection: string) => { + await Promise.all([ + database.schema.dropTable(collection), + ItemsService.deleteItem('directus_collections', collection), + database.delete().from('directus_fields').where({ collection }), + database + .delete() + .from('directus_relations') + .where({ collection_many: collection }) + .orWhere({ collection_one: collection }), + ]); +};