Skip to content

Commit

Permalink
Mutualize props code
Browse files Browse the repository at this point in the history
  • Loading branch information
foyarash committed Nov 29, 2023
1 parent b540c8f commit 28efac1
Show file tree
Hide file tree
Showing 6 changed files with 322 additions and 355 deletions.
2 changes: 2 additions & 0 deletions apps/example/e2e/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export const createItem = async (
const url = new URL(page.url());
const id = url.pathname.split("/").pop();
expect(Number(id)).not.toBeNaN();
expect(page.getByText("Created successfully")).toBeDefined();
return id!;
};

Expand All @@ -75,6 +76,7 @@ export const updateItem = async (model: ModelName, page: Page, id: string) => {
await page.click('button:has-text("Submit")');
await page.waitForURL(`${process.env.BASE_URL}/${model}/*`);
await readForm(model, page, dataTestUpdate);
expect(page.getByText("Updated successfully")).toBeDefined();
};

export const fillForm = async (
Expand Down
160 changes: 8 additions & 152 deletions packages/next-admin/src/appRouter.ts
Original file line number Diff line number Diff line change
@@ -1,155 +1,11 @@
"use server";
import { PrismaClient } from "@prisma/client";
import {
ActionParams,
AdminComponentProps,
EditOptions,
NextAdminOptions,
Select,
SubmitFormResult,
} from "./types";
import {
fillRelationInSchema,
getPrismaModelForResource,
getResourceFromParams,
getResourceIdFromParam,
getResources,
transformData,
transformSchema,
} from "./utils/server";
import { getMappedDataList } from "./utils/prisma";
import qs from "querystring";
import { createBoundServerAction } from "./utils/actions";

export type GetPropsFromParamsParams = {
params?: string[];
searchParams: { [key: string]: string | string[] | undefined } | undefined;
options: NextAdminOptions;
schema: any;
prisma: PrismaClient;
action: (
params: ActionParams,
formData: FormData
) => Promise<SubmitFormResult | undefined>;
GetPropsFromParamsParams,
getPropsFromParams as _getPropsFromParams,
} from "./utils/props";

export const getPropsFromParams = (
params: Omit<GetPropsFromParamsParams, "isAppDir">
) => {
return _getPropsFromParams({ ...params, isAppDir: true });
};

export async function getPropsFromParams({
params,
searchParams,
options,
schema,
prisma,
action,
}: GetPropsFromParamsParams): Promise<
| AdminComponentProps
| Omit<AdminComponentProps, "dmmfSchema" | "schema" | "resource" | "action">
> {
const resources = getResources(options);

let message = undefined;

try {
message = searchParams?.message
? JSON.parse(searchParams.message as string)
: null;
} catch {}

const defaultProps = {
resources,
basePath: options.basePath,
isAppDir: true,
action: createBoundServerAction({ schema, params }, action),
message,
error: searchParams?.error as string,
};

if (!params) return defaultProps;

const resource = getResourceFromParams(params, resources);

if (!resource) return defaultProps;

switch (params.length) {
case 1: {
schema = await fillRelationInSchema(
schema,
prisma,
resource,
searchParams,
options
);

const { data, total, error } = await getMappedDataList(
prisma,
resource,
options,
new URLSearchParams(qs.stringify(searchParams)),
true
);

return {
...defaultProps,
resource,
data,
total,
error,
schema,
};
}
case 2: {
const resourceId = getResourceIdFromParam(params[1], resource);
const model = getPrismaModelForResource(resource);

let selectedFields = model?.fields.reduce(
(acc, field) => {
// @ts-expect-error
acc[field.name] = true;
return acc;
},
{ id: true } as Select<typeof resource>
);

const dmmfSchema = getPrismaModelForResource(resource);
const edit = options?.model?.[resource]?.edit as EditOptions<
typeof resource
>;
schema = transformSchema(schema, resource, edit);

if (resourceId !== undefined) {
const editDisplayedKeys = edit && edit.display;
const editSelect = editDisplayedKeys?.reduce(
(acc, column) => {
acc[column] = true;
return acc;
},
{ id: true } as Select<typeof resource>
);
selectedFields = editSelect ?? selectedFields;
// @ts-expect-error
let data = await prisma[resource].findUniqueOrThrow({
where: { id: resourceId },
select: selectedFields,
});
data = transformData(data, resource, edit);
return {
...defaultProps,
resource,
data,
schema,
dmmfSchema: dmmfSchema?.fields,
};
}

if (params[1] === "new") {
return {
...defaultProps,
resource,
schema,
dmmfSchema: dmmfSchema?.fields,
};
}
}
default:
return defaultProps;
}
}
Loading

0 comments on commit 28efac1

Please sign in to comment.