Add read single

This commit is contained in:
rijkvanzanten
2020-06-30 15:03:18 -04:00
parent d52f1e5758
commit 0f8daaac79
5 changed files with 46 additions and 6 deletions

View File

@@ -0,0 +1,7 @@
import { BaseException } from './base';
export class CollectionNotFoundException extends BaseException {
constructor(collection: string) {
super(`Collection "${collection}" doesn't exist.`, 404, 'COLLECTION_NOT_FOUND');
}
}

View File

@@ -5,3 +5,4 @@ export * from './invalid-query';
export * from './item-limit';
export * from './route-not-found';
export * from './item-not-found';
export * from './collection-not-found';

View File

@@ -3,6 +3,8 @@ 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 { CollectionNotFoundException } from '../exceptions';
const router = Router();
@@ -16,4 +18,18 @@ router.get(
})
);
router.get(
'/:collection',
sanitizeQuery,
validateQuery,
asyncHandler(async (req, res) => {
const exists = await schemaInspector.hasTable(req.params.collection);
if (exists === false) throw new CollectionNotFoundException(req.params.collection);
const data = await CollectionsService.readOne(req.params.collection, req.sanitizedQuery);
res.json({ data });
})
);
export default router;

View File

@@ -27,3 +27,19 @@ export const readAll = async (query?: Query) => {
return data;
};
export const readOne = async (collection: string, query?: Query) => {
const [table, collectionInfo] = await Promise.all([
schemaInspector.table(collection),
ItemsService.readItem<Collection>('directus_collections', collection, query),
]);
return {
collection: table.name,
note: table.comment,
hidden: collectionInfo?.hidden || false,
single: collectionInfo?.single || false,
icon: collectionInfo?.icon || null,
translation: collectionInfo?.translation || null,
};
};

View File

@@ -65,12 +65,12 @@ export const readItems = async <T = Record<string, any>>(
return records;
};
export const readItem = async (collection: string, pk: number | string, query: Query = {}) => {
const dbQuery = database.select('*').from(collection).where({ id: pk });
const records = await dbQuery;
return records[0];
export const readItem = async <T = any>(
collection: string,
pk: number | string,
query: Query = {}
): Promise<T> => {
return await database.select('*').from(collection).where({ id: pk }).first();
};
export const updateItem = async (