import { View } from '../utils/View'; import { FetchOptions, Gateway } from '../types/Gateway'; import { Repository } from '../types/Repository'; import { Json, JsonValue, toJson } from '../types/Json'; import { PageList } from '../types/PageList'; import { Id, Key } from '../types/Id'; import { when } from '../validation/When'; import { Exception } from '../types/Exception'; import { List } from '../types/List'; import { RouteGateway } from '../services/RouteGateway'; import { RouteOptions } from '../services/Api'; export class Typo extends Repository { constructor( protected view: View, private readonly gateway: Gateway ) { super(); } create = (j: Json): T => this.view.from(j); all(options?: Options): Promise> { return this.gateway.all(options).then(js => js.map(this.create)); } byId(id: Id): Promise { return this.gateway .byId(id) .then(j => when(j).not.isDefined.reject(Exception.DoesNotExist)) .then(j => this.create(j)); } byIds(...ids: Id[]): Promise> { return this.gateway.byIds(...ids).then(js => js.map(this.create)); } byKey(key: Key, options?: Options): Promise> { return this.gateway.by('key', key, options).then(js => js.map(this.create)); } by(key: keyof T, value: JsonValue, options?: Options): Promise> { return this.gateway.by(key.toString(), value, options).then(js => js.map(this.create)); } search(q: JsonValue, options?: Options): Promise> { return this.gateway.search(q, options).then(js => js.map(this.create)); } filter(options?: Options): Promise> { return this.gateway.filter(options).then(js => js.map(j => this.create(j))); } exists(id: Id): Promise { return this.gateway.exists(id); } } export class Agent extends Repository { constructor(private gateway: RouteGateway) { super(); } all(options?: Options): Promise> { return this.gateway.all(options) as Promise>; } byId(id: Id): Promise { return this.gateway.byId(id) as Promise; } byIds(...ids: Id[]): Promise> { return this.gateway.byIds(...ids) as Promise>; } byKey(key: Key, options?: Options): Promise> { return this.gateway.by('key', key, options) as Promise>; } by(key: keyof T, value: JsonValue, options?: Options): Promise> { return this.gateway.by(key.toString(), value, options) as Promise>; } search(q: JsonValue, options?: Options): Promise> { return this.gateway.search(q, options) as Promise>; } filter(options?: Options): Promise> { return this.gateway.filter(options) as Promise>; } exists(id: Id): Promise { return this.gateway.exists(id); } add(t: Partial): Promise { return this.gateway.add(toJson(t)) as Promise; } update(id: Id, t: Partial): Promise { return this.gateway.update({ ...toJson(t), id }) as Promise; } upsert(id: Id, t: Partial): Promise { return this.gateway.upsert({ ...toJson(t), id }) as Promise; } remove(id: Id): Promise { return this.gateway.remove(id); } }