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: fix ordering for relationships #51

Merged
merged 1 commit into from
Feb 5, 2024
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
2 changes: 1 addition & 1 deletion src/Property.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Enums } from './types.js';
import { DATA_TYPES } from './utils/data-types.js';

export class Property extends BaseProperty {
private column: DMMF.Field;
public column: DMMF.Field;

private enums: Enums;

Expand Down
105 changes: 85 additions & 20 deletions src/Resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ export class Resource extends BaseResource {

private propertiesObject: Record<string, any>;

constructor(args: { model: DMMF.Model, client: PrismaClient, clientModule?: any }) {
constructor(args: {
model: DMMF.Model;
client: PrismaClient;
clientModule?: any;
}) {
super(args);

const { model, client, clientModule } = args;
Expand Down Expand Up @@ -58,23 +62,53 @@ export class Resource extends BaseResource {
}

public async count(filter: Filter): Promise<number> {
return this.manager.count({ where: convertFilter(this.model.fields, filter) });
return this.manager.count({
where: convertFilter(this.model.fields, filter),
});
}

public async find(filter: Filter, params: Record<string, any> = {}): Promise<Array<BaseRecord>> {
public async find(
filter: Filter,
params: Record<string, any> = {},
): Promise<Array<BaseRecord>> {
const { limit = 10, offset = 0, sort = {} } = params;
const { direction, sortBy } = sort as { direction: 'asc' | 'desc', sortBy: string };
const { direction, sortBy } = sort as {
direction: 'asc' | 'desc';
sortBy: string;
};

const orderBy = this.buildSortBy(sortBy, direction);
const results = await this.manager.findMany({
where: convertFilter(this.model.fields, filter),
skip: offset,
take: limit,
orderBy: {
[sortBy]: direction,
},
orderBy,
});

return results.map((result) => new BaseRecord(this.prepareReturnValues(result), this));
return results.map(
(result) => new BaseRecord(this.prepareReturnValues(result), this),
);
}

private buildSortBy(path: string, direction: 'asc' | 'desc') {
const [basePath, sortBy] = path.split('.');
const sortByProperty = this.property(basePath);

if (
sortByProperty?.column.relationName
&& sortByProperty?.column.kind === 'object'
&& sortByProperty.column.relationToFields?.length
) {
return {
[basePath]: {
[sortBy ?? sortByProperty.column.relationToFields[0]]: direction,
},
};
}

return {
[basePath]: direction,
}
}

public async findOne(id: string | number): Promise<BaseRecord | null> {
Expand Down Expand Up @@ -105,18 +139,25 @@ export class Resource extends BaseResource {
},
});

return results.map((result) => new BaseRecord(this.prepareReturnValues(result), this));
return results.map(
(result) => new BaseRecord(this.prepareReturnValues(result), this),
);
}

public async create(params: Record<string, any>): Promise<Record<string, any>> {
public async create(
params: Record<string, any>,
): Promise<Record<string, any>> {
const preparedParams = this.prepareParams(params);

const result = await this.manager.create({ data: preparedParams });

return this.prepareReturnValues(result);
}

public async update(pk: string | number, params: Record<string, any> = {}): Promise<Record<string, any>> {
public async update(
pk: string | number,
params: Record<string, any> = {},
): Promise<Record<string, any>> {
const idProperty = this.properties().find((property) => property.isId());
if (!idProperty) return {};

Expand All @@ -143,25 +184,41 @@ export class Resource extends BaseResource {
});
}

public static isAdapterFor(args: { model: DMMF.Model, client: PrismaClient }): boolean {
public static isAdapterFor(args: {
model: DMMF.Model;
client: PrismaClient;
}): boolean {
const { model, client } = args;

return !!model?.name && !!model?.fields.length && !!client?.[lowerCase(model.name)];
return (
!!model?.name
&& !!model?.fields.length
&& !!client?.[lowerCase(model.name)]
);
}

private prepareProperties(): { [propertyPath: string]: Property } {
const { fields = [] } = this.model;

return fields.reduce((memo, field) => {
if (field.isReadOnly || (field.relationName && !field.relationFromFields?.length)) {
const properties = fields.reduce((memo, field) => {
if (
field.isReadOnly
|| (field.relationName && !field.relationFromFields?.length)
) {
return memo;
}

const property = new Property(field, Object.keys(memo).length, this.enums);
const property = new Property(
field,
Object.keys(memo).length,
this.enums,
);
memo[property.path()] = property;

return memo;
}, {});

return properties;
}

private prepareParams(params: Record<string, any>): Record<string, any> {
Expand All @@ -178,23 +235,31 @@ export class Resource extends BaseResource {
const foreignColumnName = property.foreignColumnName();

if (type === 'reference' && foreignColumnName) {
preparedParams[foreignColumnName] = convertParam(property, this.model.fields, param);
preparedParams[foreignColumnName] = convertParam(
property,
this.model.fields,
param,
);

// eslint-disable-next-line no-continue
continue;
}

if (property.isArray()) {
preparedParams[key] = param ? param.map((p) => convertParam(property, this.model.fields, p)) : param
preparedParams[key] = param
? param.map((p) => convertParam(property, this.model.fields, p))
: param;
} else {
preparedParams[key] = convertParam(property, this.model.fields, param)
preparedParams[key] = convertParam(property, this.model.fields, param);
}
}

return preparedParams;
}

private prepareReturnValues(params: Record<string, any>): Record<string, any> {
private prepareReturnValues(
params: Record<string, any>,
): Record<string, any> {
const preparedValues: Record<string, any> = {};

for (const property of this.properties()) {
Expand Down
Loading