Optimize has fields check

This commit is contained in:
rijkvanzanten
2020-06-17 11:44:36 -04:00
parent 45101b6f40
commit 5d540385e9
2 changed files with 17 additions and 18 deletions

View File

@@ -7,7 +7,7 @@
import { RequestHandler } from 'express';
import { Query } from '../types/query';
import { hasField } from '../services/schema';
import { hasField, hasFields } from '../services/schema';
import asyncHandler from 'express-async-handler';
import APIError, { ErrorCode } from '../error';
@@ -23,23 +23,16 @@ const validateQuery: RequestHandler = asyncHandler(async (req, res, next) => {
query.fields.forEach((field) => fieldsToCheck.add(field));
}
try {
await Promise.all(
Array.from(fieldsToCheck).map(
(field) =>
new Promise(async (resolve, reject) => {
const exists = await hasField(res.locals.collection, field);
if (exists) return resolve();
return reject({ collection: res.locals.collection, field: field });
})
)
);
} catch ({ collection, field }) {
throw new APIError(
ErrorCode.FIELD_NOT_FOUND,
`Field "${field}" doesn't exist in "${collection}"`
);
}
const fieldsExist = await hasFields(res.locals.collection, Array.from(fieldsToCheck));
Array.from(fieldsToCheck).forEach((field, index) => {
const exists = fieldsExist[index];
if (exists === false)
throw new APIError(
ErrorCode.FIELD_NOT_FOUND,
`Field ${field} doesn't exist in ${res.locals.collection}.`
);
});
return next();
});

View File

@@ -7,3 +7,9 @@ export const hasCollection = async (collection: string) => {
export const hasField = async (collection: string, field: string) => {
return await database.schema.hasColumn(collection, field);
};
export const hasFields = async (collection: string, fields: string[]) => {
const columns = await database(collection).columnInfo();
const fieldNames = Object.keys(columns);
return fields.map((fieldKey) => fieldNames.includes(fieldKey));
};