Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: resolve issue with conversion string to simple-json #4476

Merged
merged 9 commits into from Aug 14, 2019
7 changes: 6 additions & 1 deletion src/util/DateUtils.ts
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
@@ -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
@@ -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"});
})));

});