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

fix(database): route declare order for crud #412

Merged
merged 2 commits into from
Nov 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
FindAttributeOptions,
FindOptions,
ModelCtor,
Order,
Sequelize,
} from 'sequelize';
import {
Expand Down Expand Up @@ -179,7 +178,7 @@ export class SequelizeSchema implements SchemaAdapter<ModelCtor<any>> {
skip?: number,
limit?: number,
select?: string,
sort?: Order,
sort?: string,
populate?: string[],
relations?: Indexable,
): Promise<any> {
Expand All @@ -202,9 +201,10 @@ export class SequelizeSchema implements SchemaAdapter<ModelCtor<any>> {
if (!isNil(select) && select !== '') {
options.attributes = this.parseSelect(select);
}
if (!isNil(sort)) {
options.order = sort;
}
// if (!isNil(sort)) {
// TODO: parse sort str
// options.order = new Literal(sort);
// }

const documents = await this.model.findAll(options);

Expand Down
22 changes: 11 additions & 11 deletions modules/database/src/controllers/cms/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,6 @@ export function getOps(
actualSchema.modelOptions.conduit!.cms.crudOperations.read.enabled;
if (readIsEnabled) {
let route = new RouteBuilder()
.path(`/${schemaName}/:id`)
.method(ConduitRouteActions.GET)
.urlParams({
id: { type: TYPE.String, required: true },
})
.cacheControl(authenticatedRead ? 'private, max-age=10' : 'public, max-age=10')
.return(`${schemaName}`, actualSchema.fields)
.handler(handlers.getDocumentById.bind(handlers));
if (authenticatedRead) route.middleware('authMiddleware');
routesArray.push(route.build());
route = new RouteBuilder()
.path(`/${schemaName}`)
.method(ConduitRouteActions.GET)
.queryParams({
Expand All @@ -110,6 +99,17 @@ export function getOps(
.handler(handlers.getDocuments.bind(handlers));
if (authenticatedRead) route.middleware('authMiddleware');
routesArray.push(route.build());
route = new RouteBuilder()
.path(`/${schemaName}/:id`)
.method(ConduitRouteActions.GET)
.urlParams({
id: { type: TYPE.String, required: true },
})
.cacheControl(authenticatedRead ? 'private, max-age=10' : 'public, max-age=10')
.return(`${schemaName}`, actualSchema.fields)
.handler(handlers.getDocumentById.bind(handlers));
if (authenticatedRead) route.middleware('authMiddleware');
routesArray.push(route.build());
}
const authenticatedCreate =
actualSchema.modelOptions.conduit!.cms.crudOperations.create.authenticated;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export class CustomEndpointController {
private readonly grpcSdk: ConduitGrpcSdk,
private readonly database: DatabaseAdapter<MongooseSchema | SequelizeSchema>,
) {
this.handler = new CustomEndpointHandler(this.grpcSdk);
this.handler = new CustomEndpointHandler(database);
this.refreshRoutes();
this.initializeState();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import ConduitGrpcSdk, {
import {
ParsedRouterRequest,
UnparsedRouterResponse,
GrpcError,
Indexable,
} from '@conduitplatform/grpc-sdk';
import { constructAssignment, constructQuery } from './utils';
import { status } from '@grpc/grpc-js';
import { ICustomEndpoint, PopulatedCustomEndpoint, Sort } from '../../interfaces';
import { ICustomEndpoint, PopulatedCustomEndpoint } from '../../interfaces';
import { OperationsEnum } from '../../admin/customEndpoints/customEndpoints.admin';
import { isNil } from 'lodash';
import { DatabaseAdapter } from '../../adapters/DatabaseAdapter';
import { MongooseSchema } from '../../adapters/mongoose-adapter/MongooseSchema';
import { SequelizeSchema } from '../../adapters/sequelize-adapter/SequelizeSchema';

export class CustomEndpointHandler {
private static routeControllers: Indexable = {};

constructor(private readonly grpcSdk: ConduitGrpcSdk) {}
constructor(
private readonly database: DatabaseAdapter<MongooseSchema | SequelizeSchema>,
) {}

static addNewCustomOperationControl(
endpoint: ICustomEndpoint | PopulatedCustomEndpoint,
Expand Down Expand Up @@ -106,72 +111,57 @@ export class CustomEndpointHandler {
);
}

let sortObj: Sort | null = null;
let sort: string | undefined = undefined;
if (endpoint.sorted && params.sort && params.sort.length > 0) {
const sort = params.sort;
sortObj = {};
sort.forEach((sortVal: string) => {
sortVal = sortVal.trim();
if (sortVal.indexOf('-') !== -1) {
(sortObj as Indexable)[sortVal.substr(1)] = -1;
} else {
(sortObj as Indexable)[sortVal] = 1;
}
});
sort = params.sort;
}

const createObj = this.parseCreateQuery(createString);
let promise;
if (endpoint.operation === OperationsEnum.GET) {
if (endpoint.paginated) {
const documentsPromise = this.grpcSdk.databaseProvider!.findMany(
endpoint.selectedSchemaName,
searchQuery,
undefined,
params['skip'],
params['limit'],
sortObj as Sort,
params['populate'],
);
const countPromise = this.grpcSdk.databaseProvider!.countDocuments(
endpoint.selectedSchemaName,
searchQuery,
);
const documentsPromise = this.database
.getSchemaModel(endpoint.selectedSchemaName)
.model.findMany(
searchQuery,
params['skip'],
params['limit'],
undefined,
sort,
params['populate'],
);
const countPromise = this.database
.getSchemaModel(endpoint.selectedSchemaName)
.model.countDocuments(searchQuery);
promise = Promise.all([documentsPromise, countPromise]);
} else {
promise = this.grpcSdk.databaseProvider!.findMany(
endpoint.selectedSchemaName,
searchQuery,
undefined,
undefined,
undefined,
sortObj as Sort,
params['populate'],
);
promise = this.database
.getSchemaModel(endpoint.selectedSchemaName)
.model.findMany(
searchQuery,
undefined,
undefined,
undefined,
sort,
params['populate'],
);
}
} else if (endpoint.operation === OperationsEnum.POST) {
promise = this.grpcSdk.databaseProvider!.create(
endpoint.selectedSchemaName,
createObj,
);
promise = this.database
.getSchemaModel(endpoint.selectedSchemaName)
.model.create(createObj);
} else if (endpoint.operation === OperationsEnum.PUT) {
promise = this.grpcSdk.databaseProvider!.updateMany(
endpoint.selectedSchemaName,
searchQuery,
createObj,
);
promise = this.database
.getSchemaModel(endpoint.selectedSchemaName)
.model.updateMany(searchQuery, createObj);
} else if (endpoint.operation === OperationsEnum.DELETE) {
promise = this.grpcSdk.databaseProvider!.deleteMany(
endpoint.selectedSchemaName,
searchQuery,
);
promise = this.database
.getSchemaModel(endpoint.selectedSchemaName)
.model.deleteMany(searchQuery);
} else if (endpoint.operation === OperationsEnum.PATCH) {
promise = this.grpcSdk.databaseProvider!.updateMany(
endpoint.selectedSchemaName,
searchQuery,
createObj,
true,
);
promise = this.database
.getSchemaModel(endpoint.selectedSchemaName)
.model.updateMany(searchQuery, createObj, true);
} else {
process.exit(-1);
}
Expand Down
61 changes: 34 additions & 27 deletions modules/database/src/handlers/cms/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class CmsHandlers {

async getDocuments(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> {
const { skip, limit, sort, populate } = call.request.params;
const res = await findSchema(call, this.database).catch((e: Error) => {
const schemaName = await findSchema(call, this.database).catch((e: Error) => {
throw e;
});
let skipNumber = 0,
Expand All @@ -32,44 +32,48 @@ export class CmsHandlers {
}

const documentsPromise = this.database
.getSchemaModel(res.schemaName)
.getSchemaModel(schemaName)
.model.findMany({}, skipNumber, limitNumber, undefined, sort, populate);
const countPromise = this.database
.getSchemaModel(res.schemaName)
.getSchemaModel(schemaName)
.model.countDocuments({});
const [documents, count] = await Promise.all([documentsPromise, countPromise]);

return { documents, count };
}

async getDocumentById(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> {
const res = await findSchema(call, this.database).catch((e: Error) => {
const schemaName = await findSchema(call, this.database).catch((e: Error) => {
throw e;
});
const document: Doc | undefined = await this.database
.getSchemaModel(res.schemaName)
.model?.findOne({ _id: res.id }, undefined, res.populate);
.getSchemaModel(schemaName)
.model?.findOne(
{ _id: call.request.params.id },
undefined,
call.request.params.populate,
);
if (!document) {
throw new GrpcError(status.NOT_FOUND, 'Document does not exist');
}
return document;
}

async createDocument(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> {
const res = await findSchema(call, this.database).catch((e: Error) => {
const schemaName = await findSchema(call, this.database).catch((e: Error) => {
throw e;
});

return this.database.getSchemaModel(res.schemaName).model!.create(res.inputDocument);
return this.database.getSchemaModel(schemaName).model!.create(call.request.params);
}

async createManyDocuments(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> {
const inputDocuments = call.request.params.docs;
const res = await findSchema(call, this.database).catch((e: Error) => {
const schemaName = await findSchema(call, this.database).catch((e: Error) => {
throw e;
});
const newDocuments = await this.database
.getSchemaModel(res.schemaName)
.getSchemaModel(schemaName)
.model?.createMany(inputDocuments)
.catch((e: Error) => {
throw new GrpcError(status.INTERNAL, e.message);
Expand All @@ -79,35 +83,38 @@ export class CmsHandlers {
}

async updateDocument(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> {
const res = await findSchema(call, this.database).catch((e: Error) => {
const schemaName = await findSchema(call, this.database).catch((e: Error) => {
throw e;
});
return getUpdatedDocument(
schemaName,
call.request.params,
this.database,
false,
).catch((e: Error) => {
throw e;
});
return getUpdatedDocument(res.schemaName, res.params, this.database, false).catch(
(e: Error) => {
throw e;
},
);
}

async patchDocument(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> {
const res = await findSchema(call, this.database).catch((e: Error) => {
const schemaName = await findSchema(call, this.database).catch((e: Error) => {
throw e;
});
return getUpdatedDocument(res.schemaName, res.params, this.database, true).catch(
return getUpdatedDocument(schemaName, call.request.params, this.database, true).catch(
(e: Error) => {
throw e;
},
);
}

async updateManyDocuments(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> {
const res = await findSchema(call, this.database).catch((e: Error) => {
const schemaName = await findSchema(call, this.database).catch((e: Error) => {
throw e;
});

const updatedDocuments = await getUpdatedDocuments(
res.schemaName,
res.params,
schemaName,
call.request.params,
this.database,
false,
).catch((e: Error) => {
Expand All @@ -117,12 +124,12 @@ export class CmsHandlers {
}

async patchManyDocuments(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> {
const res = await findSchema(call, this.database).catch((e: Error) => {
const schemaName = await findSchema(call, this.database).catch((e: Error) => {
throw e;
});
const updatedDocuments = await getUpdatedDocuments(
res.schemaName,
res.params,
schemaName,
call.request.params,
this.database,
true,
).catch((e: Error) => {
Expand All @@ -133,12 +140,12 @@ export class CmsHandlers {
}

async deleteDocument(call: ParsedRouterRequest): Promise<UnparsedRouterResponse> {
const res = await findSchema(call, this.database).catch((e: Error) => {
const schemaName = await findSchema(call, this.database).catch((e: Error) => {
throw e;
});
await this.database
.getSchemaModel(res.schemaName)
.model?.deleteOne({ _id: res.id })
.getSchemaModel(schemaName)
.model?.deleteOne({ _id: call.request.params.id })
.catch((e: Error) => {
throw new GrpcError(status.INTERNAL, e.message);
});
Expand Down
4 changes: 1 addition & 3 deletions modules/database/src/handlers/cms/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ export async function findSchema(
call: ParsedRouterRequest,
database: DatabaseAdapter<MongooseSchema | SequelizeSchema>,
) {
const { params, populate, inputDocument } = call.request.params;
const id = params.id;
const schemaName = call.request.path.split('/')[2];
const schema = await database
.getSchemaModel('_DeclaredSchema')
Expand All @@ -21,7 +19,7 @@ export async function findSchema(
if (!schema) {
throw new GrpcError(status.NOT_FOUND, 'Schema does not exist');
}
return { params, schemaName, id, populate, inputDocument };
return schemaName;
}

export async function getUpdatedDocument(
Expand Down
1 change: 0 additions & 1 deletion modules/database/src/interfaces/Sort.ts

This file was deleted.

1 change: 0 additions & 1 deletion modules/database/src/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@ export * from './CustomEndpointsQuery';
export * from './DeclaredSchema';
export * from './DeclaredSchemaExtension';
export * from './SchemaAdapter';
export * from './Sort';
export * from './TypeHacks';