All files / src/utils get-embedded-app-url.ts

100% Statements 20/20
100% Branches 6/6
100% Functions 2/2
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47  3x 3x 3x 3x 3x 3x             5x 1x   4x 1x   3x 3x 3x 1x   2x   3x   11x 10x 10x   3x                            
import http from 'http';
 
import * as ShopifyErrors from '../error';
import {Context} from '../context';
 
import {sanitizeHost} from './shop-validator';
 
/**
 * Helper method to get the host URL for the app.
 *
 * @param request Current HTTP request
 */
export default function getEmbeddedAppUrl(
  request: http.IncomingMessage,
): string {
  if (!request) {
    throw new ShopifyErrors.MissingRequiredArgument(
      'getEmbeddedAppUrl requires a request object argument',
    );
  }
 
  if (!request.url) {
    throw new ShopifyErrors.InvalidRequestError(
      'Request does not contain a URL',
    );
  }
 
  const url = new URL(request.url, `https://${request.headers.host}`);
  const host = url.searchParams.get('host');
 
  if (typeof host !== 'string') {
    throw new ShopifyErrors.InvalidRequestError(
      'Request does not contain a host query parameter',
    );
  }
 
  return buildEmbeddedAppUrl(host);
}
 
export function buildEmbeddedAppUrl(host: string): string {
  sanitizeHost(host, true);
 
  const decodedHost = Buffer.from(host, 'base64').toString();
 
  return `https://${decodedHost}/apps/${Context.API_KEY}`;
}