From 5567586c7998120d2a906e544f5850a57ed117ff Mon Sep 17 00:00:00 2001 From: Samriddhi Date: Mon, 14 Feb 2022 20:31:20 +0530 Subject: [PATCH] docs: add javascript marshaling example (#635) --- docs/languages/JavaScript.md | 12 ++++- examples/README.md | 1 + .../javascript-generate-marshalling/README.md | 17 +++++++ .../__snapshots__/index.spec.ts.snap | 48 +++++++++++++++++++ .../index.spec.ts | 14 ++++++ .../javascript-generate-marshalling/index.ts | 33 +++++++++++++ .../package-lock.json | 10 ++++ .../package.json | 12 +++++ 8 files changed, 146 insertions(+), 1 deletion(-) create mode 100644 examples/javascript-generate-marshalling/README.md create mode 100644 examples/javascript-generate-marshalling/__snapshots__/index.spec.ts.snap create mode 100644 examples/javascript-generate-marshalling/index.spec.ts create mode 100644 examples/javascript-generate-marshalling/index.ts create mode 100644 examples/javascript-generate-marshalling/package-lock.json create mode 100644 examples/javascript-generate-marshalling/package.json diff --git a/docs/languages/JavaScript.md b/docs/languages/JavaScript.md index 1d407bb2f0..99ce66c9f0 100644 --- a/docs/languages/JavaScript.md +++ b/docs/languages/JavaScript.md @@ -6,6 +6,7 @@ There are special use-cases that each language supports; this document pertains - [Rendering complete models to a specific module system](#rendering-complete-models-to-a-specific-module-system) +- [Generate un/marshal functions for classes](#generate-unmarshal-functions-for-classes) @@ -14,4 +15,13 @@ In some cases you might need to render the complete models to a specific module Check out this [example for a live demonstration how to generate the complete JavaScript models to use ESM module system](../../examples/javascript-use-esm). -Check out this [example for a live demonstration how to generate the complete JavaScript models to use CJS module system](../../examples/javascript-use-cjs). \ No newline at end of file +Check out this [example for a live demonstration how to generate the complete JavaScript models to use CJS module system](../../examples/javascript-use-cjs). + + +## Generate un/marshal functions for classes + +Sometimes you want to use the models for data transfers, and while most cases would work out of the box, custom serializer functionality is needed for the advanced cases. If you generated the data models based on a JSON Schema document and you want the serialized data to validate against the schema, this functionality is REQUIRED. + +Here, this can be done by including the preset `JS_COMMON_PRESET` using the option `marshalling`. + +Check out this [example out for a live demonstration](../../examples/javascript-generate-marshalling). diff --git a/examples/README.md b/examples/README.md index 2a8c947537..30fb253ccf 100644 --- a/examples/README.md +++ b/examples/README.md @@ -25,6 +25,7 @@ This directory contains a series of self-contained examples that you can use as - [generate-javascript-models](./generate-javascript-models) - A basic example to generate JavaScript data models - [javascript-use-esm](./javascript-use-esm) - A basic example that generate the models to use ESM module system. - [javascript-use-cjs](./javascript-use-cjs) - A basic example that generate the models to use CJS module system. +- [javascript-generate-marshalling](./javascript-generate-marshalling) - A basic example of how to use the un/marshalling functionality of the javascript class. - [generate-java-models](./generate-java-models) - A basic example to generate Java data models. - [generate-go-models](./generate-go-models) - A basic example to generate Go data models - [include-custom-function](./include-custom-function) - A basic example where a custom function is included. diff --git a/examples/javascript-generate-marshalling/README.md b/examples/javascript-generate-marshalling/README.md new file mode 100644 index 0000000000..3238358bfc --- /dev/null +++ b/examples/javascript-generate-marshalling/README.md @@ -0,0 +1,17 @@ +# JavaScript Data Models with un/marshalling functionality + +A basic example of how to use the un/marshalling functionality of the javascript class. + +## How to run this example + +Run this example using: + +```sh +npm i && npm run start +``` + +If you are on Windows, use the `start:windows` script instead: + +```sh +npm i && npm run start:windows +``` diff --git a/examples/javascript-generate-marshalling/__snapshots__/index.spec.ts.snap b/examples/javascript-generate-marshalling/__snapshots__/index.spec.ts.snap new file mode 100644 index 0000000000..d55d967ddd --- /dev/null +++ b/examples/javascript-generate-marshalling/__snapshots__/index.spec.ts.snap @@ -0,0 +1,48 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Should be able to generate ts data model with marshal und unmarshal functions and should log expected output to console 1`] = ` +Array [ + "class Test { + email; + + constructor(input) { + if (input.hasOwnProperty('email')) { + this.email = input.email; + } + } + + get email() { return this.email; } + set email(email) { this.email = email; } + + marshal(){ + let json = '{' + if(this.email !== undefined) { + json += \`\\"email\\": \${typeof this.email === 'number' || typeof this.email === 'boolean' ? this.email : JSON.stringify(this.email)},\`; + } + + + + //Remove potential last comma + return \`\${json.charAt(json.length-1) === ',' ? json.slice(0, json.length-1) : json}}\`; + } + + unmarshal(json){ + const obj = typeof json === \\"object\\" ? json : JSON.parse(json); + const instance = new Test({}); + + if (obj[\\"email\\"] !== undefined) { + instance.email = obj[\\"email\\"]; + } + + //Not part of core properties + + + for (const [key, value] of Object.entries(obj).filter((([key,]) => {return ![\\"email\\"].includes(key);}))) { + + + } + return instance; + } +}", +] +`; diff --git a/examples/javascript-generate-marshalling/index.spec.ts b/examples/javascript-generate-marshalling/index.spec.ts new file mode 100644 index 0000000000..f279d13040 --- /dev/null +++ b/examples/javascript-generate-marshalling/index.spec.ts @@ -0,0 +1,14 @@ +const spy = jest.spyOn(global.console, 'log').mockImplementation(() => { return; }); +import { generate } from './index'; + +describe('Should be able to generate ts data model with marshal und unmarshal functions', () => { + afterAll(() => { + jest.restoreAllMocks(); + }); + test('and should log expected output to console', async () => { + await generate(); + //Generate is called 2x, so even though we expect 1 model, we double it + expect(spy.mock.calls.length).toEqual(2); + expect(spy.mock.calls[1]).toMatchSnapshot(); + }); +}); diff --git a/examples/javascript-generate-marshalling/index.ts b/examples/javascript-generate-marshalling/index.ts new file mode 100644 index 0000000000..dfdc5e2826 --- /dev/null +++ b/examples/javascript-generate-marshalling/index.ts @@ -0,0 +1,33 @@ +import { JavaScriptGenerator } from '../../src'; +import { JS_COMMON_PRESET } from '../../src'; + +const generator = new JavaScriptGenerator({ + presets: [ + { + preset: JS_COMMON_PRESET, + options: { + marshalling: true + } + } + ] +}); +const jsonSchemaDraft7 = { + $schema: 'http://json-schema.org/draft-07/schema#', + $id: 'Test', + type: 'object', + additionalProperties: false, + properties: { + email: { + type: 'string', + format: 'email' + } + } +}; + +export async function generate(): Promise { + const models = await generator.generate(jsonSchemaDraft7); + for (const model of models) { + console.log(model.result); + } +} +generate(); diff --git a/examples/javascript-generate-marshalling/package-lock.json b/examples/javascript-generate-marshalling/package-lock.json new file mode 100644 index 0000000000..2c120e1672 --- /dev/null +++ b/examples/javascript-generate-marshalling/package-lock.json @@ -0,0 +1,10 @@ +{ + "name": "javascript-interface", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "hasInstallScript": true + } + } +} \ No newline at end of file diff --git a/examples/javascript-generate-marshalling/package.json b/examples/javascript-generate-marshalling/package.json new file mode 100644 index 0000000000..bbdc05acb0 --- /dev/null +++ b/examples/javascript-generate-marshalling/package.json @@ -0,0 +1,12 @@ +{ + "config": { + "example_name": "javascript-generate-marshalling" + }, + "scripts": { + "install": "cd ../.. && npm i", + "start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts", + "start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts", + "test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts", + "test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts" + } +} \ No newline at end of file