Check if collection exists in items endpoints

This commit is contained in:
rijkvanzanten
2020-06-16 16:57:39 -04:00
parent f0291bc543
commit 0447a96a15
3 changed files with 27 additions and 0 deletions

View 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;

View File

@@ -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
View File

@@ -0,0 +1,5 @@
import database from '../database';
export const hasCollection = async (collection: string) => {
return await database.schema.hasTable(collection);
};