diff --git a/src/document/document.ts b/src/document/document.ts index 36e0fd2bc..98f24918e 100644 --- a/src/document/document.ts +++ b/src/document/document.ts @@ -363,7 +363,7 @@ export class Document implements Observable { /** * `getRoot` returns a new proxy of cloned root. */ - public getRoot(): T { + public getRoot(): JSONObject { this.ensureClone(); const context = ChangeContext.create(this.changeID.next(), this.clone!); @@ -401,14 +401,14 @@ export class Document implements Observable { } /** - * `toJSON` returns the JSON encoding of this array. + * `toJSON` returns the JSON encoding of this document. */ public toJSON(): string { return this.root.toJSON(); } /** - * `toJSON` returns the sorted JSON encoding of this array. + * `toSortedJSON` returns the sorted JSON encoding of this document. */ public toSortedJSON(): string { return this.root.toSortedJSON(); diff --git a/src/document/json/object.ts b/src/document/json/object.ts index 75d405975..1ed9f8fb2 100644 --- a/src/document/json/object.ts +++ b/src/document/json/object.ts @@ -48,6 +48,11 @@ export type JSONObject = { * `toJSON` returns the JSON encoding of this object. */ toJSON?(): string; + + /** + * `toJS` returns the JSON object of this object. + */ + toJS?(): T; } & T; /** @@ -96,6 +101,10 @@ export class ObjectProxy { return (): string => { return target.toJSON(); }; + } else if (keyOrMethod === 'toJS') { + return (): object => { + return target.toJS(); + }; } return toJSONElement(context, target.get(keyOrMethod)); diff --git a/test/integration/object_test.ts b/test/integration/object_test.ts index 22e4bb7ab..c7f7d704c 100644 --- a/test/integration/object_test.ts +++ b/test/integration/object_test.ts @@ -1,4 +1,5 @@ import { assert } from 'chai'; +import { JSONObject } from '@yorkie-js-sdk/src/yorkie'; import { DocEventType, Document } from '@yorkie-js-sdk/src/document/document'; import { withTwoClientsAndDocuments } from '@yorkie-js-sdk/test/integration/integration_helper'; @@ -76,6 +77,22 @@ describe('Object', function () { assert.equal('{"k1":{"k1-2":"v2","k1-3":"v4"}}', doc.toSortedJSON()); }); + it('should support toJS and toJSON methods', function () { + const doc = Document.create<{ + content: JSONObject<{ a: number; b: number; c: number }>; + }>('test-doc'); + doc.update((root) => { + root.content = { a: 1, b: 2, c: 3 }; + }, 'set a, b, c'); + assert.equal(doc.toSortedJSON(), '{"content":{"a":1,"b":2,"c":3}}'); + + const root = doc.getRoot(); + assert.equal(root.toJSON!(), '{"content":{"a":1,"b":2,"c":3}}'); + assert.deepEqual(root.toJS!(), { content: { a: 1, b: 2, c: 3 } }); + assert.equal(root.content.toJSON!(), '{"a":1,"b":2,"c":3}'); + assert.deepEqual(root.content.toJS!(), { a: 1, b: 2, c: 3 }); + }); + it('Object.keys, Object.values and Object.entries test', function () { const doc = Document.create<{ content: { a: number; b: number; c: number };