mirror of
https://github.com/directus/directus.git
synced 2026-01-27 07:08:17 -05:00
Add fields param
This commit is contained in:
31
src/middleware/sanitize-query.ts
Normal file
31
src/middleware/sanitize-query.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Sanitize query parameters.
|
||||
* This ensures that query params are formatted and ready to go for the services.
|
||||
*/
|
||||
|
||||
import { RequestHandler } from 'express';
|
||||
import { Query } from '../types/query';
|
||||
|
||||
const sanitizeQuery: RequestHandler = (req, res, next) => {
|
||||
if (!req.query) return;
|
||||
|
||||
const query: Query = {};
|
||||
|
||||
if (req.query.fields) {
|
||||
query.fields = sanitizeFields(req.query.fields);
|
||||
}
|
||||
|
||||
res.locals.query = query;
|
||||
return next();
|
||||
};
|
||||
|
||||
export default sanitizeQuery;
|
||||
|
||||
function sanitizeFields(rawFields: any) {
|
||||
let fields: string[] = [];
|
||||
|
||||
if (typeof rawFields === 'string') fields = rawFields.split(',');
|
||||
else if (Array.isArray(rawFields)) fields = rawFields as string[];
|
||||
|
||||
return fields;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
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';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -14,8 +15,9 @@ router.post(
|
||||
|
||||
router.get(
|
||||
'/:collection',
|
||||
sanitizeQuery,
|
||||
asyncHandler(async (req, res) => {
|
||||
const records = await readItems(req.params.collection);
|
||||
const records = await readItems(req.params.collection, res.locals.query);
|
||||
|
||||
return res.json({
|
||||
data: records,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import database from '../database';
|
||||
import { Query } from '../types/query';
|
||||
import logger from '../logger';
|
||||
|
||||
export const createItem = async (
|
||||
collection: string,
|
||||
@@ -10,7 +11,7 @@ export const createItem = async (
|
||||
};
|
||||
|
||||
export const readItems = async (collection: string, query: Query = {}) => {
|
||||
return await database.select('*').from(collection);
|
||||
return await database.select(query?.fields || '*').from(collection);
|
||||
};
|
||||
|
||||
export const readItem = async (collection: string, pk: number | string, query = {}) => {
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
export type Query = {};
|
||||
export type Query = {
|
||||
fields?: string[];
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user