export function wrap()

in src/main.ts [109:189]


export function wrap<T>(
  cloudFunction: CloudFunction<T>
): WrappedScheduledFunction | WrappedFunction {
  if (!has(cloudFunction, '__trigger')) {
    throw new Error(
      'Wrap can only be called on functions written with the firebase-functions SDK.'
    );
  }

  if (get(cloudFunction, '__trigger.labels.deployment-scheduled') === 'true') {
    const scheduledWrapped: WrappedScheduledFunction = (
      options: ContextOptions
    ) => {
      // Although in Typescript we require `options` some of our JS samples do not pass it.
      options = options || {};

      _checkOptionValidity(['eventId', 'timestamp'], options);
      const defaultContext = _makeDefaultContext(cloudFunction, options);
      const context = merge({}, defaultContext, options);

      // @ts-ignore
      return cloudFunction.run(context);
    };
    return scheduledWrapped;
  }

  if (
    has(cloudFunction, '__trigger.httpsTrigger') &&
    get(cloudFunction, '__trigger.labels.deployment-callable') !== 'true'
  ) {
    throw new Error(
      'Wrap function is only available for `onCall` HTTP functions, not `onRequest`.'
    );
  }

  if (!has(cloudFunction, 'run')) {
    throw new Error(
      'This library can only be used with functions written with firebase-functions v1.0.0 and above'
    );
  }

  const isCallableFunction =
    get(cloudFunction, '__trigger.labels.deployment-callable') === 'true';

  let wrapped: WrappedFunction = (data: T, options: ContextOptions) => {
    // Although in Typescript we require `options` some of our JS samples do not pass it.
    options = options || {};
    let context;

    if (isCallableFunction) {
      _checkOptionValidity(
        ['app', 'auth', 'instanceIdToken', 'rawRequest'],
        options
      );
      let callableContextOptions = options as CallableContextOptions;
      context = {
        ...callableContextOptions,
      };
    } else {
      _checkOptionValidity(
        ['eventId', 'timestamp', 'params', 'auth', 'authType', 'resource'],
        options
      );
      const defaultContext = _makeDefaultContext(cloudFunction, options, data);

      if (
        has(defaultContext, 'eventType') &&
        defaultContext.eventType !== undefined &&
        defaultContext.eventType.match(/firebase.database/)
      ) {
        defaultContext.authType = 'UNAUTHENTICATED';
        defaultContext.auth = null;
      }
      context = merge({}, defaultContext, options);
    }

    return cloudFunction.run(data, context);
  };

  return wrapped;
}