mirror of
https://github.com/directus/directus.git
synced 2026-01-25 22:18:25 -05:00
Check if collection exists in items endpoints
This commit is contained in:
16
src/middleware/collection-exists.ts
Normal file
16
src/middleware/collection-exists.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { RequestHandler } from 'express';
|
||||
import asyncHandler from 'express-async-handler';
|
||||
import database from '../database';
|
||||
import APIError, { ErrorCode } from '../error';
|
||||
|
||||
const collectionExists: RequestHandler = asyncHandler(async (req, res, next) => {
|
||||
if (!req.params.collection) return next();
|
||||
|
||||
const exists = await database.schema.hasTable(req.params.collection);
|
||||
|
||||
if (exists) return next();
|
||||
|
||||
throw new APIError(ErrorCode.NOT_FOUND, `Collection "${req.params.collection}" doesn't exist.`);
|
||||
});
|
||||
|
||||
export default collectionExists;
|
||||
@@ -2,11 +2,13 @@ import express from 'express';
|
||||
import asyncHandler from 'express-async-handler';
|
||||
import { createItem, readItems, readItem, updateItem, deleteItem } from '../services/items';
|
||||
import sanitizeQuery from '../middleware/sanitize-query';
|
||||
import collectionExists from '../middleware/collection-exists';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.post(
|
||||
'/:collection',
|
||||
collectionExists,
|
||||
asyncHandler(async (req, res) => {
|
||||
await createItem(req.params.collection, req.body);
|
||||
res.status(200).end();
|
||||
@@ -15,6 +17,7 @@ router.post(
|
||||
|
||||
router.get(
|
||||
'/:collection',
|
||||
collectionExists,
|
||||
sanitizeQuery,
|
||||
asyncHandler(async (req, res) => {
|
||||
const records = await readItems(req.params.collection, res.locals.query);
|
||||
@@ -27,6 +30,7 @@ router.get(
|
||||
|
||||
router.get(
|
||||
'/:collection/:pk',
|
||||
collectionExists,
|
||||
asyncHandler(async (req, res) => {
|
||||
const record = await readItem(req.params.collection, req.params.pk);
|
||||
|
||||
@@ -38,6 +42,7 @@ router.get(
|
||||
|
||||
router.patch(
|
||||
'/:collection/:pk',
|
||||
collectionExists,
|
||||
asyncHandler(async (req, res) => {
|
||||
await updateItem(req.params.collection, req.params.pk, req.body);
|
||||
return res.status(200).end();
|
||||
@@ -46,6 +51,7 @@ router.patch(
|
||||
|
||||
router.delete(
|
||||
'/:collection/:pk',
|
||||
collectionExists,
|
||||
asyncHandler(async (req, res) => {
|
||||
await deleteItem(req.params.collection, req.params.pk);
|
||||
return res.status(200).end();
|
||||
|
||||
5
src/services/schema.ts
Normal file
5
src/services/schema.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import database from '../database';
|
||||
|
||||
export const hasCollection = async (collection: string) => {
|
||||
return await database.schema.hasTable(collection);
|
||||
};
|
||||
Reference in New Issue
Block a user