Skip to content

Commit

Permalink
fix: resolve issue with conversion string to simple-json (#4476)
Browse files Browse the repository at this point in the history
Closes: #4440
  • Loading branch information
abhijeet1403 authored and vlapo committed Aug 14, 2019
1 parent c321562 commit d1594f5
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/util/DateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,12 @@ export class DateUtils {
}

static stringToSimpleJson(value: any) {
return typeof value === "string" ? JSON.parse(value) : value;
try {
const simpleJSON = JSON.parse(value);
return (typeof simpleJSON === "object") ? simpleJSON : {};
} catch (err) {
return {};
}
}

static simpleEnumToString(value: any) {
Expand Down
16 changes: 16 additions & 0 deletions test/github-issues/4440/entity/Post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Column } from "../../../../src/decorator/columns/Column";
import { PrimaryColumn } from "../../../../src/decorator/columns/PrimaryColumn";
import { Entity } from "../../../../src/decorator/entity/Entity";

@Entity()
export class Post {
@PrimaryColumn()
id: number;

@Column({
type: "simple-json",
nullable: true
})
jsonField: any;

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

describe("github issues > #4440 simple-json column type throws error for string with no value", () => {

let connections: Connection[];
before(async () => {
connections = await createTestingConnections({
entities: [Post],
schemaCreate: true,
dropSchema: true
});
});
beforeEach(() => reloadTestingDatabases(connections));
after(() => closeTestingConnections(connections));

it("should correctly add retrieve simple-json field with no value", () =>
Promise.all(connections.map(async (connection) => {
const repo = connection.getRepository(Post);
const post = new Post();
post.id = 1;
post.jsonField = "";
await repo.save(post);
const postFound = await repo.findOne(1);
postFound!.id.should.eql(1);
postFound!.jsonField.should.eql({});
})));

it("should correctly add retrieve simple-json field with some value", () =>
Promise.all(connections.map(async (connection) => {
const repo = connection.getRepository(Post);
const post = new Post();
post.id = 1;
post.jsonField = {"key": "value"};
await repo.save(post);
const postFound = await repo.findOne(1);
postFound!.id.should.eql(1);
postFound!.jsonField.should.eql({"key": "value"});
})));

});

0 comments on commit d1594f5

Please sign in to comment.