Skip to content

Commit

Permalink
feat: ignore json parse error if jsonType.ignoreError is positive (#409)
Browse files Browse the repository at this point in the history
  • Loading branch information
cyjake authored Nov 9, 2023
1 parent 834c80b commit 4c76447
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"prepack": "tsc && npm run copy-dts",
"prepack:browser": "rm -rf dist && tsc -p tsconfig.browser.json && npm run copy-dts:browser",
"prepublishOnly": "npm run prepack && npm run prepack:browser",
"pretest": "npm run prepack && ./test/prepare.sh",
"pretest": "./test/prepare.sh",
"test": "./test/start.sh",
"test:local": "./test/start.sh",
"test:unit": "./test/start.sh unit",
Expand Down
7 changes: 5 additions & 2 deletions src/data_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,9 +421,12 @@ class BLOB extends DataType {

// JSON text type
class MYJSON extends DataType {
constructor() {
ignoreError: boolean;

constructor({ ignoreError = false }: { ignoreError?: boolean } = {}) {
super();
this.dataType = 'text';
this.ignoreError = ignoreError;
}

toSqlString() {
Expand All @@ -441,7 +444,7 @@ class MYJSON extends DataType {
try {
return global.JSON.parse(value);
} catch (err) {
console.error(new Error(`unable to cast ${value} to JSON`));
if (!this.ignoreError) console.error(new Error(`unable to cast ${value} to JSON`));
return value;
}
}
Expand Down
11 changes: 11 additions & 0 deletions test/unit/data_types.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const assert = require('assert').strict;
const dayjs = require('dayjs');
const sinon = require('sinon');
const { default: DataTypes } = require('../../src/data_types');
const Raw = require('../../src/raw').default;
const Postgres_DataTypes = require('../../src/drivers/postgres/data_types');
Expand Down Expand Up @@ -113,6 +114,16 @@ describe('=> Data Types', () => {
// JSON type is actually stored as TEXT
assert.equal(new JSON().dataType, 'text');
assert.equal(new JSON().toSqlString(), 'TEXT');
assert.equal(new JSON().cast('invalid json text'), 'invalid json text');

const sandbox = sinon.createSandbox();
sandbox.spy(console, 'error');
try {
assert.equal(new JSON({ ignoreError: true }).cast('invalid json text'), 'invalid json text');
assert.ok(console.error.notCalled);
} finally {
sandbox.restore();
}
});

it('JSONB', () => {
Expand Down

0 comments on commit 4c76447

Please sign in to comment.