Beispiel #1
0
export function updateUserAccount({
  api,
  picture,
  userId,
  ...editableFields
}: UpdateUserAccountParams): Promise<ExternalUserType> {
  invariant(api, 'api state is required.');
  invariant(userId, 'userId is required.');

  let body = editableFields;

  if (picture) {
    const form = new FormData();
    // Add all the editable fields, one by one.
    Object.keys(editableFields).forEach((key: string) => {
      // We cannot send `null` values, so we send empty string values instead.
      const value = editableFields[key];
      form.set(key, value === null ? '' : value);
    });
    // Add the picture file.
    form.set('picture_upload', picture);
    // Set the API body to be the form.
    body = form;
  }

  return callApi({
    auth: true,
    body,
    endpoint: `accounts/account/${userId}`,
    method: 'PATCH',
    apiState: api,
  });
}
Beispiel #2
0
    (resolve) => {
      const review = {
        addon: undefined,
        rating,
        version: versionId,
        body,
        title,
      };
      let method = 'POST';
      let endpoint = 'reviews/review';

      if (reviewId) {
        endpoint = `${endpoint}/${reviewId}`;
        method = 'PATCH';
        // You cannot update the version of an existing review.
        review.version = undefined;
      } else {
        if (!addonId) {
          throw new Error('addonId is required when posting a new review');
        }
        review.addon = addonId;
      }

      resolve(callApi({
        endpoint,
        body: review,
        method,
        auth: true,
        state: apiState,
        ...apiCallParams,
      }));
    });
Beispiel #3
0
 return new Promise((resolve) => {
   if (!userId) {
     throw new Error('userId cannot be falsey');
   }
   resolve(callApi({
     endpoint: `accounts/account/${userId}/reviews`,
   }));
 })
Beispiel #4
0
 it('transforms method to upper case', () => {
   mockWindow.expects('fetch')
     .withArgs(`${apiHost}/api/v3/resource/`, {
       body: undefined, credentials: undefined, method: 'GET', headers: {},
     })
     .once()
     .returns(createApiResponse());
   return api.callApi({ endpoint: 'resource', method: 'get' })
     .then(() => mockWindow.verify());
 });
Beispiel #5
0
 it('encodes non-ascii URLs in UTF8', () => {
   const endpoint = 'diccionario-español-venezuela';
   mockWindow.expects('fetch')
     .withArgs(utf8.encode(`${apiHost}/api/v3/${endpoint}/`), {
       body: undefined, credentials: undefined, method: 'GET', headers: {},
     })
     .once()
     .returns(createApiResponse());
   return api.callApi({ endpoint }).then(() => mockWindow.verify());
 });
Beispiel #6
0
export function currentUserAccount({
  api,
}: CurrentUserAccountParams): Promise<ExternalUserType> {
  invariant(api, 'api state is required.');

  return callApi({
    auth: true,
    endpoint: 'accounts/profile',
    apiState: api,
  });
}
Beispiel #7
0
    it('clears an error handler before making a request', () => {
      mockWindow.expects('fetch').returns(createApiResponse());

      const errorHandler = newErrorHandler();
      sinon.stub(errorHandler, 'clear');

      return api.callApi({ endpoint: 'resource', errorHandler })
        .then(() => {
          expect(errorHandler.clear.called).toBeTruthy();
        });
    });
export function postRating({ rating, apiState, addonId, versionId }) {
  const postData = { rating, version: versionId };
  log.debug('about to post add-on rating with', postData);
  return callApi({
    endpoint: `addons/addon/${addonId}/reviews`,
    body: postData,
    method: 'post',
    auth: true,
    state: apiState,
  });
}
Beispiel #9
0
 return new Promise((resolve) => {
   if (!user && !addon) {
     throw new Error('Either user or addon must be specified');
   }
   resolve(callApi({
     // Make an authenticated request if an API token exists.
     auth: Boolean(apiState && apiState.token),
     endpoint: 'reviews/review',
     params: { user, addon, ...params },
     state: apiState,
   }));
 });
Beispiel #10
0
export function userAccount({
  api,
  userId,
}: UserApiParams): Promise<ExternalUserType> {
  invariant(api, 'api state is required.');
  invariant(userId, 'userId is required.');

  return callApi({
    auth: true,
    endpoint: `accounts/account/${userId}`,
    apiState: api,
  });
}
Beispiel #11
0
export function userNotifications({
  api,
  userId,
}: UserApiParams): Promise<NotificationsType> {
  invariant(api, 'api state is required.');
  invariant(userId, 'userId is required.');

  return callApi({
    auth: true,
    endpoint: `accounts/account/${userId}/notifications`,
    apiState: api,
  });
}
Beispiel #12
0
export const getVersion = ({
  api,
  slug,
  versionId,
}: GetVersionParams): Promise<ExternalAddonVersionType> => {
  invariant(slug, 'slug is required');
  invariant(versionId, 'versionId is required');

  return callApi({
    apiState: api,
    auth: true,
    endpoint: `addons/addon/${slug}/versions/${versionId}/`,
  });
};
Beispiel #13
0
export function deleteUserPicture({
  api,
  userId,
}: UserApiParams): Promise<ExternalUserType> {
  invariant(api, 'api state is required.');
  invariant(userId, 'userId is required.');

  return callApi({
    auth: true,
    endpoint: `accounts/account/${userId}/picture`,
    method: 'DELETE',
    apiState: api,
  });
}
Beispiel #14
0
    it('handles an oddly-cased Content-Type', () => {
      const response = createApiResponse({
        headers: generateHeaders({ 'Content-Type': 'Application/JSON' }),
      });

      mockWindow.expects('fetch')
        .withArgs(`${apiHost}/api/v3/resource/`, {
          body: undefined, credentials: undefined, method: 'GET', headers: {},
        })
        .once()
        .returns(response);
      return api.callApi({ endpoint: 'resource', method: 'GET' })
        .then(() => mockWindow.verify());
    });
Beispiel #15
0
    it('handles non-JSON responses', () => {
      mockWindow.expects('fetch').returns(createApiResponse({
        headers: generateHeaders({ 'Content-Type': 'text/plain' }),
        text() {
          return Promise.resolve('some text response');
        },
      }));

      return api.callApi({ endpoint: 'resource' })
        .then((responseData) => {
          mockWindow.verify();
          expect(responseData).toEqual({});
        });
    });
Beispiel #16
0
    it('handles any fetch error', () => {
      mockWindow.expects('fetch').returns(Promise.reject(new Error(
        'this could be any error'
      )));

      const errorHandler = newErrorHandler();
      sinon.stub(errorHandler, 'handle');

      return api.callApi({ endpoint: 'resource', errorHandler })
        .then(unexpectedSuccess, () => {
          expect(errorHandler.handle.called).toBeTruthy();
          const args = errorHandler.handle.firstCall.args;
          expect(args[0].message).toEqual('this could be any error');
        });
    });
Beispiel #17
0
export function deleteUserAccount({
  api,
  userId,
}: UserApiParams): Promise<UserId> {
  invariant(api, 'api state is required.');
  invariant(userId, 'userId is required.');

  return callApi({
    auth: true,
    credentials: true,
    endpoint: `accounts/account/${userId}`,
    method: 'DELETE',
    apiState: api,
  });
}
Beispiel #18
0
    it('handles error responses with JSON syntax errors', () => {
      mockWindow.expects('fetch').returns(createApiResponse({
        json() {
          return Promise.reject(
            new SyntaxError('pretend this was a response with invalid JSON'));
        },
      }));

      const errorHandler = newErrorHandler();
      sinon.stub(errorHandler, 'handle');

      return api.callApi({ endpoint: 'resource' })
        .then(unexpectedSuccess, (err) => {
          expect(err.message).toEqual('pretend this was a response with invalid JSON');
        });
    });
Beispiel #19
0
export const getVersions = ({
  api,
  slug,
  ...params
}: GetVersionsParams): Promise<
  PaginatedApiResponse<ExternalAddonVersionType>,
> => {
  invariant(slug, 'slug is required');

  return callApi({
    apiState: api,
    auth: true,
    endpoint: `addons/addon/${slug}/versions/`,
    params,
  });
};
Beispiel #20
0
export function updateUserNotifications({
  api,
  notifications,
  userId,
}: UpdateUserNotificationsParams): Promise<NotificationsType> {
  invariant(api, 'api state is required.');
  invariant(userId, 'userId is required.');
  invariant(notifications, 'notifications are required.');

  return callApi({
    auth: true,
    body: notifications,
    endpoint: `accounts/account/${userId}/notifications`,
    method: 'POST',
    apiState: api,
  });
}
Beispiel #21
0
    it('passes errors to the error handler', () => {
      const nonFieldErrors = ['user_id and password cannot be blank'];
      mockWindow.expects('fetch').returns(createApiResponse({
        ok: false,
        jsonData: { non_field_errors: nonFieldErrors },
      }));

      const errorHandler = newErrorHandler();
      sinon.stub(errorHandler, 'handle');

      return api.callApi({ endpoint: 'resource', errorHandler })
        .then(unexpectedSuccess, () => {
          expect(errorHandler.handle.called).toBeTruthy();
          const args = errorHandler.handle.firstCall.args;
          expect(args[0].response.data.non_field_errors).toEqual(nonFieldErrors);
        });
    });
Beispiel #22
0
export function unsubscribeNotification({
  api,
  hash,
  notification,
  token,
}: UnsubscribeNotificationParams): Promise<NotificationType> {
  return callApi({
    auth: false,
    apiState: api,
    endpoint: 'accounts/unsubscribe',
    method: 'POST',
    body: {
      hash,
      notification,
      token,
    },
  });
}
Beispiel #23
0
 (resolve) => {
   if (!addonSlug) {
     throw new Error('addonSlug is required to build the endpoint');
   }
   let method = 'POST';
   let endpoint = `addons/addon/${addonSlug}/reviews`;
   if (reviewId) {
     endpoint = `${endpoint}/${reviewId}`;
     method = 'PATCH';
   }
   resolve(callApi({
     endpoint,
     body: data,
     method,
     auth: true,
     state: apiState,
     ...apiCallParams,
   }));
 });
Beispiel #24
0
    it('handles error responses with JSON syntax errors', () => {
      mockWindow.expects('fetch').returns(Promise.resolve({
        ok: false,
        json() {
          return Promise.reject(
            new SyntaxError('pretend this was a response with invalid JSON'));
        },
        text() {
          return Promise.resolve('actual error response');
        },
      }));

      const errorHandler = newErrorHandler();
      sinon.stub(errorHandler, 'handle');

      return api.callApi({ endpoint: 'resource', errorHandler })
        .then(() => {
          assert(false, 'unexpected success');
        }, () => {
          assert.ok(errorHandler.handle.called);
          const args = errorHandler.handle.firstCall.args;
          assert.equal(args[0].response.data.text, 'actual error response');
        });
    });