Add fields param

This commit is contained in:
rijkvanzanten
2020-06-16 16:35:29 -04:00
parent 4cc8af1912
commit 6aa528aa32
4 changed files with 39 additions and 3 deletions

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

View File

@@ -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,

View File

@@ -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 = {}) => {

View File

@@ -1 +1,3 @@
export type Query = {};
export type Query = {
fields?: string[];
};