import { Subject } from 'rxjs'; import { first } from 'rxjs/operators'; import { initialRequestState, IRequestState, IRequestStoreOptions, IRxRequestStoreParams, IVariablesObservable, IVariablesSubjectType, RxRequestStore } from "./RxRequestStore"; import { CustomError } from "@proscom/ui-utils"; export interface IRequestStoreParams extends IRxRequestStoreParams {} export class RequestStoreReactivityError extends CustomError { } export class RequestStore< Vars = any, Data = any, Options extends IRequestStoreOptions = any > extends RxRequestStore { variables$ = new Subject>(); isReactive: boolean = false; constructor({ initialData = null, skipQuery = (x) => undefined, ssrId = null, updateData = (data) => data, ssrContext = null, variables$ }: IRequestStoreParams = {}) { super({ initialData, skipQuery, ssrId, updateData, ssrContext, variables$ }); this.isReactive = !!variables$; if (!variables$) { this.variables$$.next(this.variables$); } } setVariables$(variables$: IVariablesObservable | null) { if (variables$) { super.setVariables$(variables$); this.isReactive = true; } else { super.setVariables$(this.variables$); this.isReactive = false; } } async loadData( variables: Vars, options?: Options ): Promise> { if (this.isReactive) { throw new RequestStoreReactivityError('RequestStoreReactivityError: Cannot use loadData when "variables$" are supplied as an Observable'); } const promise = this.state$ .pipe( first( (state) => !state.loading && (state.loaded || state.error) && state.variables === variables ) ) .toPromise(); this.variables$.next({ variables, options: options }); this.registerSsrPromise(promise); return await promise; } /** * @deprecated Use skipQuery and change variables instead */ reset(state: Partial>) { this.state = { ...initialRequestState, ...state }; } } export type GetRequestStoreVars = Store extends RequestStore< infer Vars, any, any > ? Vars : never; export type GetRequestStoreData = Store extends RequestStore< any, infer Data, any > ? Data : never; export type GetRequestStoreOptions = Store extends RequestStore< any, any, infer Options > ? Options : never; export type GetRequestStoreState = IRequestState< GetRequestStoreVars, GetRequestStoreData >;