client-search
Version:
客户端搜索
77 lines (60 loc) • 2.01 kB
text/typescript
// tslint:disable-next-line:import-name
// import { bind } from 'helpful-decorators';
import Service from './service';
export default class Controller {
protected params: HouseListParams = {};
protected houseList: IHouseDetail[] = [];
protected hasNext: boolean = true;
protected service: Service;
protected option: IOptions;
constructor(option: IOptions) {
this.option = option;
this.service = new Service(this.fetch.bind(this));
}
protected async fetch<T>(input: string, init?: RequestInit): Promise<T> {
if (!this.option.fetch) {
throw new Error('提供 fetch polyfill');
}
if (!this.option.prefix_api) {
throw new Error('提供接口前缀');
}
let url = input;
if (!/^\w+:\/\//.test(url)) {
url = this.option.prefix_api + url;
}
if (init) {
init.headers = { ...init.headers, ['content-type']: 'application/json' };
}
const response = await this.option.fetch(url, init);
const isSuccess = (response.status >= 200 && response.status < 300) || response.status === 304;
const data = await response.json();
if (!isSuccess || data.success === false) {
return Promise.reject(data);
}
return Promise.resolve(data);
}
/**
* 读取参数查询房源列表
*
* @protected
* @param {boolean} [immediate=false] 本次查询是否直接查询
* @returns {Promise<IHouseDetail[]>}
* @memberof Controller
*/
protected async fetchHouseListWithParams(immediate: boolean = false): Promise<IHouseDetail[]> {
if (!immediate && !this.option.immediate && !this.params.beginDate && !this.params.endDate) {
return [];
}
const data = await this.service.fetchHouseList(this.params);
if (!data) {
return [];
}
if (!this.params.pageNum || this.params.pageNum <= 1) {
this.houseList = data.list;
} else {
this.houseList = [...this.houseList, ...data.list];
}
this.hasNext = data.hasNextPage;
return data.list;
}
}