import EntityMetaManager from "../entity/entity-meta-manager"; import EntityDataMapper from "../entity/entity-data-mapper"; import EntityFilterQuery from "../entity/query/entity-filter-query"; import EntityFilteredResults from "../entity/query/entity-filtered-results"; import Config from "../config"; /** * Entity API class */ export default class EntityApi { /** * Get all entities defined for the current site. */ public get definitions(): Promise { return EntityMetaManager.definitions; } /** * Get the entity represented by the current URL path. Also, handle * welcome file scenario by checking parent path as well */ public get current(): Promise { // Shortcut if we have a current object configured if (Config.instance().currentObject) { let currentObject = Config.instance().currentObject; return this.byId(currentObject.type, currentObject.id); } else { return EntityMetaManager.urlTypeMap.then(map => { let path = location.pathname.substr(1); if (path.endsWith("/")) { path = path.substr(0, path.length - 1); } let parentPath: any = path.split("/"); parentPath.pop(); parentPath = parentPath.join("/"); let targetType = map[path]; let parentTargetType = map[parentPath]; if (targetType) { return this.byPath(targetType, path); } else if (parentTargetType) { return this.byPath(parentTargetType, parentPath); } else { return null; } }); } } /** * Get an entity by id or throw an exception */ public byId(entityName: string, id: string): Promise { return EntityDataMapper.getMapper(entityName).then((dataMapper: EntityDataMapper) => { return dataMapper.getById(id); }); } /** * Get an entity by path or throw an exception * * @param entityName * @param path */ public byPath(entityName: string, path: string): Promise { return EntityDataMapper.getMapper(entityName).then((datamapper: EntityDataMapper) => { return datamapper.getByPath(path); }); } /** * Get a single instance entity * * @param entityName */ public single(entityName: string): Promise { return EntityDataMapper.getMapper(entityName).then((datamapper: EntityDataMapper) => { return datamapper.single(); }); } /** * Get filtered entities using the supplied query * * @param entityName * @param filterQuery */ public filter(entityName: string, filterQuery: EntityFilterQuery): Promise { return EntityDataMapper.getMapper(entityName).then((datamapper: EntityDataMapper) => { return datamapper.getFilteredResults(filterQuery); }); } /** * Get all entities for the current type * * @param entityName */ public all(entityName: string): Promise { return EntityDataMapper.getMapper(entityName).then((datamapper: EntityDataMapper) => { return datamapper.all(); }); } }