Skip to content

Commit

Permalink
fix: resolves issue proto-less object validation (#6884)
Browse files Browse the repository at this point in the history
Due to `instanceof` comparison, object without prototype is mistaken for a privative value, throwing `TypeError: Cannot convert object to primitive value.` when trying to `.toString` said object (inside template string).

This mostly effects usage with `graphql` as `graphql-js`, [by design](graphql/graphql-js#504), creates objects by using Object.create(null).
This fix allows saving these objects.    

The fix uses `typeof` instead of `toString` comparison since I see no reason why `new Number/Boolean/Date` should be a supported use case.

Closes: #2065
  • Loading branch information
maayanbar13 committed Oct 12, 2020
1 parent 68bb9dc commit e08d9c6
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/persistence/EntityPersistExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class EntityPersistExecutor {
execute(): Promise<void> {

// check if entity we are going to save is valid and is an object
if (!this.entity || !(this.entity instanceof Object))
if (!this.entity || typeof this.entity !== "object")
return Promise.reject(new MustBeEntityError(this.mode, this.entity));

// we MUST call "fake" resolve here to make sure all properties of lazily loaded relations are resolved
Expand Down
17 changes: 17 additions & 0 deletions test/github-issues/2065/entity/Post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Entity, PrimaryColumn, Column } from "../../../../src";

@Entity()
export class Post {

@PrimaryColumn()
id: number;

@Column()
title: string;

constructor(id: number, title: string) {
this.id = id;
this.title = title;
}

}
23 changes: 23 additions & 0 deletions test/github-issues/2065/issue-2065.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import "reflect-metadata";
import {createTestingConnections, closeTestingConnections, reloadTestingDatabases} from "../../utils/test-utils";
import {Connection} from "../../../src/connection/Connection";
import {Post} from "./entity/Post";

describe("github issues > #2065 TypeError: Cannot convert object to primitive value", () => {

let connections: Connection[];
before(async () => connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
schemaCreate: true,
dropSchema: true,
}));
beforeEach(() => reloadTestingDatabases(connections));
after(() => closeTestingConnections(connections));

it("should save an entity created with Object.create(null)", () => Promise.all(connections.map(async connection => {
const post = Object.create(null) as Post;
post.id = 1;
post.title = "Hello Post";
await connection.manager.save(Post, post);
})));
});

0 comments on commit e08d9c6

Please sign in to comment.