common.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { internal_getRequestContext } from '@vendure/core';
  2. import { Request } from 'express';
  3. import { AssetServerOptions, ImageTransformFormat } from './types';
  4. export function getAssetUrlPrefixFn(options: AssetServerOptions) {
  5. const { assetUrlPrefix, route } = options;
  6. if (assetUrlPrefix == null) {
  7. return (request: Request, identifier: string) => {
  8. const protocol = request.headers['x-forwarded-proto'] ?? request.protocol;
  9. return `${Array.isArray(protocol) ? protocol[0] : protocol}://${
  10. request.get('host') ?? 'could-not-determine-host'
  11. }/${route}/`;
  12. };
  13. }
  14. if (typeof assetUrlPrefix === 'string') {
  15. return (...args: any[]) => assetUrlPrefix;
  16. }
  17. if (typeof assetUrlPrefix === 'function') {
  18. return (request: Request, identifier: string) => {
  19. const ctx = internal_getRequestContext(request);
  20. return assetUrlPrefix(ctx, identifier);
  21. };
  22. }
  23. throw new Error(`The assetUrlPrefix option was of an unexpected type: ${JSON.stringify(assetUrlPrefix)}`);
  24. }
  25. export function getValidFormat(format?: unknown): ImageTransformFormat | undefined {
  26. if (typeof format !== 'string') {
  27. return undefined;
  28. }
  29. switch (format) {
  30. case 'jpg':
  31. case 'jpeg':
  32. case 'png':
  33. case 'webp':
  34. case 'avif':
  35. return format;
  36. default:
  37. return undefined;
  38. }
  39. }