utils.ts 2.5 KB

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