common.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { REQUEST_CONTEXT_KEY } from '@vendure/core/dist/common/constants';
  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 `${protocol}://${request.get('host')}/${route}/`;
  10. };
  11. }
  12. if (typeof assetUrlPrefix === 'string') {
  13. return (...args: any[]) => assetUrlPrefix;
  14. }
  15. if (typeof assetUrlPrefix === 'function') {
  16. return (request: Request, identifier: string) => {
  17. const ctx = (request as any)[REQUEST_CONTEXT_KEY];
  18. return assetUrlPrefix(ctx, identifier);
  19. };
  20. }
  21. throw new Error(`The assetUrlPrefix option was of an unexpected type: ${JSON.stringify(assetUrlPrefix)}`);
  22. }
  23. export function getValidFormat(format?: unknown): ImageTransformFormat | undefined {
  24. if (typeof format !== 'string') {
  25. return undefined;
  26. }
  27. switch (format) {
  28. case 'jpg':
  29. case 'jpeg':
  30. case 'png':
  31. case 'webp':
  32. case 'avif':
  33. return format;
  34. default:
  35. return undefined;
  36. }
  37. }