Skip to content
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
8 changes: 8 additions & 0 deletions src/utils/serializer.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,17 @@ export class Helpers<PrimaryType extends Dictionary<any> = any> {
if (options.projection === undefined) {
this.projectAttributes = () => undefined;
} else if (options.projection === null) {
const relatorKeys = this.relators
? new Set(Object.keys(this.relators))
: undefined;
this.projectAttributes = (data: PrimaryType) => {
const attributes = { ...data };
delete attributes[options.idKey];
if (relatorKeys) {
for (const key of relatorKeys) {
delete attributes[key as keyof PrimaryType];
}
}
return attributes;
};
} else {
Expand Down
41 changes: 41 additions & 0 deletions test/issue-77.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Relator, Serializer } from "../lib";

describe("Issue #77 - Related fields should not appear in attributes", () => {
interface Article {
id: string;
title: string;
}

interface User {
articles: Article[];
id: string;
name: string;
}

const ArticleSerializer = new Serializer<Article>("Article");
const UserArticleRelator = new Relator<User, Article>(
async (user) => user.articles,
ArticleSerializer
);
const UserSerializer = new Serializer<User>("User", {
relators: [UserArticleRelator],
});

it("should exclude relator fields from attributes by default", async () => {
const user: User = {
id: "1",
name: "Foo",
articles: [
{ id: "1", title: "Article 1" },
{ id: "2", title: "Article 2" },
],
};

const document = await UserSerializer.serialize(user);
const data = document.data as any;

expect(data.attributes).not.toHaveProperty("Article");
expect(data.attributes).toHaveProperty("name", "Foo");
expect(data.relationships).toHaveProperty("Article");
});
});
2 changes: 0 additions & 2 deletions test/serializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,6 @@ describe("Serializer Tests", () => {
id: user.id,
attributes: {
createdAt: user.createdAt.toISOString(),
articles: user.articles,
comments: user.comments,
},
relationships: {
Expand Down Expand Up @@ -302,7 +301,6 @@ describe("Serializer Tests", () => {
id: user.id,
attributes: {
createdAt: user.createdAt.toISOString(),
articles: user.articles,
comments: user.comments,
},
relationships: {
Expand Down
Loading