Skip to content

Commit

Permalink
Fix comment serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
dcramer committed May 18, 2023
1 parent ffbe3dd commit 0df17d5
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 14 deletions.
30 changes: 16 additions & 14 deletions apps/api/src/lib/serializers/comment.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
import { inArray } from "drizzle-orm";
import { Serializer } from ".";
import { Serializer, serialize } from ".";
import { db } from "../../db";
import { Comment, User, users } from "../../db/schema";
import { UserSerializer } from "./user";

export const CommentSerializer: Serializer<Comment> = {
attrs: async (itemList: Comment[], currentUser?: User) => {
const userList = await db
.select()
.from(users)
.where(
inArray(
users.id,
itemList.map((i) => i.createdById),
),
);
const usersById = Object.fromEntries(
(
await db
.select()
.from(users)
.where(
inArray(
users.id,
itemList.map((i) => i.createdById),
),
)
).map((u) => [u.id, u]),
(await serialize(UserSerializer, userList, currentUser)).map(
(data, index) => [userList[index].id, data],
),
);

return Object.fromEntries(
itemList.map((item) => {
return [
item.id,
{
createdBy: usersById[item.id],
createdBy: usersById[item.createdById],
},
];
}),
Expand All @@ -34,7 +36,7 @@ export const CommentSerializer: Serializer<Comment> = {
item: (item: Comment, attrs: Record<string, any>, currentUser?: User) => {
return {
id: `${item.id}`,
comments: item.comment,
comment: item.comment,
createdAt: item.createdAt,
createdBy: attrs.createdBy,
};
Expand Down
31 changes: 31 additions & 0 deletions apps/api/src/routes/listComments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { FastifyInstance } from "fastify";
import buildFastify from "../app";
import * as Fixtures from "../lib/test/fixtures";

let app: FastifyInstance;
beforeAll(async () => {
app = await buildFastify();

return async () => {
await app.close();
};
});

test("lists comments", async () => {
const comment = await Fixtures.Comment();
await Fixtures.Comment();

const response = await app.inject({
method: "GET",
url: "/comments",
query: {
tasting: `${comment.tastingId}`,
},
headers: DefaultFixtures.authHeaders,
});

expect(response).toRespondWith(200);
const { results } = JSON.parse(response.payload);
expect(results.length).toBe(1);
expect(results[0].id).toBe(`${comment.id}`);
});

0 comments on commit 0df17d5

Please sign in to comment.