Skip to content

Commit

Permalink
Fix ID field doesn't display
Browse files Browse the repository at this point in the history
  • Loading branch information
cregourd committed Oct 16, 2023
1 parent 18c9f04 commit 04091e1
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 63 deletions.
5 changes: 4 additions & 1 deletion packages/next-admin/src/components/DataTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export function DataTable({ columns, data, resource }: DataTableProps) {
manualSorting: true,
columns,
getCoreRowModel: getCoreRowModel(),
initialState: {
columnVisibility: { _accessorKey: false },
},
});

return (
Expand Down Expand Up @@ -64,7 +67,7 @@ export function DataTable({ columns, data, resource }: DataTableProps) {
className="cursor-pointer hover:bg-indigo-50"
onClick={() => {
router?.push({
pathname: `${basePath}/${resource}/${row.original.id}`,
pathname: `${basePath}/${resource}/${row.original._accessorKey}`,
});
}}
>
Expand Down
46 changes: 3 additions & 43 deletions packages/next-admin/src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { createRouter } from "next-connect";

import {
fillRelationInSchema,
findRelationInData,
flatRelationInData,
formatSearchFields,
formattedFormData,
Expand All @@ -26,7 +25,7 @@ import {
Select,
EditFieldsOptions,
} from "./types";
import { preparePrismaListRequest } from "./utils/prisma";
import { getMappedDataList } from "./utils/prisma";
import { validate } from "./utils/validator";

// Router
Expand Down Expand Up @@ -123,37 +122,7 @@ export const nextAdminRouter = async (

// List
const searchParams = new URLSearchParams(req.url!.split("?")[1]);
const prismaListRequest = preparePrismaListRequest(
resource,
searchParams,
options
);
let data: any[] = [];
let total: number;
let error = null;

try {
// @ts-expect-error
data = await prisma[resource].findMany(prismaListRequest);
// @ts-expect-error
total = await prisma[resource].count({
where: prismaListRequest.where,
});
} catch (e: any) {
const { skip, take, orderBy } = prismaListRequest;
// @ts-expect-error
data = await prisma[resource].findMany({
skip,
take,
orderBy,
});
// @ts-expect-error
total = await prisma[resource].count();
error = e.message ? e.message : e;
console.error(e);
}
data = await findRelationInData(data, dmmfSchema?.fields);

const { data, total, error } = await getMappedDataList(prisma, resource, dmmfSchema, options, searchParams);
return {
props: {
...defaultProps,
Expand Down Expand Up @@ -221,16 +190,7 @@ export const nextAdminRouter = async (
// Delete redirect, display the list (this is needed because next keeps the HTTP method on redirects)
if (resourceId === undefined && formData.action === "delete") {
const searchParams = new URLSearchParams(req.url!.split("?")[1]);
const prismaListRequest = preparePrismaListRequest(
resource,
searchParams,
options
);
// @ts-expect-error
let data = await prisma[resource].findMany(prismaListRequest);
data = await findRelationInData(data, dmmfSchema?.fields);
// @ts-expect-error
const total = await prisma[resource].count();
const { data, total } = await getMappedDataList(prisma, resource, dmmfSchema, options, searchParams);

return {
props: {
Expand Down
4 changes: 2 additions & 2 deletions packages/next-admin/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ export type ObjectField<T extends ModelName> = Prisma.TypeMap["model"][T]["paylo

export type Model<M extends ModelName, T extends never | number = never> = ScalarField<M> & {
[P in keyof ObjectField<M>]:
ObjectField<M>[P] extends { scalars: infer S } ? T extends never ? S : T
ObjectField<M>[P] extends { scalars: infer S } ? T extends never ? S : T
: ObjectField<M>[P] extends { scalars: infer S } | null ? T extends never ? S | null : T | null
: ObjectField<M>[P] extends { scalars: infer S }[] ? T extends never ? S[] : T[]
: never;
}

export type ModelWithoutRelationships<M extends ModelName> = Model<M, number>;
export type ModelWithoutRelationships<M extends ModelName> = Model<M, number>;

export type Field<P extends ModelName> = keyof Model<P>;

Expand Down
87 changes: 70 additions & 17 deletions packages/next-admin/src/utils/prisma.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Prisma } from "@prisma/client";
import { getPrismaModelForResource } from "./server";
import { Prisma, PrismaClient } from "@prisma/client";
import { findRelationInData, getPrismaModelForResource } from "./server";
import {
ListFieldsOptions,
ModelName,
Expand All @@ -18,21 +18,21 @@ export const createWherePredicate = (
) => {
return search
? {
OR: fieldsFiltered
?.filter((field) => field.kind === "scalar")
.map((field) => {
if (field.type === "String") {
return {
[field.name]: { contains: search, mode: "insensitive" },
};
}
if (field.type === "Int" && !isNaN(Number(search))) {
return { [field.name]: Number(search) };
}
return null;
})
.filter(Boolean),
}
OR: fieldsFiltered
?.filter((field) => field.kind === "scalar")
.map((field) => {
if (field.type === "String") {
return {
[field.name]: { contains: search, mode: "insensitive" },
};
}
if (field.type === "Int" && !isNaN(Number(search))) {
return { [field.name]: Number(search) };
}
return null;
})
.filter(Boolean),
}
: {};
};

Expand Down Expand Up @@ -66,6 +66,7 @@ export const preparePrismaListRequest = <M extends ModelName>(
const listKeys = Object.keys(list) as Array<keyof ListFieldsOptions<M>>;
select = listKeys.reduce((acc, column) => {
const field = model?.fields.find(({ name }) => name === column);
if (!list[column]?.display) return acc;
if (field?.kind === "object") {
if (!acc._count) acc._count = { select: {} };
acc._count.select = { ...acc._count.select, [column]: true };
Expand All @@ -76,6 +77,8 @@ export const preparePrismaListRequest = <M extends ModelName>(
return acc;
}, {} as Select<M>);

if (!select.id) select.id = true;

fieldsFiltered =
model?.fields.filter(
({ name }) => list[name as keyof ListFieldsOptions<M>]?.search
Expand All @@ -91,3 +94,53 @@ export const preparePrismaListRequest = <M extends ModelName>(
take: itemsPerPage,
};
};

export const getMappedDataList = async (prisma: PrismaClient, resource: ModelName, dmmfSchema: Prisma.DMMF.Model | undefined, options: NextAdminOptions, searchParams: URLSearchParams) => {
const prismaListRequest = preparePrismaListRequest(
resource,
searchParams,
options
);
let data: any[] = [];
let total: number;
let error = null;
try {
// @ts-expect-error
data = await prisma[resource].findMany(prismaListRequest);
// @ts-expect-error
total = await prisma[resource].count({
where: prismaListRequest.where,
});
} catch (e: any) {
const { skip, take, orderBy } = prismaListRequest;
// @ts-expect-error
data = await prisma[resource].findMany({
skip,
take,
orderBy,
});
// @ts-expect-error
total = await prisma[resource].count();
error = e.message ? e.message : e;
console.error(e);
}

data = await findRelationInData(data, dmmfSchema?.fields);


const isIdDisplayed = options?.model?.[resource]?.list?.fields.id?.display;

data.forEach((item) => {
const id = item.id;
if (!isIdDisplayed) {
delete item.id;
}
item._accessorKey = id;
});

return {
data,
total,
error,
};
};

0 comments on commit 04091e1

Please sign in to comment.