Skip to content

Commit

Permalink
feat: unify promise utils [wip]
Browse files Browse the repository at this point in the history
  • Loading branch information
mroz22 committed Dec 22, 2021
1 parent beac20d commit 1d8e21f
Show file tree
Hide file tree
Showing 18 changed files with 31 additions and 68 deletions.
1 change: 1 addition & 0 deletions packages/blockchain-link/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"devDependencies": {
"@babel/register": "^7.13.14",
"@babel/runtime": "^7.13.10",
"@trezor/utils": "*",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.1",
"eslint-config-airbnb-base": "^14.2.1",
Expand Down
4 changes: 3 additions & 1 deletion packages/blockchain-link/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { EventEmitter } from 'events';
import { createDeferred } from '@trezor/utils';
import { CustomError } from './constants/errors';
import { MESSAGES, RESPONSES } from './constants';
import { create as createDeferred, Deferred } from './utils/deferred';
import { BlockchainSettings } from './types';
import * as ResponseTypes from './types/responses';
import * as MessageTypes from './types/messages';
import { Events } from './types/events';

import type { Deferred } from '@trezor/utils';

const workerWrapper = (factory: BlockchainSettings['worker']): Worker => {
if (typeof factory === 'function') return factory();
if (typeof factory === 'string' && typeof Worker !== 'undefined') return new Worker(factory);
Expand Down
4 changes: 3 additions & 1 deletion packages/blockchain-link/src/workers/blockbook/websocket.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import WebSocket from 'ws';
import { EventEmitter } from 'events';
import { createDeferred } from '@trezor/utils';

import { CustomError } from '../../constants/errors';
import { create as createDeferred, Deferred } from '../../utils/deferred';
import {
BlockNotification,
AddressNotification,
Expand All @@ -18,6 +19,7 @@ import {
EstimateFeeParams,
AccountBalanceHistoryParams,
} from '../../types/params';
import type {Deferred} from '@trezor/utils';

const NOT_INITIALIZED = new CustomError('websocket_not_initialized');

Expand Down
5 changes: 4 additions & 1 deletion packages/blockchain-link/src/workers/blockfrost/websocket.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import WebSocket from 'ws';
import { EventEmitter } from 'events';
import { createDeferred } from '@trezor/utils';

import { CustomError } from '../../constants/errors';
import { create as createDeferred, Deferred } from '../../utils/deferred';
import { Send, BlockContent } from '../../types/blockfrost';
import { AccountInfoParams, EstimateFeeParams } from '../../types/params';

import type { Deferred } from '@trezor/utils';

const NOT_INITIALIZED = new CustomError('websocket_not_initialized');

interface Subscription {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,10 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const WebSocket = require('ws');
const { EventEmitter } = require('events');
const { createDeferred } = require('@trezor/utils');

const NOT_INITIALIZED = new Error('websocket_not_initialized');

const createDeferred = id => {
let localResolve = t => () => {};
let localReject = e => () => {};

const promise = new Promise((resolve, reject) => {
localResolve = resolve;
localReject = reject;
});

return {
id,
resolve: localResolve,
reject: localReject,
promise,
};
};

// Making the timeout high because the controller in trezor-user-env
// must synchronously run actions on emulator and they may take a long time
// (for example in case of Shamir backup)
Expand Down
4 changes: 2 additions & 2 deletions packages/suite/src/actions/suite/metadataActions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import TrezorConnect from 'trezor-connect';
import { createDeferred } from '@trezor/utils';
import { METADATA } from '@suite-actions/constants';
import { createDeferred } from '@suite-utils/deferred';
import { Dispatch, GetState } from '@suite-types';
import {
MetadataProviderType,
Expand Down Expand Up @@ -216,7 +216,7 @@ export const disableMetadata = () => (dispatch: Dispatch) => {
};

export const initProvider = () => (dispatch: Dispatch) => {
const decision = createDeferred<boolean>();
const decision = createDeferred<boolean>(-1);
dispatch(modalActions.openModal({ type: 'metadata-provider', decision }));
return decision.promise;
};
Expand Down
4 changes: 2 additions & 2 deletions packages/suite/src/actions/suite/modalActions.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import TrezorConnect, { UI } from 'trezor-connect';
import { createDeferred, Deferred, DeferredResponse } from '@trezor/utils';
import { MODAL, SUITE } from '@suite-actions/constants';
import { Route, Dispatch, GetState, TrezorDevice } from '@suite-types';
import { Account, WalletAccountTransaction } from '@wallet-types';
import { createDeferred, Deferred, DeferredResponse } from '@suite-utils/deferred';

export type UserContextPayload =
| {
Expand Down Expand Up @@ -213,7 +213,7 @@ type DeferredPayload<T extends DeferredModals['type']> = { type: T } & DeferredR
export const openDeferredModal =
<T extends DeferredModals['type']>(payload: DeferredPayload<T>) =>
(dispatch: Dispatch) => {
const dfd = createDeferred<DeferredResponse<DeferredModal<T>['decision']>>();
const dfd = createDeferred<DeferredResponse<DeferredModal<T>['decision']>>(-1);
dispatch({
type: MODAL.OPEN_USER_CONTEXT,
payload: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Button, Icon, variables, Checkbox, H3 } from '@trezor/components';
import React, { useState } from 'react';
import { Translation, Modal } from '@suite-components';
import styled, { css } from 'styled-components';
import { Deferred } from '@suite-utils/deferred';
import { Deferred } from '@trezor/utils';

const Text = styled.div<{ isLast?: boolean; isFirst?: boolean }>`
padding: 20px 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Button, Icon, variables, Checkbox } from '@trezor/components';
import React, { useState } from 'react';
import { Translation, Modal } from '@suite-components';
import styled, { css } from 'styled-components';
import { Deferred } from '@suite-utils/deferred';
import { Deferred } from '@trezor/utils';

const Text = styled.div<{ isLast?: boolean; isFirst?: boolean }>`
padding: 20px 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Button, Icon, variables, Checkbox, H3 } from '@trezor/components';
import React, { useState } from 'react';
import { Translation, Modal } from '@suite-components';
import styled, { css } from 'styled-components';
import { Deferred } from '@suite-utils/deferred';
import { Deferred } from '@trezor/utils';

const Text = styled.div<{ isLast?: boolean; isFirst?: boolean }>`
padding: 20px 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Button, Icon, variables, Checkbox, H3 } from '@trezor/components';
import React, { useState } from 'react';
import { Translation, Modal } from '@suite-components';
import styled, { css } from 'styled-components';
import { Deferred } from '@suite-utils/deferred';
import { Deferred } from '@trezor/utils';

const Text = styled.div<{ isLast?: boolean; isFirst?: boolean }>`
padding: 20px 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { P, Button, variables } from '@trezor/components';
import { Translation, Modal } from '@suite-components';
import { useActions } from '@suite-hooks';
import * as metadataActions from '@suite-actions/metadataActions';
import { Deferred } from '@suite-utils/deferred';
import { Deferred } from '@trezor/utils';
import { MetadataProviderType } from '@suite-types/metadata';
import { isEnabled } from '@suite-utils/features';

Expand Down
4 changes: 2 additions & 2 deletions packages/suite/src/hooks/suite/useAsyncDebounce.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useRef } from 'react';
import { createDeferred } from '@suite-utils/deferred';
import { createDeferred } from '@trezor/utils';

type TimeoutType = ReturnType<typeof setTimeout>; // resolves to Timeout type in react-native, number otherwise

Expand All @@ -14,7 +14,7 @@ export const useAsyncDebounce = () => {
// clear previous timeout
if (timeout.current) clearTimeout(timeout.current);
// set new timeout
const timeoutDfd = createDeferred();
const timeoutDfd = createDeferred(-1);
// @ts-ignore needed with @types/react-native 0.63.45, could be a bug
const newTimeout = setTimeout(timeoutDfd.resolve, 300);
// @ts-ignore needed with @types/react-native 0.63.45, could be a bug
Expand Down
4 changes: 2 additions & 2 deletions packages/suite/src/reducers/wallet/discoveryReducer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import produce from 'immer';
import { DISCOVERY } from '@wallet-actions/constants';
import { STORAGE } from '@suite-actions/constants';
import { Deferred, createDeferred } from '@suite-utils/deferred';
import { Deferred, createDeferred } from '@trezor/utils';
import { ObjectValues } from '@suite/types/utils';
import { Action as SuiteAction } from '@suite-types';
import { WalletAction, Network } from '@wallet-types';
Expand Down Expand Up @@ -46,7 +46,7 @@ const start = (draft: State, payload: PartialDiscovery) => {
draft[index] = {
...draft[index],
...payload,
running: createDeferred(),
running: createDeferred(-1),
};
}
};
Expand Down
28 changes: 0 additions & 28 deletions packages/suite/src/utils/suite/deferred.ts

This file was deleted.

4 changes: 2 additions & 2 deletions packages/suite/src/utils/suite/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { getPrefixedURL } from '@suite-utils/router';
import { METADATA } from '@suite-actions/constants';
import { Deferred, createDeferred } from '@suite-utils/deferred';
import { Deferred, createDeferred } from '@trezor/utils';
import { urlHashParams, urlSearchParams } from '@suite-utils/metadata';

/**
Expand Down Expand Up @@ -142,7 +142,7 @@ const getWebHandlerInstance = (
*/
export const extractCredentialsFromAuthorizationFlow = (url: string) => {
const originalParams = urlHashParams(url);
const dfd: Deferred<Credentials> = createDeferred();
const dfd: Deferred<Credentials> = createDeferred(-1);

const { desktopApi } = window;

Expand Down
2 changes: 1 addition & 1 deletion packages/utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const todo = () => {};
export * from './promise';
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
export function create<T>(id: number | string): Deferred<T> {
// intentionally ignore below lines in test coverage, they will be overridden in promise creation
/* istanbul ignore next */
export function createDeferred<T>(id: number | string): Deferred<T> {
let localResolve: (t: T) => void = () => {};
/* istanbul ignore next */
let localReject: (e?: Error) => void = () => {};

const promise: Promise<T> = new Promise((resolve, reject) => {
Expand All @@ -24,3 +21,5 @@ export interface Deferred<T> {
resolve: (t: T) => void;
reject: (e: Error) => void;
}
// unwrap promise response from Deferred
export type DeferredResponse<D> = D extends Deferred<infer R> ? R : never;

0 comments on commit 1d8e21f

Please sign in to comment.