Work on field query validation a bit

This commit is contained in:
rijkvanzanten
2020-07-07 15:54:59 -04:00
parent 15f1f629e4
commit a034e44775
5 changed files with 74 additions and 38 deletions

43
src/utils/has-fields.ts Normal file
View File

@@ -0,0 +1,43 @@
import database, { schemaInspector } from '../database';
import { FIELD_SPECIAL_ALIAS_TYPES } from '../constants';
import { uniq } from 'lodash';
export default async function hasFields(fields: { collection: string; field: string }[]) {
const fieldsObject: { [collection: string]: string[] } = {};
fields.forEach(({ field, collection }) => {
if (fieldsObject.hasOwnProperty(collection) === false) {
fieldsObject[collection] = [];
}
fieldsObject[collection].push(field);
});
await Promise.all(
Object.entries(fieldsObject).map(([collection, fields]) =>
collectionHasFields(collection, fields)
)
);
return true;
}
export async function collectionHasFields(collection: string, fieldKeys: string[]) {
const [columns, fields] = await Promise.all([
schemaInspector.columns(collection),
database
.select('field')
.from('directus_fields')
.where({ collection })
.whereIn('field', fieldKeys)
.whereIn('special', FIELD_SPECIAL_ALIAS_TYPES),
]);
const existingFields = uniq([
...columns.map(({ column }) => column),
...fields.map(({ field }) => field),
]);
for (const key of fieldKeys) {
if (existingFields.includes(key) === false) throw new Error(key);
}
}