bellini/ts_api/api.classes.belliniclient.ts

59 lines
1.7 KiB
TypeScript

import * as plugins from './api.plugins.js';
export interface IBelliniClientOptions {
publicationName?: string;
smartstatePart?: plugins.smartstate.StatePart<any, IBelliniClientState>;
apiEndpoint?: string;
}
export interface IBelliniClientState {
articles: plugins.belliniInterfaces.IBelliniArticle[];
}
export class BelliniClient {
public smartstatePart: plugins.smartstate.StatePart<any, IBelliniClientState>;
public options: IBelliniClientOptions;
constructor(optionsArg: IBelliniClientOptions) {
this.options = optionsArg;
this.init();
}
public initPromise: Promise<void>;
public async init() {
if (this.initPromise) {
return this.initPromise;
}
const deferred = plugins.smartpromise.defer<void>();
this.initPromise = deferred.promise;
if (this.options.smartstatePart) {
this.smartstatePart = this.options.smartstatePart;
} else {
const smartstate = new plugins.smartstate.Smartstate();
this.smartstatePart = await smartstate.getStatePart<IBelliniClientState>('bellini', {} as any);
}
await this.smartstatePart.setState({
articles: [],
});
deferred.resolve();
}
public async fetchArticles() {
await this.init();
const getArticles =
new plugins.typedrequest.TypedRequest<plugins.belliniInterfaces.IRequest_Any_Bellini_GetArticles>(
this.options.apiEndpoint,
'getArticles',
);
const response = await getArticles.fire({
from: Date.now() - 1000000000,
to: Date.now(),
publicationName: this.options.publicationName,
});
this.smartstatePart.setState({
articles: response.articles,
});
return response.articles;
}
}