Skip to content

Commit

Permalink
fix(database): cms route sorting (#425)
Browse files Browse the repository at this point in the history
  • Loading branch information
kon14 committed Nov 16, 2022
1 parent 97340a5 commit a2f87c2
Show file tree
Hide file tree
Showing 10 changed files with 49 additions and 26 deletions.
4 changes: 2 additions & 2 deletions modules/chat/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { v4 as uuid } from 'uuid';
export async function validateUsersInput(grpcSdk: ConduitGrpcSdk, users: any[]) {
const uniqueUsers = Array.from(new Set(users));
let errorMessage: string | null = null;
const usersToBeAdded = (await grpcSdk
.databaseProvider!.findMany('User', { _id: { $in: uniqueUsers } })
const usersToBeAdded = (await User.getInstance()
.findMany({ _id: { $in: uniqueUsers } })
.catch((e: Error) => {
errorMessage = e.message;
})) as any[];
Expand Down
4 changes: 3 additions & 1 deletion modules/database/src/Database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,9 @@ export default class DatabaseModule extends ManagedModule<void> {
const skip = call.request.skip;
const limit = call.request.limit;
const select = call.request.select;
const sort = call.request.sort ? JSON.parse(call.request.sort) : null;
const sort: { [key: string]: number } = call.request.sort
? JSON.parse(call.request.sort)
: null;
const populate = call.request.populate;

const schemaAdapter = this._activeAdapter.getSchemaModel(call.request.schemaName);
Expand Down
18 changes: 11 additions & 7 deletions modules/database/src/adapters/mongoose-adapter/MongooseSchema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Model, Mongoose, Schema } from 'mongoose';
import { Model, Mongoose, Schema, SortOrder } from 'mongoose';
import {
MultiDocQuery,
ParsedQuery,
Expand Down Expand Up @@ -166,7 +166,7 @@ export class MongooseSchema implements SchemaAdapter<Model<any>> {
skip?: number,
limit?: number,
select?: string,
sort?: string,
sort?: { [key: string]: number },
populate?: string[],
) {
let parsedQuery: ParsedQuery | ParsedQuery[];
Expand All @@ -176,17 +176,17 @@ export class MongooseSchema implements SchemaAdapter<Model<any>> {
parsedQuery = query;
}
let finalQuery = this.model.find(this.parseQuery(parsedQuery), select);
if (skip !== null) {
if (!isNil(skip)) {
finalQuery = finalQuery.skip(skip!);
}
if (limit !== null) {
if (!isNil(limit)) {
finalQuery = finalQuery.limit(limit!);
}
if (populate != null) {
if (!isNil(populate)) {
finalQuery = this.calculatePopulates(finalQuery, populate);
}
if (sort !== null) {
finalQuery = finalQuery.sort(sort);
if (!isNil(sort)) {
finalQuery = finalQuery.sort(this.parseSort(sort));
}
// } else {
// finalQuery = finalQuery.sort({ createdAt: -1 });
Expand Down Expand Up @@ -235,4 +235,8 @@ export class MongooseSchema implements SchemaAdapter<Model<any>> {

return parsed;
}

private parseSort(sort: { [key: string]: number }): { [p: string]: SortOrder } {
return sort as { [p: string]: SortOrder };
}
}
18 changes: 8 additions & 10 deletions modules/database/src/adapters/sequelize-adapter/SequelizeSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
FindOptions,
ModelCtor,
Sequelize,
Order,
OrderItem,
} from 'sequelize';
import {
Expand Down Expand Up @@ -179,7 +180,7 @@ export class SequelizeSchema implements SchemaAdapter<ModelCtor<any>> {
skip?: number,
limit?: number,
select?: string,
sort?: string,
sort?: { [key: string]: number },
populate?: string[],
relations?: Indexable,
): Promise<any> {
Expand Down Expand Up @@ -491,18 +492,15 @@ export class SequelizeSchema implements SchemaAdapter<ModelCtor<any>> {
return { exclude };
}

private parseSort(sort: string) {
const fields = sort.split(' ');
const order = [];
for (const field of fields) {
let tmp;
private parseSort(sort: { [key: string]: number }): Order {
const order: Order = [];
Object.keys(sort).forEach(field => {
if (field[0] === '-') {
tmp = [field.slice(1), 'DESC'] as OrderItem;
order.push([field.slice(1), 'DESC'] as OrderItem);
} else {
tmp = [field, 'ASC'] as OrderItem;
order.push([field, 'ASC'] as OrderItem);
}
order.push(tmp);
}
});
return order;
}
}
2 changes: 1 addition & 1 deletion modules/database/src/controllers/cms/schema.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { sortAndConstructRoutes } from './utils';
import { DatabaseAdapter } from '../../adapters/DatabaseAdapter';
import { MongooseSchema } from '../../adapters/mongoose-adapter/MongooseSchema';
import { SequelizeSchema } from '../../adapters/sequelize-adapter/SequelizeSchema';
import { CmsHandlers } from '../../handlers/cms/handler';
import { CmsHandlers } from '../../handlers/cms/crud.handler';
import { ParsedQuery } from '../../interfaces';
import { status } from '@grpc/grpc-js';
import { isNil } from 'lodash';
Expand Down
2 changes: 1 addition & 1 deletion modules/database/src/controllers/cms/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
RouteBuilder,
TYPE,
} from '@conduitplatform/grpc-sdk';
import { CmsHandlers } from '../../handlers/cms/handler';
import { CmsHandlers } from '../../handlers/cms/crud.handler';
import { ConduitBuiltRoute } from '../../interfaces';

export function compareFunction(schemaA: ConduitModel, schemaB: ConduitModel): number {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
Indexable,
} from '@conduitplatform/grpc-sdk';
import { constructAssignment, constructQuery } from './utils';
import { constructSortObj } from '../utils';
import { status } from '@grpc/grpc-js';
import { ICustomEndpoint, PopulatedCustomEndpoint } from '../../interfaces';
import { OperationsEnum } from '../../admin/customEndpoints/customEndpoints.admin';
Expand Down Expand Up @@ -111,9 +112,9 @@ export class CustomEndpointHandler {
);
}

let sort: string | undefined = undefined;
let sort: { [key: string]: number } | undefined = undefined;
if (endpoint.sorted && params.sort && params.sort.length > 0) {
sort = params.sort;
sort = constructSortObj(params.sort);
}

const createObj = this.parseCreateQuery(createString);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { MongooseSchema } from '../../adapters/mongoose-adapter/MongooseSchema';
import { SequelizeSchema } from '../../adapters/sequelize-adapter/SequelizeSchema';
import { Doc } from '../../interfaces';
import { findSchema, getUpdatedDocument, getUpdatedDocuments } from './utils';
import { constructSortObj } from '../utils';

export class CmsHandlers {
constructor(
Expand All @@ -31,9 +32,14 @@ export class CmsHandlers {
limitNumber = Number.parseInt(limit as string);
}

let parsedSort: { [key: string]: number } | undefined = undefined;
if (sort && sort.length > 0) {
parsedSort = constructSortObj(sort);
}

const documentsPromise = this.database
.getSchemaModel(schemaName)
.model.findMany({}, skipNumber, limitNumber, undefined, sort, populate);
.model.findMany({}, skipNumber, limitNumber, undefined, parsedSort, populate);
const countPromise = this.database
.getSchemaModel(schemaName)
.model.countDocuments({});
Expand Down
12 changes: 12 additions & 0 deletions modules/database/src/handlers/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export function constructSortObj(sort: string[]) {
const sortObj: { [key: string]: number } = {};
sort.forEach((sortVal: string) => {
sortVal = sortVal.trim();
if (sortVal.indexOf('-') !== -1) {
sortObj[sortVal.substring(1)] = -1;
} else {
sortObj[sortVal] = 1;
}
});
return sortObj;
}
2 changes: 1 addition & 1 deletion modules/database/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CmsHandlers } from '../handlers/cms/handler';
import { CmsHandlers } from '../handlers/cms/crud.handler';
import ConduitGrpcSdk, {
ConduitRouteOptions,
ConduitRouteReturnDefinition,
Expand Down

0 comments on commit a2f87c2

Please sign in to comment.