Skip to content

Commit

Permalink
Merge pull request #548 from sinamics/api
Browse files Browse the repository at this point in the history
Return node data from controller as first priority.
  • Loading branch information
sinamics authored Sep 14, 2024
2 parents 314bb65 + a06772a commit 5fd0bee
Show file tree
Hide file tree
Showing 10 changed files with 160 additions and 192 deletions.
20 changes: 4 additions & 16 deletions src/components/networkByIdPage/table/memberEditCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,6 @@ const MemberEditCell = ({ nwid, central = false, organizationId }: IProp) => {
);

const { data: me } = api.auth.me.useQuery();
const { mutate: updateMemberDatabaseOnly } =
api.networkMember.UpdateDatabaseOnly.useMutation({
onError: handleApiError,
onSuccess: handleApiSuccess({
actions: [refetchNetworkById],
toastMessage: t(
"networkById.networkMembersTable.toastMessages.memberNameUpdated",
),
}),
});

const { mutate: updateMember } = api.networkMember.Update.useMutation({
onError: handleApiError,
Expand Down Expand Up @@ -86,14 +76,12 @@ const MemberEditCell = ({ nwid, central = false, organizationId }: IProp) => {

const submitName = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
updateMemberDatabaseOnly({
updateMember({
updateParams: { name: value as string },
memberId: original.id,
organizationId,
nwid,
id: original.id,
central,
organizationId,
updateParams: {
name: value as string,
},
});

inputRef.current?.blur();
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/__tests__/v1/network/network.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe("/api/createNetwork", () => {
status: jest.fn().mockReturnThis(),
end: jest.fn(),
json: jest.fn().mockReturnThis(),
setHeader: jest.fn(), // Mock `setHeader` rate limiter uses it
setHeader: jest.fn(),
} as unknown as NextApiResponse;

await apiNetworkHandler(req, res);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ jest.mock("~/utils/ztApi", () => {
return {
...originalModule,
member_update: jest.fn(),
member_details: jest.fn(),
};
});
describe("Update Network Members", () => {
Expand Down Expand Up @@ -105,11 +106,18 @@ describe("Update Network Members", () => {
networkMembers: [{ id: "memberId" }],
});

prisma.network_members.findUnique = jest.fn().mockResolvedValue({
id: "memberId",
authorized: false,
});

// mock the token
prisma.aPIToken.findUnique = jest.fn().mockResolvedValue({
expiresAt: new Date(),
});

(ztController.member_details as jest.Mock).mockResolvedValue([]);

const req = {
method: "POST",
headers: { "x-ztnet-auth": "validApiKey" },
Expand Down
44 changes: 28 additions & 16 deletions src/pages/api/v1/network/[id]/member/[memberId]/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const POST_updateNetworkMember = SecuredPrivateApiRoute(
const validatedInput = updateableFieldsMetaSchema.parse(body);

const updateableFields = {
name: { type: "string", destinations: ["database"] },
name: { type: "string", destinations: ["controller"] },
authorized: { type: "boolean", destinations: ["controller"] },
};

Expand Down Expand Up @@ -101,14 +101,9 @@ const POST_updateNetworkMember = SecuredPrivateApiRoute(
},
});

if (!network?.networkMembers || network.networkMembers.length === 0) {
return res
.status(401)
.json({ error: "Member or Network not found or access denied." });
}
const dbMember = network?.networkMembers?.[0];

if (Object.keys(databasePayload).length > 0) {
// if users click the re-generate icon on IP address
if (dbMember && Object.keys(databasePayload).length > 0) {
await ctx.prisma.network.update({
where: {
nwid: networkId,
Expand All @@ -119,7 +114,7 @@ const POST_updateNetworkMember = SecuredPrivateApiRoute(
where: {
id_nwid: {
id: memberId,
nwid: networkId, // this should be the value of `nwid` you are looking for
nwid: networkId,
},
},
data: {
Expand Down Expand Up @@ -149,15 +144,32 @@ const POST_updateNetworkMember = SecuredPrivateApiRoute(
});
}

// @ts-expect-error
const caller = appRouter.createCaller(ctx);
const networkAndMembers = await caller.networkMember.getMemberById({
nwid: networkId,
id: memberId,
});
// Fetch the latest data from both database and controller
const [updatedDbMember, controllerMember] = await Promise.all([
ctx.prisma.network_members.findUnique({
where: {
id_nwid: {
id: memberId,
nwid: networkId,
},
},
}),
// @ts-expect-error
ztController.member_details(ctx, networkId, memberId, false),
]);
if (!controllerMember) {
return res.status(404).json({ error: "Member not found in controller" });
}

return res.status(200).json(networkAndMembers);
// Merge the database and controller data
const mergedMember = {
...updatedDbMember,
...controllerMember,
};

return res.status(200).json(mergedMember);
} catch (cause) {
console.error(cause);
return handleApiErrors(cause, res);
}
},
Expand Down
41 changes: 21 additions & 20 deletions src/pages/api/v1/network/[id]/member/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,28 +40,29 @@ const GET_networkMembers = SecuredPrivateApiRoute(
},
async (_req, res, { networkId, ctx }) => {
try {
const arr = [];
const networks = await prisma.network.findUnique({
where: {
nwid: networkId,
},
include: {
networkMembers: true,
},
});
const controllerMember = await ztController.local_network_detail(
// @ts-expect-error: fake request object
ctx,
networkId,
false,
);

for (const member of networks.networkMembers) {
const controllerMember = await ztController.member_details(
//@ts-expect-error
ctx,
networkId,
member.id,
false,
);
arr.push({ ...member, ...controllerMember });
}
const networkMembers = await Promise.all(
controllerMember.members.map(async (member) => {
const dbMember = await prisma.network_members.findUnique({
where: {
id_nwid: {
nwid: member.nwid,
id: member.id,
},
},
});

return res.status(200).json(arr);
return { ...dbMember, ...member };
}),
);

return res.status(200).json(networkMembers);
} catch (cause) {
return handleApiErrors(cause, res);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export const POST_orgUpdateNetworkMember = SecuredOrganizationApiRoute(
where: {
id_nwid: {
id: memberId,
nwid: networkId, // this should be the value of `nwid` you are looking for
nwid: networkId,
},
},
data: {
Expand Down Expand Up @@ -225,14 +225,24 @@ export const GET_orgNetworkMemberById = SecuredOrganizationApiRoute(
const validatedContext = HandlerContextSchema.parse(context);
const { networkId, memberId, ctx } = validatedContext;

const controllerMember = await ztController.local_network_detail(
// @ts-expect-error: fake request object
ctx,
networkId,
false,
);

const findControllermemberById = controllerMember.members.find(
(member) => member.id === memberId,
);
// @ts-expect-error
const caller = appRouter.createCaller(ctx);
const networkAndMembers = await caller.networkMember.getMemberById({
nwid: networkId,
id: memberId,
});

return res.status(200).json(networkAndMembers);
return res.status(200).json({ ...networkAndMembers, ...findControllermemberById });
} catch (cause) {
return handleApiErrors(cause, res);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ test("updateDatabaseOnly test", async () => {
id: "12234",
updateParams: {
deleted: false,
name: "test name",
},
};

Expand All @@ -52,6 +51,7 @@ test("updateDatabaseOnly test", async () => {
wss: null,
res: null,
});

// @ts-expect-error -- awaiting fix:
prisma.network.update.mockResolvedValue(mockOutput);

Expand All @@ -68,7 +68,7 @@ test("updateDatabaseOnly test", async () => {
where: {
id_nwid: {
id: input.id,
nwid: input.nwid, // this should be the value of `nwid` you are looking for
nwid: input.nwid,
},
},
data: {
Expand Down
Loading

0 comments on commit 5fd0bee

Please sign in to comment.