Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. import { find, curry, filter, pipe } from 'ramda';
  2. import { propOr, propSatisfies, not, isNil } from 'crocks';
  3.  
  4. /**
  5. * Determines whether at least one of the given fields at the given prefix exists.
  6. *
  7. * If the second boolean (exclusive) is set, only one of the fields may exist.
  8. *
  9. * objectHasOneOf :: String p -> Boolean e -> [String] f -> Object o -> Boolean b
  10. */
  11. const objectHasOneOf = curry((exclusive, fields, obj) => {
  12. const fieldsInObj = filter(field => propSatisfies(field, not(isNil), obj), fields);
  13.  
  14. if (fieldsInObj.length === 0) {
  15. return false;
  16. }
  17.  
  18. if (exclusive && fieldsInObj.length > 1) {
  19. return false;
  20. }
  21.  
  22. return true;
  23. });
  24.  
  25. /**
  26. * Creates a middleware which determines whether one of the two fields appears in all create inputs.
  27. * The boolean given controls whether or not an exclusive or is used, limiting the input to exactly one of the two fields.
  28. *
  29. * If all create inputs are valid, this resolves. If not, it throws an error containing the first bad element.
  30. *
  31. * createHasOneOf :: Boolean e -> [String] f -> GraphQLMiddleware m
  32. */
  33. export const createHasOneOf = curry((exclusive, fields) => {
  34. const hasOneOf = objectHasOneOf('create', exclusive, fields);
  35. const doesNotHaveOneOf = not(hasOneOf);
  36.  
  37. return async (resolve, parent, args, context, info) => {
  38. const firstBadElement = find(
  39. pipe(
  40. propOr(undefined, 'create'),
  41. doesNotHaveOneOf
  42. ),
  43. args.payload
  44. );
  45.  
  46. if (!firstBadElement) {
  47. return resolve(parent, args, context, info);
  48. }
  49.  
  50. throw new Error(
  51. `Invalid create input: ${JSON.stringify(firstBadElement)}. It must have${
  52. exclusive ? ' exactly ' : ' '
  53. }one of either ${fields.join(', or ')}.`
  54. );
  55. };
  56. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement