Skip to content

Commit

Permalink
wpcom-proxy-request: Return Promise if no callback specified (Take 3) (
Browse files Browse the repository at this point in the history
…#39825)

* Revert "Revert "wpcom-proxy-request: Return Promise if no callback specified (Take Two) (#39722)" (#39823)"

This reverts commit 1753cb9.

* Update type location

* Update imports

* Fix tests to use wpcom-proxy-request
  • Loading branch information
sirreal authored Mar 3, 2020
1 parent 2a10e7d commit af0d7ff
Show file tree
Hide file tree
Showing 19 changed files with 117 additions and 83 deletions.
1 change: 0 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,3 @@ Dockerfile
/apps/*/dist/
/apps/*/types/
/packages/*/dist/
/packages/*/types/
3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,3 @@ cached-requests.json
/apps/*/dist/
/apps/*/types/
/packages/*/dist/
# Redundant after https://github.com/Automattic/wp-calypso/pull/39173
# Safe to remove after some time has passed
/packages/*/types/
11 changes: 0 additions & 11 deletions packages/data-stores/global.d.ts

This file was deleted.

6 changes: 5 additions & 1 deletion packages/data-stores/src/auth/controls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,19 @@
*/
import { createRegistryControl } from '@wordpress/data';
import { stringify } from 'qs';
import wpcomRequest, { requestAllBlogsAccess } from 'wpcom-proxy-request';

/**
* Internal dependencies
*/
import { wpcomRequest, WpcomClientCredentials } from '../utils';
import { FetchAuthOptionsAction, FetchWpLoginAction } from './actions';
import { STORE_KEY } from './constants';
import { WpcomClientCredentials } from '../shared-types';

export function createControls( clientCreds: WpcomClientCredentials ) {
requestAllBlogsAccess().catch( () => {
throw new Error( 'Could not get all blog access.' );
} );
return {
SELECT_USERNAME_OR_EMAIL: createRegistryControl( registry => () => {
return registry.select( STORE_KEY ).getUsernameOrEmail();
Expand Down
2 changes: 1 addition & 1 deletion packages/data-stores/src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import * as actions from './actions';
import { createControls } from './controls';
import * as selectors from './selectors';
import { DispatchFromMap, SelectFromMap } from '../mapped-types';
import { WpcomClientCredentials } from '../utils';
import { WpcomClientCredentials } from '../shared-types';

export * from './types';
export { State };
Expand Down
16 changes: 10 additions & 6 deletions packages/data-stores/src/auth/test/controls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,22 @@
* @jest-environment jsdom
*/

/**
* External dependencies
*/
import wpcomRequest from 'wpcom-proxy-request';

/**
* Internal dependencies
*/
import { wpcomRequest as wpcomRequestOriginal } from '../../utils';
import { createControls } from '../controls';

jest.mock( '../../utils', () => ( {
wpcomRequest: jest.fn(),
jest.mock( 'wpcom-proxy-request', () => ( {
__esModule: true,
default: jest.fn(),
requestAllBlogsAccess: jest.fn( () => Promise.resolve() ),
} ) );

const wpcomRequest: jest.Mock = wpcomRequestOriginal as any;

const { FETCH_AUTH_OPTIONS } = createControls( { client_id: '', client_secret: '' } );

describe( 'FETCH_AUTH_OPTIONS', () => {
Expand All @@ -26,7 +30,7 @@ describe( 'FETCH_AUTH_OPTIONS', () => {
success: true,
data: { token_links: [] },
};
wpcomRequest.mockResolvedValue( apiResponse );
( wpcomRequest as jest.Mock ).mockResolvedValue( apiResponse );

const result = await FETCH_AUTH_OPTIONS( {
type: 'FETCH_AUTH_OPTIONS',
Expand Down
16 changes: 10 additions & 6 deletions packages/data-stores/src/auth/test/flows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,19 @@
*/
import { dispatch, select } from '@wordpress/data';
import { parse } from 'qs';
import wpcomRequest from 'wpcom-proxy-request';

/**
* Internal dependencies
*/
import { register } from '..';
import { wpcomRequest as wpcomRequestOriginal } from '../../utils';

jest.mock( '../../utils', () => ( {
wpcomRequest: jest.fn(),
jest.mock( 'wpcom-proxy-request', () => ( {
__esModule: true,
default: jest.fn(),
requestAllBlogsAccess: jest.fn( () => Promise.resolve() ),
} ) );

const wpcomRequest: jest.Mock = wpcomRequestOriginal as any;
const fetch = jest.fn();

beforeAll( () => {
Expand All @@ -34,7 +35,7 @@ beforeEach( () => {
store = register( { client_id: '', client_secret: '' } );

fetch.mockReset();
wpcomRequest.mockReset();
( wpcomRequest as jest.Mock ).mockReset();
} );

describe( 'password login flow', () => {
Expand All @@ -44,7 +45,10 @@ describe( 'password login flow', () => {

expect( getLoginFlowState() ).toBe( 'ENTER_USERNAME_OR_EMAIL' );

wpcomRequest.mockResolvedValue( { email_verified: true, passwordless: false } );
( wpcomRequest as jest.Mock ).mockResolvedValue( {
email_verified: true,
passwordless: false,
} );

await submitUsernameOrEmail( 'user1' );

Expand Down
4 changes: 4 additions & 0 deletions packages/data-stores/src/shared-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface WpcomClientCredentials {
client_id: string;
client_secret: string;
}
10 changes: 9 additions & 1 deletion packages/data-stores/src/site/controls.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
/**
* External dependencies
*/
import wpcomRequest, { requestAllBlogsAccess } from 'wpcom-proxy-request';

/**
* Internal dependencies
*/
import { wpcomRequest, WpcomClientCredentials } from '../utils';
import { CreateSiteAction } from './types';
import { WpcomClientCredentials } from '../shared-types';

export default function createControls( clientCreds: WpcomClientCredentials ) {
requestAllBlogsAccess().catch( () => {
throw new Error( 'Could not get all blog access.' );
} );
return {
CREATE_SITE: async ( action: CreateSiteAction ) => {
const { authToken, ...providedParams } = action.params;
Expand Down
2 changes: 1 addition & 1 deletion packages/data-stores/src/site/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import * as actions from './actions';
import * as selectors from './selectors';
import createControls from './controls';
import { DispatchFromMap, SelectFromMap } from '../mapped-types';
import { WpcomClientCredentials } from '../utils';
import { WpcomClientCredentials } from '../shared-types';

export * from './types';
export { State };
Expand Down
10 changes: 9 additions & 1 deletion packages/data-stores/src/user/controls.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
/**
* External dependencies
*/
import wpcomRequest, { requestAllBlogsAccess } from 'wpcom-proxy-request';

/**
* Internal dependencies
*/
import { wpcomRequest, WpcomClientCredentials } from '../utils';
import { CreateAccountAction } from './types';
import { WpcomClientCredentials } from '../shared-types';

export default function createControls( clientCreds: WpcomClientCredentials ) {
requestAllBlogsAccess().catch( () => {
throw new Error( 'Could not get all blog access.' );
} );
return {
CREATE_ACCOUNT: async ( action: CreateAccountAction ) => {
const defaultParams = {
Expand Down
2 changes: 1 addition & 1 deletion packages/data-stores/src/user/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import * as resolvers from './resolvers';
import * as selectors from './selectors';
import createControls from './controls';
import { DispatchFromMap, SelectFromMap } from '../mapped-types';
import { WpcomClientCredentials } from '../utils';
import { WpcomClientCredentials } from '../shared-types';

export * from './types';
export { State };
Expand Down
1 change: 0 additions & 1 deletion packages/data-stores/src/utils/index.ts

This file was deleted.

47 changes: 0 additions & 47 deletions packages/data-stores/src/utils/wpcom-wrapper.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/data-stores/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@
"incremental": true,
"tsBuildInfoFile": "../../.tsc-cache/data-stores"
},
"files": [ "./src/index.ts", "./global.d.ts" ],
"files": [ "./src/index.ts" ],
"exclude": [ "**/docs/*", "**/test/*" ]
}
4 changes: 4 additions & 0 deletions packages/wpcom-proxy-request/History.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# 6.0.0 / TBD

- Breaking: Return Promise (rather than `XMLHttpRequest` instance) if no callback argument is provided.
- In practice, most people have probably been using the callback rather than the returned `XMLHttpRequest` instance, so this shouldn't be a breaking change for most.
- Add `requestAllBlogsAccess()`.
- Add a few type definitions.
- Move the published `build/` folder to `dist/` to align with other Calypso packages
- Upgrade dependency 'debug' to 4.1.1
- Remove `component-event` dependency, use `addEventListener`/`removeEventListener` directly
Expand Down
2 changes: 2 additions & 0 deletions packages/wpcom-proxy-request/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@
},
"files": [
"dist",
"types",
"History.md",
"README.md"
],
"types": "types",
"scripts": {
"clean": "npx rimraf dist",
"prepublish": "npm run clean",
Expand Down
36 changes: 35 additions & 1 deletion packages/wpcom-proxy-request/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ debug( 'using "origin": %o', origin );
* @param {Function} [fn] - callback response
* @returns {window.XMLHttpRequest} XMLHttpRequest instance
*/
const request = ( originalParams, fn ) => {
const makeRequest = ( originalParams, fn ) => {
const params = Object.assign( {}, originalParams );

debug( 'request(%o)', params );
Expand Down Expand Up @@ -170,6 +170,40 @@ const request = ( originalParams, fn ) => {
return xhr;
};

/**
* Performs a "proxied REST API request". This happens by calling
* `iframe.postMessage()` on the proxy iframe instance, which from there
* takes care of WordPress.com user authentication (via the currently
* logged-in user's cookies).
*
* If no function is specified as second parameter, a promise is returned.
*
* @param {object} originalParams - request parameters
* @param {Function} [fn] - callback response
* @returns {window.XMLHttpRequest|Promise} XMLHttpRequest instance or Promise
*/
const request = ( originalParams, fn ) => {
// if callback is provided, behave traditionally
if ( 'function' === typeof fn ) {
// request method
return makeRequest( originalParams, fn );
}

// but if not, return a Promise
return new Promise( ( res, rej ) => {
makeRequest( originalParams, ( err, response ) => {
err ? rej( err ) : res( response );
} );
} );
};

/**
* Set proxy to "access all users' blogs" mode.
*/
export function requestAllBlogsAccess() {
return request( { metaAPI: { accessAllUsersBlogs: true } } );
}

/**
* Calls the `postMessage()` function on the <iframe>.
*
Expand Down
25 changes: 25 additions & 0 deletions packages/wpcom-proxy-request/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* TypeScript type definitions for wpcom-proxy-request
*
* @todo Migrate `src/index.js` to TypeScript, incorporate these type definitions.
* (Needs changes to the build chain, see other packages in the monorepo
* for inspiration, e.g. `@automattic/data-stores`.)
*/

export interface WpcomRequestParams {
path?: string;
method?: string;
apiVersion?: string;
body?: object;
token?: string;
metaAPI?: {
accessAllUsersBlogs?: boolean;
};
}

export function reloadProxy(): void;

export function requestAllBlogsAccess(): ReturnType< typeof request >;

export default function request( params: WpcomRequestParams, callback: Function ): XMLHttpRequest;
export default function request< T >( params: WpcomRequestParams ): Promise< T >;

0 comments on commit af0d7ff

Please sign in to comment.