Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remult with limit data api #123

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions core-api/src/context.d.ts
Expand Up @@ -38,6 +38,7 @@ export declare class Remult {
*
*/
repo<T>(entity: ClassType<T>, dataProvider?: DataProvider): Repository<T>;
__enforceApiRules: boolean;
user?: UserInfo;
/** Checks if a user was authenticated */
authenticated(): boolean;
Expand Down
1 change: 1 addition & 0 deletions core-api/src/data-api.d.ts
Expand Up @@ -9,6 +9,7 @@ export declare class DataApi<T = any> {
httpPost(res: DataApiResponse, req: DataApiRequest, body: any): Promise<void>;
static defaultGetLimit: number;
get(response: DataApiResponse, id: any): Promise<void>;
catch(err: any, response: DataApiResponse): void;
count(response: DataApiResponse, request: DataApiRequest, filterBody?: any): Promise<void>;
getArray(response: DataApiResponse, request: DataApiRequest, filterBody?: any): Promise<void>;
private buildWhere;
Expand Down
3 changes: 2 additions & 1 deletion core-api/src/remult3/RepositoryImplementation.d.ts
Expand Up @@ -3,7 +3,7 @@ import { EntityOptions } from "../entity";
import { LookupColumn } from '../column';
import { EntityMetadata, FieldRef, FieldsRef, EntityFilter, FindOptions, Repository, EntityRef, QueryOptions, QueryResult, EntityOrderBy, FieldsMetadata, IdMetadata, FindFirstOptionsBase, FindFirstOptions, OmitEB, Subscribable, ControllerRef } from "./remult3";
import { ClassType } from "../../classType";
import { Remult, Unobserve } from "../context";
import { Remult, Unobserve, AllowedForInstance } from "../context";
import { entityEventListener } from "../__EntityValueProvider";
import { DataProvider, EntityDataProvider } from "../data-interfaces";
import { RefSubscriber } from ".";
Expand Down Expand Up @@ -93,6 +93,7 @@ declare abstract class rowHelperBase<T> {
__validateEntity(): Promise<void>;
__performColumnAndEntityValidations(): Promise<void>;
toApiJson(): any;
allowedWithUndefinedTrue(allow: AllowedForInstance<T>): boolean;
_updateEntityBasedOnApi(body: any): Promise<void>;
}
export declare class rowHelperImplementation<T> extends rowHelperBase<T> implements EntityRef<T> {
Expand Down
8 changes: 8 additions & 0 deletions core-api/src/remult3/remult3.d.ts
@@ -1,6 +1,7 @@
import { ClassType } from "../../classType";
import { FieldMetadata } from "../column-interfaces";
import { Unobserve } from "../context";
import { ErrorInfo } from "../data-interfaces";
import { EntityOptions as EntityOptions } from "../entity";
import { SortSegment } from "../sort";
import { entityEventListener } from "../__EntityValueProvider";
Expand Down Expand Up @@ -310,3 +311,10 @@ export interface Paginator<entityType> {
/** the count of the total items in the `query`'s result */
count(): Promise<number>;
}
export declare class ForbiddenError extends Error implements ErrorInfo {
constructor();
message: string;
isForbiddenError: boolean;
httpStatusCode: number;
static isForbiddenError(error: any): boolean;
}
2 changes: 1 addition & 1 deletion projects/core/src/context.ts
Expand Up @@ -129,9 +129,9 @@ export class Remult {
return r;
}

__enforceApiRules = false;
user?: UserInfo;

/* delete me */
/** Checks if a user was authenticated */
authenticated() {
return this.user?.id !== undefined;
Expand Down
92 changes: 21 additions & 71 deletions projects/core/src/data-api.ts
@@ -1,14 +1,13 @@
import { EntityOptions } from './entity';
import { AndFilter, customUrlToken, buildFilterFromRequestParameters } from './filter/filter-interfaces';
import { Remult, UserInfo } from './context';
import { customUrlToken, buildFilterFromRequestParameters } from './filter/filter-interfaces';
import { Remult } from './context';
import { Filter } from './filter/filter-interfaces';
import { FindOptions, Repository, EntityRef, rowHelperImplementation, EntityFilter } from './remult3';
import { SortSegment } from './sort';
import { FindOptions, Repository, rowHelperImplementation, EntityFilter, ForbiddenError } from './remult3';
import { ErrorInfo } from './data-interfaces';

export class DataApi<T = any> {

constructor(private repository: Repository<T>, private remult: Remult) {
remult.__enforceApiRules = true;
}
httpGet(res: DataApiResponse, req: DataApiRequest) {
if (req.get("__action") == "count") {
Expand All @@ -28,63 +27,31 @@ export class DataApi<T = any> {
}
static defaultGetLimit = 0;
async get(response: DataApiResponse, id: any) {
if (!this.repository.metadata.apiReadAllowed) {
response.forbidden();
return;
}

await this.doOnId(response, id, async row => response.success(this.repository.getEntityRef(row).toApiJson()));

}
async count(response: DataApiResponse, request: DataApiRequest, filterBody?: any) {
if (!this.repository.metadata.apiReadAllowed) {
catch(err: any, response: DataApiResponse) {
if (ForbiddenError.isForbiddenError(err))
response.forbidden();
return;
}
try {
else
response.error(err);
}
async count(response: DataApiResponse, request: DataApiRequest, filterBody?: any) {

try {
response.success({ count: +await this.repository.count(await this.buildWhere(request, filterBody)) });
} catch (err) {
response.error(err);
this.catch(err, response);
}
}


async getArray(response: DataApiResponse, request: DataApiRequest, filterBody?: any) {
if (!this.repository.metadata.apiReadAllowed) {
response.forbidden();
return;
}
try {
let findOptions: FindOptions<T> = { load: () => [] };
findOptions.where = await this.buildWhere(request, filterBody);
if (this.remult.isAllowed(this.repository.metadata.options.apiRequireId)) {
let hasId = false;
let w = await Filter.fromEntityFilter(this.repository.metadata, findOptions.where);
if (w) {
w.__applyToConsumer({
containsCaseInsensitive: () => { },
isDifferentFrom: () => { },
isEqualTo: (col, val) => {
if (this.repository.metadata.idMetadata.isIdField(col))
hasId = true;
},
custom: () => { },
databaseCustom: () => { },
isGreaterOrEqualTo: () => { },
isGreaterThan: () => { },
isIn: () => { },
isLessOrEqualTo: () => { },
isLessThan: () => { },
isNotNull: () => { },
isNull: () => { },

or: () => { }
});
}
if (!hasId) {
response.forbidden();
return
}
}

if (request) {

let sort = <string>request.get("_sort");
Expand All @@ -106,17 +73,12 @@ export class DataApi<T = any> {
});
}
catch (err) {
response.error(err);
this.catch(err, response);
}
}
private async buildWhere(request: DataApiRequest, filterBody: any): Promise<EntityFilter<any>> {
var where: EntityFilter<any>[] = [];
if (this.repository.metadata.options.apiPrefilter) {
if (typeof this.repository.metadata.options.apiPrefilter === "function")
where.push(await this.repository.metadata.options.apiPrefilter());
else
where.push(this.repository.metadata.options.apiPrefilter);
}

if (request) {
where.push(buildFilterFromRequestParameters(this.repository.metadata, {
get: key => {
Expand All @@ -140,7 +102,7 @@ export class DataApi<T = any> {


await this.repository.find({
where: { $and: [this.repository.metadata.options.apiPrefilter, this.repository.metadata.idMetadata.getIdFilter(id)] } as EntityFilter<any>
where: { $and: [this.repository.metadata.idMetadata.getIdFilter(id)] } as EntityFilter<any>
})
.then(async r => {
if (r.length == 0)
Expand All @@ -151,30 +113,21 @@ export class DataApi<T = any> {
await what(r[0]);
});
} catch (err) {
response.error(err);
this.catch(err, response);
}
}
async put(response: DataApiResponse, id: any, body: any) {

await this.doOnId(response, id, async row => {
let ref = this.repository.getEntityRef(row) as rowHelperImplementation<T>;
await ref._updateEntityBasedOnApi(body);
if (!ref.apiUpdateAllowed) {
response.forbidden();
return;
}
await this.repository.getEntityRef(row).save();
response.success(this.repository.getEntityRef(row).toApiJson());
});
}

async delete(response: DataApiResponse, id: any) {
await this.doOnId(response, id, async row => {

if (!this.repository.getEntityRef(row).apiDeleteAllowed) {
response.forbidden();
return;
}
await this.repository.getEntityRef(row).delete();
response.deleted();
});
Expand All @@ -186,15 +139,12 @@ export class DataApi<T = any> {
try {
let newr = this.repository.create();
await (this.repository.getEntityRef(newr) as rowHelperImplementation<T>)._updateEntityBasedOnApi(body);
if (!this.repository.getEntityRef(newr).apiInsertAllowed) {
response.forbidden();
return;
}


await this.repository.getEntityRef(newr).save();
response.created(this.repository.getEntityRef(newr).toApiJson());
} catch (err) {
response.error(err);
this.catch(err, response);
}
}

Expand Down
6 changes: 6 additions & 0 deletions projects/core/src/remult-proxy.ts
Expand Up @@ -7,6 +7,12 @@ import { Repository, RepositoryImplementation } from "./remult3";
let defaultRemult = new Remult();
/*@internal*/
export class RemultProxy implements Remult {
get __enforceApiRules() {
return this.remultFactory().__enforceApiRules;
}
set __enforceApiRules(value: boolean) {
this.remultFactory().__enforceApiRules = value;
}
call<T extends ((...args: any[]) => Promise<any>)>(backendMethod: T, self?: any, ...args: GetArguments<T>): ReturnType<T> {
return this.remultFactory().call(backendMethod, self, ...args);
}
Expand Down