Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { find, curry, filter, pipe } from 'ramda';
- import { propOr, propSatisfies, not, isNil } from 'crocks';
- /**
- * Determines whether at least one of the given fields at the given prefix exists.
- *
- * If the second boolean (exclusive) is set, only one of the fields may exist.
- *
- * objectHasOneOf :: String p -> Boolean e -> [String] f -> Object o -> Boolean b
- */
- const objectHasOneOf = curry((exclusive, fields, obj) => {
- const fieldsInObj = filter(field => propSatisfies(field, not(isNil), obj), fields);
- if (fieldsInObj.length === 0) {
- return false;
- }
- if (exclusive && fieldsInObj.length > 1) {
- return false;
- }
- return true;
- });
- /**
- * Creates a middleware which determines whether one of the two fields appears in all create inputs.
- * The boolean given controls whether or not an exclusive or is used, limiting the input to exactly one of the two fields.
- *
- * If all create inputs are valid, this resolves. If not, it throws an error containing the first bad element.
- *
- * createHasOneOf :: Boolean e -> [String] f -> GraphQLMiddleware m
- */
- export const createHasOneOf = curry((exclusive, fields) => {
- const hasOneOf = objectHasOneOf('create', exclusive, fields);
- const doesNotHaveOneOf = not(hasOneOf);
- return async (resolve, parent, args, context, info) => {
- const firstBadElement = find(
- pipe(
- propOr(undefined, 'create'),
- doesNotHaveOneOf
- ),
- args.payload
- );
- if (!firstBadElement) {
- return resolve(parent, args, context, info);
- }
- throw new Error(
- `Invalid create input: ${JSON.stringify(firstBadElement)}. It must have${
- exclusive ? ' exactly ' : ' '
- }one of either ${fields.join(', or ')}.`
- );
- };
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement