rxjs#map TypeScript Examples
The following examples show how to use
rxjs#map.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: base-select.ts From alauda-ui with MIT License | 6 votes |
ngAfterContentInit() {
this.customCreatedOptions$ = combineLatest([
this.values$,
(
this.contentOptions.changes as Observable<QueryList<OptionComponent<T>>>
).pipe(
startWith(this.contentOptions),
switchMap((options: QueryList<OptionComponent<T>>) =>
options.length > 0
? combineLatest(options.map(option => option.value$))
: of([] as T[]),
),
),
]).pipe(
map(([values, optionValues]) =>
values.reduce<Array<SelectFilterOption<T>>>((acc, value) => {
const included = optionValues
.map(value => this.trackFn(value))
.includes(this.trackFn(value));
if (!included) {
const label =
this.labelFn?.(value) || coerceString(this.trackFn(value));
if (label) {
acc.push({
label,
value,
});
}
}
return acc;
}, []),
),
publishRef(),
);
}
Example #2
Source File: team-details.component.ts From worktez with MIT License | 6 votes |
getTeamData() {
this.showLoader = true;
const orgDomain = this.backendService.getOrganizationDomain();
const callable = this.functions.httpsCallable("teams/getTeamData");
callable({OrganizationDomain: orgDomain, TeamId: this.teamId}).pipe(
map(actions => {
const data = actions.resultData as Team
return data;
})).subscribe({
next: (data) => {
this.team = data;
data.TeamMembers.forEach((element: any) => {
this.userService.checkAndAddToUsersUsingEmail(element);
});
this.userService.fetchUserData().subscribe(()=>{
this.teamDataReady = true;
});
this.showLoader = false
},
error: (error) => {
console.error(error);
},
complete: () => console.info("Completed getting Team Data...")
});
}
Example #3
Source File: autocomplete.component.ts From alauda-ui with MIT License | 6 votes |
ngAfterContentInit() {
this.hasVisibleSuggestion$ = this.suggestions.changes.pipe(
startWith(this.suggestions),
switchMap((suggestions: QueryList<SuggestionComponent>) =>
suggestions.length > 0
? combineLatest(suggestions.map(suggestion => suggestion.visible$))
: of([] as boolean[]),
),
map(visible => visible.some(Boolean)),
withLatestFrom(this.directive$$),
map(([hasVisibleSuggestion, directive]) => {
if (hasVisibleSuggestion && directive.defaultFirstSuggestion) {
directive.autoFocusFirstSuggestion();
}
return hasVisibleSuggestion;
}),
distinctUntilChanged(),
debounceTime(0),
tap(() => this.cdr.markForCheck()),
publishRef(),
);
this.hasContent$ = combineLatest([
this.hasVisibleSuggestion$,
this.placeholder.changes.pipe(
startWith(this.placeholder),
map(
(list: QueryList<AutocompletePlaceholderComponent>) => !!list.length,
),
),
]).pipe(
map(
([hasVisibleSuggestion, hasPlaceholder]) =>
hasVisibleSuggestion || hasPlaceholder,
),
);
}
Example #4
Source File: celer.service.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
public async getCelerLiquidityInfo(): Promise<void> {
this.celerTransitTokens = (await this.celerApiService
.getCelerLiquidityInfo()
.pipe(
map(response => {
const lpInfo = response.lp_info.filter(
item =>
CELER_SUPPORTED_BLOCKCHAINS.map(
(blockchain: BlockchainName) =>
networks.find(network => network.name === blockchain).id
).includes(item.chain.id) && this.isSupportedTransitToken(item.token.token.symbol)
);
return CELER_SUPPORTED_BLOCKCHAINS.map(blockchain => {
const blockchainId = networks.find(item => item.name === blockchain).id;
const tokens = lpInfo.filter(item => item.chain.id === blockchainId);
return { [blockchain]: tokens };
}).reduce((acc, curr) => {
return { ...acc, ...curr };
}, {});
})
)
.toPromise()) as Record<BlockchainName, LiquidityInfoItem[]>;
}
Example #5
Source File: multi-select.component.ts From alauda-ui with MIT License | 6 votes |
override ngAfterViewInit() {
super.ngAfterViewInit();
this.selectAllStatus$ = combineLatest([
this.allOptions$,
this.filterString$,
]).pipe(
switchMap(([allOptions]) =>
combineLatest([
...(allOptions ?? [])
.filter(({ visible, disabled }) => visible && !disabled)
.map(({ selected$ }) => selected$),
]),
),
map(statuses => {
const selected = statuses.filter(Boolean);
return selected.length === 0
? SelectAllStatus.Empty
: selected.length !== statuses.length
? SelectAllStatus.Indeterminate
: SelectAllStatus.Checked;
}),
startWith(SelectAllStatus.Empty),
tap(selectAllStatus => (this.selectAllStatus = selectAllStatus)),
publishRef(),
);
this.hasEnabledOptions$ = combineLatest([
this.allOptions$,
this.filterString$,
]).pipe(
map(
([allOptions]) =>
!!allOptions.filter(({ visible, disabled }) => visible && !disabled)
.length,
),
);
}
Example #6
Source File: TodoListEventsController.ts From remix-hexagonal-architecture with MIT License | 6 votes |
@Sse("/:todoListId")
async getEvents(@Param("todoListId") todoListId: string) {
const currentUser = await this.authenticator.currentUser();
const heartbeat$ = interval(30_000).pipe(
map(() => ({ type: "heartbeat", data: "_" }))
);
const updates$ = this.todoListEvents.events.pipe(
filter(
(event) =>
event.todoListId === todoListId &&
event.sessionId !== currentUser.sessionId
),
map((event) => ({ type: "update", data: event.type } as MessageEvent))
);
return merge(heartbeat$, updates$);
}
Example #7
Source File: publish-list.tsx From bext with MIT License | 6 votes |
Banner: FC<{ current: number; empty?: boolean }> = ({
current,
empty,
}) => {
const nextTime = useObservableState(
useObservable(
(input$) =>
input$.pipe(
pluckFirst,
switchMap((current) =>
timer(0, 1000).pipe(
map(() => current + REFRESH_DURATION - Date.now()),
),
),
),
[current],
),
REFRESH_DURATION,
);
return (
<Separator>
{empty ? '暂无' : ''}发布历史({' '}
{nextTime > 0 ? `${Math.floor(nextTime / 1000)} 秒后刷新` : '刷新中'})
</Separator>
);
}
Example #8
Source File: task-ecard.component.ts From worktez with MIT License | 6 votes |
ngOnInit(): void {
this.statusLabels = this.applicationSettingsService.status;
this.priorityLabels = this.applicationSettingsService.priority;
this.difficultyLabels = this.applicationSettingsService.difficulty;
this.teamMembers = this.applicationSettingsService.team.TeamMembers;
this.todayDate = this.toolsService.date();
this.time = this.toolsService.time();
this.filteredOptionsAssignee = this.assigneeName.valueChanges.pipe(
startWith(''),
map((value) => {
return this._filter(value)
}),
);
}
Example #9
Source File: celer.service.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
/**
* Transforms each element of array of arguments to string for smart-contract method call.
* @param args Array of arguments.
* @returns Prepared array of arguments.
*/
private prepareArgs(args: unknown[]): unknown[] {
return args.map(arg => {
if (Array.isArray(arg)) {
return this.prepareArgs(arg);
}
if (typeof arg === 'boolean') {
return arg;
} else {
return String(arg);
}
});
}
Example #10
Source File: filter-page.component.ts From worktez with MIT License | 6 votes |
getTeamFilters(){
const orgDomain = this.backendService.getOrganizationDomain();
this.teamName = this.startService.teamName;
const callable = this.functions.httpsCallable("filters/getFilter");
callable({OrganizationDomain: orgDomain, TeamName: this.teamName}).pipe(
map(actions => {
const data = actions.resultData as CustomFilter[]
return data;
})).subscribe({
next: (data) => {
this.filters = data;
this.filtersReady = true;
},
error: (error) => {
console.error(error);
},
complete: () => console.info("Completed getting Filter Data...")
});
}
Example #11
Source File: celer.service.ts From rubic-app with GNU General Public License v3.0 | 5 votes |
/**
* Preparing data for source swap.
* @param srcProvider Source provider data.
* @param fromBlockchain Source blockchain.
* @param fromTransitTokenAmount Transit token amount in source network.
* @param fromToken Token in.
* @param celerBridgeSlippage Celer bridge slippage.
* @returns Source swap data.
*/
private getSrcSwapObject(
srcProvider: IndexedTradeAndToAmount,
fromBlockchain: EthLikeBlockchainName,
fromTransitTokenAmount: BigNumber,
fromToken: TokenAmount,
fromSlippage: number,
bridgePair: boolean
): SwapInfoInch | SwapInfoV2 | SwapInfoV3 | SwapInfoBridge {
const dexes = this.contractsDataService.contracts[fromBlockchain];
const dexAddress = dexes.getProvider(srcProvider.providerIndex).contractAddress;
const amountOutMinimum = Web3Pure.toWei(
fromTransitTokenAmount.multipliedBy(fromSlippage),
dexes.transitToken.decimals
);
const canBridgeInSourceNetwork = bridgePair || this.isSmartRoutingTransitToken(fromToken);
if (canBridgeInSourceNetwork) {
return { srcBridgeToken: fromToken.address } as SwapInfoBridge;
}
if (dexes.isProviderOneinch(srcProvider.providerIndex)) {
const trade = srcProvider.tradeAndToAmount.trade as OneinchInstantTrade;
const [tokenIn, ...path] = trade?.path?.map(token => token.address);
const isInchNative = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' === tokenIn;
return {
dex: dexAddress,
path: [isInchNative ? WRAPPED_NATIVE[fromBlockchain] : tokenIn, path.at(-1)],
data: trade.data,
amountOutMinimum
} as SwapInfoInch;
}
if (dexes.isProviderUniV2(srcProvider.providerIndex)) {
return {
dex: dexAddress,
path: srcProvider.tradeAndToAmount.trade?.path?.map(token => token.address),
deadline: DEADLINE,
amountOutMinimum
} as SwapInfoV2;
}
if (dexes.isProviderUniV3(srcProvider.providerIndex)) {
const pathV3 = this.contractsDataService.contracts[fromBlockchain].getFirstPath(
srcProvider.providerIndex,
srcProvider.tradeAndToAmount.trade
);
return {
dex: dexAddress,
path: pathV3,
deadline: DEADLINE,
amountOutMinimum
} as SwapInfoV3;
}
}
Example #12
Source File: useTx.ts From anchor-web-app with Apache License 2.0 | 5 votes |
useTx = <TxParams, TxResult>(
sendTx: (
txParams: TxParams,
renderTxResults: Subject<TxResultRendering<TxResult>>,
txEvents: Subject<TxEvent<TxParams>>,
) => Promise<TxResult | null>,
parseTx: (txResult: NonNullable<TxResult>) => ContractReceipt,
emptyTxResult: TxResult,
): StreamReturn<TxParams, TxResultRendering<TxResult>> => {
const { txErrorReporter } = useAnchorWebapp();
// TODO: represent renderingEvents stream as txEvents.map(render) and remove the need for two subjects
const txEvents = useMemo(() => new Subject<TxEvent<TxParams>>(), []);
const renderingEvents = useMemo(
() =>
new BehaviorSubject<TxResultRendering<TxResult>>({
value: emptyTxResult,
message: 'Processing transaction...',
phase: TxStreamPhase.BROADCAST,
receipts: [],
}),
[emptyTxResult],
);
const txCallback = useCallback(
(txParams: TxParams) => {
return merge(
from(sendTx(txParams, renderingEvents, txEvents))
.pipe(
map((txResult) => {
renderingEvents.complete();
txEvents.complete();
return {
value: txResult,
phase: TxStreamPhase.SUCCEED,
receipts: Boolean(txResult)
? [txReceipt(parseTx(txResult!))]
: [],
};
}),
)
.pipe(catchTxError<TxResult | null>({ txErrorReporter })),
renderingEvents,
);
},
[sendTx, parseTx, txErrorReporter, renderingEvents, txEvents],
);
const [fetch, result] = useStream(txCallback);
const txStreamResult = useMemo(
() =>
[fetch, result] as StreamReturn<TxParams, TxResultRendering<TxResult>>,
[fetch, result],
);
return txStreamResult;
}
Example #13
Source File: publish-list.tsx From bext with MIT License | 5 votes |
PublishList: FC = () => (
<div className="py-3">
{useObservableState(
useObservable(() =>
user$.pipe(
switchMap(({ status, user }) => {
switch (status) {
case 'loading':
return of(<Spinner />);
case 'complete':
const octokit = octokit$.getValue()!;
return timer(0, REFRESH_DURATION).pipe(
switchMap(() =>
from(
octokit.paginate(octokit.search.issuesAndPullRequests, {
q: `is:pr author:${user?.login} repo:${packageJson.metaRepository.owner}/${packageJson.metaRepository.repo}`,
sort: 'created',
order: 'desc',
}),
).pipe(
map((items) => (
<>
<Banner current={Date.now()} empty={!items.length} />
{items.length ? (
<List
items={items}
onRenderCell={(item) => <PrItem item={item!} />}
/>
) : null}
</>
)),
retry(2),
catchError(() =>
of(<div className="text-center">出错了...</div>),
),
),
),
);
default:
return of(
<div className="text-center">
<LoginLink /> 后查看发布历史
</div>,
);
}
}),
startWith(<Spinner />),
),
),
) || null}
</div>
)
Example #14
Source File: celer.service.ts From rubic-app with GNU General Public License v3.0 | 5 votes |
/**
* Preparing data for destination swap.
* @param dstProvider Target provider data.
* @param toBlockchain Target blockchain.
* @param estimatedTokenAmount Estimated amount out.
* @param toToken Token out.
* @returns Destination swap data.
*/
private getDstSwapObject(
dstProvider: IndexedTradeAndToAmount,
toBlockchain: EthLikeBlockchainName,
estimatedTokenAmount: BigNumber,
toToken: TokenAmount,
bridgePair: boolean
): SwapInfoDest {
const swapVersion = this.getCelerSwapVersion(toBlockchain, dstProvider.providerIndex);
const dexes = this.contractsDataService.contracts[toBlockchain];
const dexAddress = dexes.getProvider(dstProvider.providerIndex).contractAddress;
const amountOutMinimum = this.getAmountWithUsersSlippage(estimatedTokenAmount);
const canBridgeInTargetNetwork = bridgePair || this.isSmartRoutingTransitToken(toToken);
const dstSwap: SwapInfoDest = {
dex: dexAddress,
integrator: EMPTY_ADDRESS,
version: swapVersion,
path: [EMPTY_ADDRESS],
pathV3: EMPTY_DATA,
deadline: DEADLINE,
amountOutMinimum: Web3Pure.toWei(amountOutMinimum, toToken.decimals)
};
if (canBridgeInTargetNetwork) {
return {
dex: EMPTY_ADDRESS,
integrator: EMPTY_ADDRESS,
version: SwapVersion.BRIDGE,
path: [toToken.address],
pathV3: EMPTY_DATA,
deadline: 0,
amountOutMinimum: '0'
};
}
if (dexes.isProviderUniV2(dstProvider.providerIndex)) {
// TODO change to getSecondPath
dstSwap.path = dstProvider.tradeAndToAmount.trade.path.map(token => token.address);
}
if (dexes.isProviderUniV3(dstProvider.providerIndex)) {
const pathV3 = this.contractsDataService.contracts[toBlockchain].getFirstPath(
dstProvider.providerIndex,
dstProvider.tradeAndToAmount.trade
);
dstSwap.pathV3 = pathV3;
}
return dstSwap;
}
Example #15
Source File: store.test.ts From foca with MIT License | 5 votes |
it('rxjs can observe store', () => {
store.init();
const observable = from(store);
const results: any[] = [];
const model = defineModel('rxjs', {
initialState: {
foo: 0,
bar: 0,
},
actions: {
foo(state) {
state.foo += 1;
},
bar(state) {
state.bar += 1;
},
},
});
const sub = observable
.pipe(
map((state) => {
return { fromRx: true, ...state[model.name] };
}),
)
.subscribe((state) => {
results.push(state);
});
model.foo();
model.foo();
sub.unsubscribe();
model.bar();
expect(results).toEqual(
expect.arrayContaining([
{ foo: 0, bar: 0, fromRx: true },
{ foo: 1, bar: 0, fromRx: true },
{ foo: 2, bar: 0, fromRx: true },
]),
);
});
Example #16
Source File: state.ts From platyplus with MIT License | 5 votes |
addStateToDatabasePrototype = (proto: Database) => {
proto.isConfigReady$ = new Observable((subscriber) => {
readyTables.subscribe((tables) =>
subscriber.next(CONFIG_TABLES.every((name) => tables.includes(name)))
)
}).pipe(distinctUntilChanged<boolean>())
proto.isReady$ = new Observable((subscriber) => {
readyTables.subscribe((tables) =>
subscriber.next(PLATYPLUS_TABLES.every((name) => tables.includes(name)))
)
}).pipe(distinctUntilChanged<boolean>())
proto.jwt$ = new BehaviorSubject<string | null>(null)
proto.isAdmin$ = new BehaviorSubject<boolean>(false)
proto.isAuthenticated$ = new BehaviorSubject<boolean>(false)
proto.setAuthStatus = (
status: boolean | null,
newJwt: string | null,
admin: boolean
) => {
debug('db', 'setAuthStatus', status, !!newJwt)
if (typeof status === 'boolean') {
proto.isAuthenticated$.next(status)
proto.jwt$.next(newJwt)
proto.isAdmin$.next(status ? admin : false)
}
}
proto.isConnected$ = merge(
of(null),
fromEvent(window, 'online'),
fromEvent(window, 'offline')
).pipe(map(() => navigator.onLine))
proto.stop = async function (this: Database) {
this.setAuthStatus(false, null, false)
readyTables.next([])
for (const collection of Object.values(this.collections)) {
await collection.destroy()
}
}
}
Example #17
Source File: watch-content-exist.ts From alauda-ui with MIT License | 5 votes |
export function watchContentExist(queryList: QueryList<unknown>) {
return queryList.changes.pipe(
startWith(queryList),
map((list: QueryList<unknown>) => !!list.length),
publishRef(),
);
}
Example #18
Source File: plugin.ts From platyplus with MIT License | 5 votes |
options: SearchOptions<{ systemFields: boolean; deleted: boolean }> = {
getField: (value, key: string | number, options) => {
if (!options.systemFields && typeof key === 'string' && key.startsWith('_'))
return of(null)
if (isRxDocument(value)) {
const document: RxDocument = value
// TODO combineLatest as per getIdentity
return document.deleted$.pipe(
switchMap((deleted) => {
if (!options.deleted && deleted) return of(null)
if (typeof key === 'number') return of(value[key] ?? null)
const definition = value.collection.schema.jsonSchema.properties[key]
if (definition) {
if (definition.ref) {
return document
.get$(key)
.pipe(switchMap(() => document.populate(key)))
} else {
return document.get$(key)
}
} else return of(value[key] ?? null)
})
)
} else return of(value[key] ?? null)
},
getIdentity: (value, { systemFields }) => {
if (isRxDocument(value)) {
const document: RxDocument = value
return combineLatest([document.deleted$, document.$]).pipe(
map(([deleted, value]) => {
if (!options.deleted && deleted) return of(null)
else {
if (systemFields) return value
else return trimSystemFields(value)
}
})
)
} else return of(value)
},
circularData: true,
systemFields: false,
deleted: false
}
Example #19
Source File: property.spec.ts From frp-ts with MIT License | 5 votes |
testObservable: Functor1<TEST_OBSERVABLE_URI> = {
URI: TEST_OBSERVABLE_URI,
map: (fa, f) => fa.pipe(map(f)),
}
Example #20
Source File: tooltip.component.ts From alauda-ui with MIT License | 5 votes |
setupInputs(inputs: {
inputContent$: Observable<string | TemplateRef<any>>;
inputType$: Observable<TooltipType>;
inputPosition$: Observable<string>;
inputClass$: Observable<string>;
inputContext$: Observable<any>;
}) {
Object.assign(this, inputs);
this.text$ = this.inputContent$.pipe(
map(val => {
if (typeof val === 'string') {
return val;
}
return '';
}),
publishRef(),
);
this.template$ = this.inputContent$.pipe(
map(val => {
if (typeof val !== 'string') {
return val;
}
return null;
}),
publishRef(),
);
this.class$ = combineLatest([
this.inputPosition$.pipe(startWith('top')),
this.inputType$.pipe(startWith(TooltipType.Default)),
this.inputClass$.pipe(startWith('')),
]).pipe(
map(([inputPosition, inputType, inputClass]) => {
const b = this.bem.block();
const dir = inputPosition.split(' ')[0];
return inputType === TooltipType.Plain
? `${b}--${dir} ${inputClass}`
: `${b} ${b}--${inputType} ${b}--${dir} ${inputClass}`;
}),
publishRef(),
);
this.context$ = this.inputContext$.pipe(publishRef());
}
Example #21
Source File: curse-migration-dialog.component.ts From WowUp with GNU General Public License v3.0 | 5 votes |
public readonly autoIncomplete$ = this.autoComplete$.pipe(map((complete) => !complete));
Example #22
Source File: github-login.tsx From bext with MIT License | 4 votes |
GithubLogin: FC = () => {
const [{ code }] = useUrlState({ code: undefined });
const historyReplace = useHistoryReplace();
const { notify, dismissNotification } = useNotifications();
useRequest(
async () => {
const id = uniqueId('login-loading');
notify({
id,
status: 'loading',
message: '登录中',
dismissAfter: 0,
dismissible: false,
});
const response = await fetch(`/api/gh/login?code=${code}`);
const data = await response.json();
if (
response.ok &&
data.code === 200 &&
typeof data?.data?.access_token === 'string'
) {
accessToken$.next(data.data.access_token);
notify({
status: 'success',
message: '登录成功',
});
historyReplace(location.pathname);
trackEvent(Events.ghLoginSuccess);
} else {
notify({
status: 'error',
message:
data?.data?.error_description || data?.msg || response.statusText,
});
}
dismissNotification(id);
},
{
ready: !!code,
refreshDeps: [code],
onError: () => notify({ status: 'error', message: '登录失败' }),
},
);
const el = useObservableState(
useObservable(() =>
octokit$.pipe(
switchMap((octokit) =>
octokit
? user$.pipe(
map(({ status, user }) => {
switch (status) {
case 'complete':
return (
<div className="flex justify-between">
<Persona
imageUrl={user?.avatar_url}
text={user?.name || user?.login}
secondaryText={user?.bio || '暂无签名'}
/>
<Link onClick={() => accessToken$.next(undefined)}>
退出
</Link>
</div>
);
case 'loading':
return '获取用户信息...';
default:
return (
<>
发布、更新脚本请先
<LoginLink />
</>
);
}
}),
startWith('获取用户信息...'),
)
: of(
<>
发布、更新脚本请先
<LoginLink />
</>,
),
),
),
),
null,
);
return (
<>
<Title>Github</Title>
{el}
</>
);
}
Example #23
Source File: replicator.ts From platyplus with MIT License | 4 votes |
createReplicator = async <T>(
collection: RxCollection<T, unknown> & { replicator: Replicator<T> },
options: ReplicatorOptions<T>
): Promise<Replicator<T>> => {
const db = collection.database as unknown as Database
const headers = () =>
createHeaders(options.role, db.jwt$.getValue(), options.substituteRole)
const resetWs = () => {
if (wsClient) {
wsClient.unsubscribeAll()
wsClient.close()
}
}
let state: RxGraphQLReplicationState<T> | undefined
let wsClient: SubscriptionClient | undefined
let jwtSubscription: Subscription | undefined
let errorSubscription: Subscription | undefined
const setupGraphQLReplication = async () => {
const replicationState = collection.syncGraphQL({
url: options.url,
headers: headers(),
pull: {
queryBuilder: options.pull.queryBuilder,
modifier: options.pull.modifier
},
push: {
batchSize: options.batchSize || DEFAULT_BATCH_SIZE,
queryBuilder: options.push?.queryBuilder,
modifier: options.push?.modifier
},
live: true,
liveInterval: 1000 * 60 * 10, // 10 minutes
deletedFlag: DELETED_COLUMN,
waitForLeadership: true // defaults to true
})
// replicationState.initialReplicationComplete$.subscribe((active) =>
// active
// ? setReplicationReady(collection.name)
// : setReplicationBusy(collection.name)
// )
replicationState.canceled$.subscribe(() => {
debug(collection.name, `replication cancelled`)
jwtSubscription?.unsubscribe()
errorSubscription?.unsubscribe()
startOption?.()
resetWs()
})
return replicationState
}
const initWsSubscription = () => {
debug(collection.name, `initGraphQLSubscription`)
resetWs()
wsClient = new SubscriptionClient(httpUrlToWebSockeUrl(options.url), {
reconnect: true,
connectionParams: {
headers: headers()
},
timeout: 1000 * 60,
reconnectionAttempts: 10000,
inactivityTimeout: 10 * 1000,
lazy: true
})
const request = wsClient.request({
query: options.subscription.query,
variables: options.subscription.variables?.()
})
request.subscribe({
next: ({ data, ...rest }) => {
if (data) {
const contents = Object.values(data)[0]
debug(collection.name, `WS request emitted`, contents)
options.onWsReceive?.(contents)
state?.run()
} else {
debug(collection.name, `WS request emitted, but no data`, rest)
}
},
error: (error) => {
warn(collection.name, `WS request error`, error)
}
})
wsClient.onReconnected(() => {
info(collection.name, `WS reconnected`)
})
wsClient.onConnected(() => {
debug(collection.name, `WS connected`)
})
wsClient.onDisconnected(() => {
debug(collection.name, `WS disconnected`)
})
wsClient.onReconnecting(() => {
info(collection.name, `WS reconnecting`)
})
wsClient.onError((err) => {
info(collection.name, ` WS error`, err)
})
}
let startOption: undefined | (() => void)
const start = async (): Promise<void> => {
state = await setupGraphQLReplication()
startOption = options.onStart?.()
errorSubscription = state.error$.subscribe((data) => {
warn(collection.name, `replication error`, data)
})
jwtSubscription = db.jwt$.subscribe((jwt) => {
debug(collection.name, `new jwt received`)
if (jwt) {
state.setHeaders(headers())
initWsSubscription()
} else debug(collection.name, `new jwt received was null`)
})
state.awaitInitialReplication().then(() => {
debug(collection.name, `awaitInitialReplication OK`)
})
}
const stop = async (): Promise<void> => {
debug(collection.name, `stop replication`)
await state?.cancel()
}
const destroy = async (): Promise<void> => {
// TODO check if it is really solved: https://gitter.im/pubkey/rxdb?at=61391ec763dca818914c246e
// this should be part of _prepare() in https://github.com/pubkey/rxdb/blob/master/src/plugins/replication-graphql/index.ts
await setLastPullDocument(state.collection, state.endpointHash, null)
await setLastPushSequence(state.collection, state.endpointHash, 0)
await stop()
}
combineLatest([db.isConnected$, db.isAuthenticated$])
.pipe(
map(([connected, authenticated]) => connected && authenticated),
distinctUntilChanged<boolean>()
)
.subscribe(async (ok) => {
debug(collection.name, `auth/connection status change`, ok)
if (ok) await start()
else await stop()
})
collection.replicator = { start, stop, destroy, state }
return collection.replicator
}
Example #24
Source File: profile.component.ts From worktez with MIT License | 4 votes |
readUser() {
if(this.authService.userAppSetting.Username == this.username){
this.displayName = this.authService.userAppSetting.displayName;
this.email = this.authService.userAppSetting.email;
this.uid = this.authService.userAppSetting.uid;
this.aboutMe = this.authService.userAppSetting.AboutMe;
this.appTheme = this.authService.userAppSetting.AppTheme;
this.photoURL = this.authService.userAppSetting.photoURL;
this.phoneNumber = this.authService.userAppSetting.phoneNumber;
this.linkedInProfile = this.authService.userAppSetting.LinkedInProfile;
this.githubProfile = this.authService.userAppSetting.GithubProfile;
this.dateOfJoining = this.authService.userAppSetting.DateOfJoining;
this.skills = this.authService.userAppSetting.Skills;
this.website = this.authService.userAppSetting.Website;
if (this.website.includes("https://") == false) {
this.website = "https://" + this.website;
}
this.readUserEducation(this.uid);
this.readUserExperience(this.uid);
this.readUserProject(this.uid);
this.readUserProfilePic(this.uid);
this.sameUser = true;
}
else{
const data = this.userService.getUserNameData(this.username);
if(data != null) {
this.displayName = data.displayName;
this.email = data.email;
this.uid = data.uid;
this.aboutMe = data.AboutMe;
this.photoURL = data.photoURL;
this.phoneNumber = data.phoneNumber;
this.linkedInProfile = data.LinkedInProfile;
this.githubProfile = data.LinkedInProfile;
this.dateOfJoining = data.DateOfJoining;
this.skills = data.Skills;
this.website = data.Website;
if (this.website.includes("https://") == false) {
this.website = "https://" + this.website;
}
this.readUserEducation(this.uid);
this.readUserExperience(this.uid);
this.readUserProject(this.uid);
this.readUserProfilePic(this.uid);
this.sameUser = false;
}
else{
const callable = this.functions.httpsCallable("users/getUserByUsername");
callable({Username : this.username}).pipe(map(res => {
const data = res.userData as UserAppSetting;
return { ...data }
})).subscribe({
next: (data:UserAppSetting) => {
console.log(data);
this.displayName = data.displayName;
this.email = data.email;
this.uid = data.uid;
this.aboutMe = data.AboutMe;
this.photoURL = data.photoURL;
this.phoneNumber = data.phoneNumber;
this.linkedInProfile = data.LinkedInProfile;
this.githubProfile = data.LinkedInProfile;
this.dateOfJoining = data.DateOfJoining;
this.skills = data.Skills;
this.website = data.Website;
if (this.website.includes("https://") == false) {
this.website = "https://" + this.website;
}
this.readUserEducation(this.uid);
this.readUserExperience(this.uid);
this.readUserProject(this.uid);
this.sameUser = false;
},
error: (error) => {
console.error(error);
},
complete: () => console.info('Getting Task successful')
});
}
}
}