UNPKG

kea-react

Version:

Componentes comunes de react

76 lines (65 loc) 3.28 kB
import httpModule = require("./http"); import { UrlParameters } from "./url"; import cookies = require("./cookies"); function urlId(url: string, id: number | string): string { return url + "/" + id; } export interface ResourceInterface<T> { Query: <TParams extends UrlParameters<keyof TParams>>(params?: TParams) => Promise<T[]>; Get: <TParams extends UrlParameters<keyof TParams>>(id: number | string, params?: TParams) => Promise<T>; Insert: <TParams extends UrlParameters<keyof TParams>>(entity: Partial<T>, params?: TParams) => Promise<number>; Update: <TParams extends UrlParameters<keyof TParams>>(id: number | string, entity: Partial<T>, params?: TParams) => Promise<void>; Delete: <TParams extends UrlParameters<keyof TParams>>(id: number | string, params?: TParams) => Promise<void>; } /**Represent a RESTful http resource */ export class Resource<T> implements ResourceInterface<T>{ /** * @param url Url del servicio * @param http Servicio de peticiones HTTP, si no se especifica se usara el servicio HTTP por default */ constructor(url: string, enableMemoize?: boolean, http?: httpModule.HttpClass) { this.http = http || httpModule.Http; this.url = url; this.enableMemoize = !!enableMemoize; } private enableMemoize: boolean; private http: httpModule.HttpClass; /**URL del recurso */ url: string; /**Query a collection of entities */ Query = async <TParams extends UrlParameters<keyof TParams>>(params?: TParams): Promise<T[]> => { if (this.enableMemoize) return cookies.cookieNetworkMemoize(this.http.Get, "resource")(this.url, params); else return await this.http.Get(this.url, params); } /**Get a single entity */ Get = async <TParams extends UrlParameters<keyof TParams>>(id: number | string, params?: TParams): Promise<T> => { const url = urlId(this.url, id); if (this.enableMemoize) return cookies.cookieNetworkMemoize(this.http.Get, "resource")(url, params); else return await this.http.Get(url, params); } /**Insert a single entity. Return the entity id */ Insert = async <TParams extends UrlParameters<keyof TParams>>(entity: Partial<T>, params?: TParams): Promise<number> => { return await this.http.Post(this.url, entity, params); } /**Update an entity */ Update = async <TParams extends UrlParameters<keyof TParams>>(id: number | string, entity: Partial<T>, params?: TParams): Promise<void> => { return await this.http.Put(urlId(this.url, id), entity, params); } /**Delete an entity */ Delete = async <TParams extends UrlParameters<keyof TParams>>(id: number | string, params?: TParams): Promise<void> => { return await this.http.Delete(urlId(this.url, id), params); } networkMemoize(): ResourceInterface<T> { return { Query: cookies.cookieNetworkMemoize(this.Query, "query_" + this.url), Get: cookies.cookieNetworkMemoize(this.Get, "get_" + this.url), Insert: this.Insert, Update: this.Update, Delete: this.Delete } } }