utils.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { AssetType } from '@vendure/common/lib/generated-types';
  2. import { ID } from '@vendure/common/lib/shared-types';
  3. /**
  4. * Takes a predicate function and returns a negated version.
  5. */
  6. export function not(predicate: (...args: any[]) => boolean) {
  7. return (...args: any[]) => !predicate(...args);
  8. }
  9. /**
  10. * Returns a predicate function which returns true if the item is found in the set,
  11. * as determined by a === equality check on the given compareBy property.
  12. */
  13. export function foundIn<T>(set: T[], compareBy: keyof T) {
  14. return (item: T) => set.some(t => t[compareBy] === item[compareBy]);
  15. }
  16. /**
  17. * Indentity function which asserts to the type system that a promise which can resolve to T or undefined
  18. * does in fact resolve to T.
  19. * Used when performing a "find" operation on an entity which we are sure exists, as in the case that we
  20. * just successfully created or updated it.
  21. */
  22. export function assertFound<T>(promise: Promise<T | undefined>): Promise<T> {
  23. return promise as Promise<T>;
  24. }
  25. /**
  26. * Compare ID values for equality, taking into account the fact that they may not be of matching types
  27. * (string or number).
  28. */
  29. export function idsAreEqual(id1?: ID, id2?: ID): boolean {
  30. if (id1 === undefined || id2 === undefined) {
  31. return false;
  32. }
  33. return id1.toString() === id2.toString();
  34. }
  35. /**
  36. * Returns the AssetType based on the mime type.
  37. */
  38. export function getAssetType(mimeType: string): AssetType {
  39. const type = mimeType.split('/')[0];
  40. switch (type) {
  41. case 'image':
  42. return AssetType.IMAGE;
  43. case 'video':
  44. return AssetType.VIDEO;
  45. default:
  46. return AssetType.BINARY;
  47. }
  48. }
  49. /**
  50. * A simple normalization for email addresses. Lowercases the whole address,
  51. * even though technically the local part (before the '@') is case-sensitive
  52. * per the spec. In practice, however, it seems safe to treat emails as
  53. * case-insensitive to allow for users who might vary the usage of
  54. * upper/lower case. See more discussion here: https://ux.stackexchange.com/a/16849
  55. */
  56. export function normalizeEmailAddress(input: string): string {
  57. return input.trim().toLowerCase();
  58. }